feat(wasm): route D zero-author-JS frontend + plan route E

Auto-mount via bridge mount/data-mq and client_embed; expand DOM/form
effects; drop hello loader JS; add web-client-site. Document that C+D
cover mid-size interactivity but not most JS apps—route E covers
routing, storage, lists, WebSocket, and richer DOM/timers.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-04 08:46:05 +08:00
1 parent 4c27c8afeb
commit a9d30cdf4a
30 files changed
+1769 -213

No files matched your search

+4 -4
View File
@@ -29,7 +29,7 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.
7. **Paths:** In bare *expressions* `/` is division. In **call args / param defaults / table cells**, unspaced `a/b` and quoted `".marqdo/agent-kb"` are path text — no `json.parse` needed. Numeric ratios that must stay text use quotes (`"1/5"`, `"16/9"`); bare `1/5` is division.
8. Prefer ending side-effect-only function bodies with a lone `---` or `***` line (or `****` empty return) so later siblings are not swallowed.
9. **`ext/**` never calls `host_*`.** Agent/OKF helpers are plugin names (`agent_kb_*`, …) after `plugin.load`. Do **not** add agent/OKF domain code to `src/host/` (core bloat). See `doc/design/ext-agent.md` §4.
10. **Browser (route C):** client logic is Marqdo on WASM ([ADR 0002](../../../doc/adr/0002-browser-marqdo-wasm.md)); async I/O via return effects `fetch`/`after` ([ADR 0003](../../../doc/adr/0003-browser-async-effects.md)); official bridge is host glue only.
10. **Browser (route C/D):** client logic is Marqdo on WASM ([ADR 0002](../../../doc/adr/0002-browser-marqdo-wasm.md)); async I/O via return effects `fetch`/`after` ([ADR 0003](../../../doc/adr/0003-browser-async-effects.md)); official bridge is **host glue only**. **Author zero business JS** — use `web.client_embed` / `网页.客户端挂载` (`wasm` + `source` + `boot`) or `data-mq-source-url` so bridge `mount`s automatically ([roadmap D](../../../doc/roadmap/browser-wasm-d.md)). DOM effects: `set_text` / `set_value` / `set_attr` / `set_class` / `toggle_class` / `set_html` only on `#trusted*` selectors.
## Markup → meaning (v0.2)
@@ -175,11 +175,11 @@ data/ # sqlite runtime (gitignore)
**Core objects (EN / ZH):** `# page`/`页面`, `# style`/`样式`, `# db`/`数据库`, `# form`/`表单`, `# app`/`应用`, `# auth`/`鉴权`, `# cache`/`缓存`, `# storage`/`存储`.
**Typical flow:** `db.init` → `page.compose_components` + `page.compose_main` → `page.head` / `page.images` / `page.meta` → `app` with `route` / `static` / `icons` / `configure` / `listen`.
**Typical flow:** `db.init` → `page.compose_components` + `page.compose_main` → `page.head` / `page.images` / `page.meta` → `app` with `route` / `static` / `icons` / `configure` / `listen`. For client interactivity: `marqdo wasm build -o static`, then `web.client_embed source="/static/client.mq.md"` (or ZH `网页.客户端挂载`) in page HTML — **no author JS** ([browser-wasm-d.md](../../doc/roadmap/browser-wasm-d.md) · [web-client-site](../../examples/web-client-site/)).
**Shipped surface (W0–W7 + P3 + W8):** middleware + JSON API (`app.configure`); transactions, pagination, FTS search (`db.migrate`, `db.fts`, `db.search`); security (argon2, CSRF, SQLite sessions, login rate limit); SEO / RSS / Markdown (`page.meta`, `route_rss`, `lib/net.markdown_parse`); upload / download / gallery; sitemap / robots / error pages / redirects; RBAC (`app.gate`, user `role`); audit timestamps + FK in `db.init`; ETag on downloads; **W8** site icons (`app.icons` → `/favicon.ico`), head resource tables (`page.head`), image assembly (`make_images` / `page.images`).
**Shipped surface (W0–W7 + P3 + W8 + route D mount):** middleware + JSON API (`app.configure`); transactions, pagination, FTS search (`db.migrate`, `db.fts`, `db.search`); security (argon2, CSRF, SQLite sessions, login rate limit); SEO / RSS / Markdown (`page.meta`, `route_rss`, `lib/net.markdown_parse`); upload / download / gallery; sitemap / robots / error pages / redirects; RBAC (`app.gate`, user `role`); audit timestamps + FK in `db.init`; ETag on downloads; **W8** site icons (`app.icons` → `/favicon.ico`), head resource tables (`page.head`), image assembly (`make_images` / `page.images`); **D** `client_embed` auto-mount + DOM effect helpers (`text_patch` / `dom_patch`).
Design: [ext-web.md](../../doc/design/ext-web.md) · assets: [web-assets-and-images.md](../../doc/design/web-assets-and-images.md) · capability matrix: [web-net-capabilities.md](../../doc/design/web-net-capabilities.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/).
Design: [ext-web.md](../../doc/design/ext-web.md) · assets: [web-assets-and-images.md](../../doc/design/web-assets-and-images.md) · capability matrix: [web-net-capabilities.md](../../doc/design/web-net-capabilities.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/) · client: [examples/web-client-site/](../../examples/web-client-site/).
Web patterns: [examples.md](examples.md) §13 · API index: [reference.md](reference.md).
+1
View File
@@ -42,6 +42,7 @@ spike/.pytest_cache/
# Built browser WASM (rebuild via crates/marqdo-wasm README)
/examples/browser-hello/marqdo_wasm.wasm
/examples/browser-hello/pkg/
/examples/web-client-site/static/marqdo_wasm.wasm
# Local sqlite / scratch
/data/
+2
View File
@@ -3,6 +3,8 @@
## Unreleased
### Added
- **路线 D(作者零 JS)**:[roadmap](doc/roadmap/browser-wasm-d.md) · 设计 §16。官方 bridge `mount` / `data-mq-*` 自启;`client_embed` 带 `wasm`/`source`/`boot`;DOM 效应 `set_value`/`set_attr`/`set_class`/`toggle_class`/`set_html(#trusted…)`;wire 传 `value`/`fields`;示例去业务 JS;`examples/web-client-site/`。
- **路线 E(规划)**:[browser-wasm-e.md](doc/roadmap/browser-wasm-e.md) — 路由 / 存储 / 列表片段 / WebSocket / DOM·定时补齐;C+D **尚不能**替代大部分前端 JS。
### Fixed
+1 -1
View File
@@ -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`
- **浏览器 Marqdo(WASM)**:`marqdo wasm build` + 官方 bridge;示例 [browser-hello](examples/browser-hello/);站点挂载 `web.client_embed` / `网页.客户端挂载`([ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [ADR 0003](doc/adr/0003-browser-async-effects.md))
- **浏览器 Marqdo(WASM)**:`marqdo wasm build` + 官方 bridge **自启**(路线 D 作者零业务 JS);`web.client_embed` / `网页.客户端挂载`;示例 [browser-hello](examples/browser-hello/) · [web-client-site](examples/web-client-site/)([ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [ADR 0003](doc/adr/0003-browser-async-effects.md) · [路线 D](doc/roadmap/browser-wasm-d.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.2)
+342 -6
View File
@@ -1,11 +1,13 @@
/**
* Canonical Marqdo browser bridge (route C). Host glue only — not app logic.
* Canonical Marqdo browser bridge (route C/D). 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
* Effects (ADR 0003 + route D): set_text, set_value, set_attr, set_class,
* toggle_class, set_html (#trusted* only), fetch, after
* Mount: mount() / data-mq-* / #marqdo-boot auto-start (author zero JS)
*/
export function readCString(memory, ptr) {
@@ -67,16 +69,196 @@ export async function loadWasm(url = "./marqdo_wasm.wasm") {
return instance.exports;
}
/** Apply C3/C4 return effects: set_text, fetch, after */
function isPlainObject(v) {
return v != null && typeof v === "object" && !Array.isArray(v);
}
/** Normalize mount options from plain object or DOM dataset. */
export function normalizeMountOptions(raw = {}) {
const o = raw && typeof raw === "object" ? raw : {};
const dataset = o.dataset || {};
const wasmUrl =
o.wasmUrl ||
o.wasm ||
dataset.mqWasm ||
dataset.wasm ||
"./marqdo_wasm.wasm";
const sourceUrl =
o.sourceUrl ||
o.source_url ||
dataset.mqSourceUrl ||
dataset.sourceUrl ||
"";
let source = o.source != null ? o.source : dataset.mqSource || "";
if (!source && typeof o.sourceInline === "string") source = o.sourceInline;
const playground =
o.playground ||
dataset.mqPlayground ||
dataset.playground ||
"";
const ready =
o.ready ||
o.readySel ||
dataset.mqReady ||
"";
const enable =
o.enable ||
dataset.mqEnable ||
"";
const noBoot =
o.noBoot === true ||
dataset.mqNoBoot === "1" ||
dataset.mqNoBoot === "true";
return {
wasmUrl: String(wasmUrl),
sourceUrl: sourceUrl ? String(sourceUrl) : "",
source: source ? String(source) : "",
playground: playground ? String(playground) : "",
ready: ready ? String(ready) : "",
enable: enable ? String(enable) : "",
noBoot,
onError: typeof o.onError === "function" ? o.onError : null,
};
}
/**
* Collect mount configs from `#marqdo-boot` JSON and `script[data-mq-*]`.
* Pure DOM scan — safe to call once after DOM ready.
*/
export function collectMountConfigs(doc = typeof document !== "undefined" ? document : null) {
if (!doc) return [];
const out = [];
const bootEl = doc.getElementById("marqdo-boot");
if (bootEl) {
try {
const json = JSON.parse(bootEl.textContent || "{}");
out.push(normalizeMountOptions(json));
} catch (e) {
console.error("marqdo-boot JSON:", e);
}
}
const scripts = doc.querySelectorAll(
"script[data-mq-source-url], script[data-mq-source], script[data-mq-playground], script[data-mq-wasm]",
);
for (const el of scripts) {
if (el.dataset.mqNoBoot === "1" || el.dataset.mqNoBoot === "true") continue;
const hasWork =
el.dataset.mqSourceUrl ||
el.dataset.mqSource ||
el.dataset.mqPlayground;
if (!hasWork && !el.dataset.mqWasm) continue;
if (!hasWork) continue;
out.push(
normalizeMountOptions({
dataset: el.dataset,
wasmUrl: el.dataset.mqWasm,
sourceUrl: el.dataset.mqSourceUrl,
source: el.dataset.mqSource,
playground: el.dataset.mqPlayground,
ready: el.dataset.mqReady,
enable: el.dataset.mqEnable,
}),
);
}
return out;
}
/** Build mq_call args from a DOM event + optional value_from selector. */
export function eventArgsFromDom(ev, valueFromSel) {
const t = ev && ev.target;
const args = {
event: ev && ev.type ? ev.type : "click",
};
if (t && typeof t === "object") {
if ("value" in t && t.value != null) args.value = String(t.value);
if ("checked" in t) args.checked = !!t.checked;
if (t.id) args.id = String(t.id);
if (typeof t.textContent === "string" && !("value" in t)) {
args.text = t.textContent;
}
}
if (valueFromSel && typeof document !== "undefined") {
const src = document.querySelector(valueFromSel);
if (src) {
if ("value" in src) args.value = String(src.value);
else args.value = src.textContent != null ? String(src.textContent) : "";
}
}
if (ev && ev.type === "submit" && t) {
const form = typeof t.closest === "function" ? t.closest("form") : t;
if (form && typeof FormData !== "undefined") {
try {
ev.preventDefault();
} catch (_) {
/* ignore */
}
const fields = {};
for (const [k, v] of new FormData(form)) {
fields[k] = String(v);
}
args.fields = fields;
}
}
return args;
}
/** Apply C3/C4/D3 return effects: DOM patches then fetch/after. */
export function applyDomPatch(value) {
if (!value || typeof value !== "object") return;
if (typeof document === "undefined") return;
const setText = value.set_text || value.setText;
if (setText && typeof setText === "object") {
if (isPlainObject(setText)) {
for (const [sel, text] of Object.entries(setText)) {
const el = document.querySelector(sel);
if (el) el.textContent = String(text);
}
}
const setValue = value.set_value || value.setValue;
if (isPlainObject(setValue)) {
for (const [sel, v] of Object.entries(setValue)) {
const el = document.querySelector(sel);
if (el && "value" in el) el.value = String(v);
}
}
const setAttr = value.set_attr || value.setAttr;
if (isPlainObject(setAttr)) {
for (const [sel, attrs] of Object.entries(setAttr)) {
const el = document.querySelector(sel);
if (!el || !isPlainObject(attrs)) continue;
for (const [name, raw] of Object.entries(attrs)) {
if (raw === null || raw === false) el.removeAttribute(name);
else el.setAttribute(name, String(raw));
}
}
}
const setClass = value.set_class || value.setClass;
if (isPlainObject(setClass)) {
for (const [sel, cls] of Object.entries(setClass)) {
const el = document.querySelector(sel);
if (el) el.className = String(cls);
}
}
const toggleClass = value.toggle_class || value.toggleClass;
if (isPlainObject(toggleClass)) {
for (const [sel, cls] of Object.entries(toggleClass)) {
const el = document.querySelector(sel);
if (el && cls) el.classList.toggle(String(cls));
}
}
const setHtml = value.set_html || value.setHtml;
if (isPlainObject(setHtml)) {
for (const [sel, html] of Object.entries(setHtml)) {
if (!String(sel).startsWith("#trusted")) continue;
const el = document.querySelector(sel);
if (el) el.innerHTML = String(html);
}
}
}
/**
@@ -180,12 +362,15 @@ export function wireEvents(exports, bootValue, { onError } = {}) {
const sel = row["选择器"] || row.selector || row.sel;
const ev = row["事件"] || row.event || "click";
const fn = row["调用"] || row.call || row.fn;
const valueFrom =
row["值选择器"] || row.value_from || row.valueFrom || row.from || "";
if (!sel || !fn) continue;
const nodes = document.querySelectorAll(sel);
nodes.forEach((node) => {
node.addEventListener(ev, () => {
node.addEventListener(ev, (domEv) => {
try {
const result = call(exports, fn, { event: ev });
const args = eventArgsFromDom(domEv, valueFrom);
const result = call(exports, fn, args);
if (!result.ok) {
if (onError) onError(result.error);
else console.error(result.error);
@@ -202,3 +387,154 @@ export function wireEvents(exports, bootValue, { onError } = {}) {
}
return rows.length;
}
function markReady(opts, message) {
if (opts.ready && typeof document !== "undefined") {
const el = document.querySelector(opts.ready);
if (el) {
el.classList?.remove?.("err");
el.textContent = message;
}
}
if (opts.enable && typeof document !== "undefined") {
for (const sel of String(opts.enable).split(",")) {
const s = sel.trim();
if (!s) continue;
document.querySelectorAll(s).forEach((n) => {
n.disabled = false;
n.removeAttribute("disabled");
});
}
}
}
function markError(opts, err) {
const msg = String(err);
if (opts.onError) opts.onError(msg);
if (opts.ready && typeof document !== "undefined") {
const el = document.querySelector(opts.ready);
if (el) {
el.classList?.add?.("err");
el.textContent = msg;
}
} else {
console.error(msg);
}
}
function wirePlayground(exports, playgroundSpec, { onError } = {}) {
const parts = String(playgroundSpec)
.split(",")
.map((s) => s.trim())
.filter(Boolean);
const sourceSel = parts[0] || "#src";
const runSel = parts[1] || "#run";
const outSel = parts[2] || "#out";
const runBtn = document.querySelector(runSel);
const src = document.querySelector(sourceSel);
const out = document.querySelector(outSel);
if (!runBtn || !src) return 0;
runBtn.disabled = false;
runBtn.removeAttribute("disabled");
runBtn.addEventListener("click", () => {
try {
const result = runSource(exports, src.value || "");
if (out) {
out.classList?.toggle?.("err", !result.ok);
out.textContent = result.ok
? (result.stdout || "(empty stdout)") +
(result.value != null && result.value !== "None"
? `\n[return] ${typeof result.value === "string" ? result.value : JSON.stringify(result.value)}`
: "")
: result.error || "error";
}
} catch (e) {
if (onError) onError(String(e));
else if (out) {
out.classList?.add?.("err");
out.textContent = String(e);
}
}
});
return 1;
}
/**
* One-shot: load wasm, boot session (or playground), wire events.
* @returns {{ exports, boot, wired }}
*/
export async function mount(rawOpts = {}) {
const opts = normalizeMountOptions(rawOpts);
const onError = (err) => markError(opts, err);
let exports;
try {
exports = await loadWasm(opts.wasmUrl);
} catch (e) {
onError(e);
throw e;
}
const ver = readCString(exports.memory, exports.mq_version());
if (opts.playground) {
const n = wirePlayground(exports, opts.playground, { onError });
markReady(opts, `marqdo-wasm ${ver} · playground ready`);
return { exports, boot: null, wired: n };
}
let source = opts.source;
if (!source && opts.sourceUrl) {
const res = await fetch(opts.sourceUrl);
if (!res.ok) {
const err = `failed to load ${opts.sourceUrl} (${res.status})`;
onError(err);
throw new Error(err);
}
source = await res.text();
}
if (!source) {
const err = "mount: need source, sourceUrl, or playground";
onError(err);
throw new Error(err);
}
const result = boot(exports, source);
if (!result.ok) {
onError(result.error || "boot failed");
throw new Error(result.error || "boot failed");
}
// If boot value is a map with effects alongside wire, apply them.
if (result.value && !Array.isArray(result.value)) {
await applyEffects(exports, result.value, { onError });
}
const n = wireEvents(exports, result.value, { onError });
const srcLabel = opts.sourceUrl || "(inline)";
markReady(opts, `marqdo-wasm ${ver} · wired ${n} handler(s)\nsource: ${srcLabel}`);
return { exports, boot: result, wired: n };
}
/** Auto-mount from DOM configs (route D). */
export async function autoMount(doc) {
const configs = collectMountConfigs(doc);
const results = [];
for (const cfg of configs) {
if (cfg.noBoot) continue;
results.push(await mount(cfg));
}
return results;
}
const g = typeof globalThis !== "undefined" ? globalThis : undefined;
if (g && g.document) {
const start = () => {
autoMount(g.document).catch((e) => console.error("marqdo autoMount:", e));
};
if (g.document.readyState === "loading") {
g.document.addEventListener("DOMContentLoaded", start);
} else {
queueMicrotask(start);
}
}
+4 -1
View File
@@ -59,7 +59,10 @@
| [roadmap/object-inheritance.md](roadmap/object-inheritance.md) | **对象继承**(`# 子类 = > 父类`;I0–I2 已落地) |
| [roadmap/tables-maps-footnotes.md](roadmap/tables-maps-footnotes.md) | **表格语义**(竖表 / 横表字典 / 脚注取元 / 行向记录 / **单元格表达式 T5**) |
| [design/table-cell-expressions.md](design/table-cell-expressions.md) | **表数据单元格 = 表达式**(同调用实参值语法;Accepted) |
| [roadmap/ext-web.md](roadmap/ext-web.md) | **实现路线:`ext/web`**(W0–W4;设计见 [ext-web.md](../design/ext-web.md)) |
| [roadmap/browser-wasm.md](roadmap/browser-wasm.md) | **浏览器 WASM 路线 C(C0–C5 Completed)** |
| [roadmap/browser-wasm-d.md](roadmap/browser-wasm-d.md) | **路线 D:作者零 JS 前端(Completed)** |
| [roadmap/browser-wasm-e.md](roadmap/browser-wasm-e.md) | **路线 E:前端能力补齐(Planned)** |
| [design/browser-marqdo-wasm.md](design/browser-marqdo-wasm.md) | **浏览器 Marqdo(WASM)设计** |
| [roadmap/ext-quantum.md](roadmap/ext-quantum.md) | **规划:`ext/quantum` 量子模拟**(基础门·电路·ABI·`ext add`) |
| [research/okf-and-marqdo.md](research/okf-and-marqdo.md) | OKF 调研 |
| [research/agent-frameworks-and-marqdo.md](research/agent-frameworks-and-marqdo.md) | 主流智能体框架 vs Marqdo 优势 |
+68
View File
@@ -299,6 +299,74 @@ marqdo wasm build -o static # marqdo_wasm.wasm + marqdo-bridge.js
---
## 16. 路线 D — 作者零 JS(Active)
路线图:[browser-wasm-d.md](../roadmap/browser-wasm-d.md)。
**原则:** 业务与交互 100% `.mq.md`;`marqdo-bridge.js` 仅宿主胶。作者仓库可不含自写 `.js`。
### 16.1 一键挂载
| API | 含义 |
|-----|------|
| `mount({ wasmUrl, source \| sourceUrl, … })` | `loadWasm` → `boot` → `wireEvents` → 初始效应 |
| `script[data-mq-source-url]` / `data-mq-wasm` | 模块脚本属性自启 |
| `#marqdo-boot` | `application/json` 配置块 |
| `data-mq-playground` | 官方 playground(`#src,#run,#out`),仍非业务 JS |
`ext/web`:`client_embed` / `客户端挂载` 参数 `bridge`、`wasm`、`source`、`boot`(默认 true)。
```bash
marqdo wasm build -o static # marqdo_wasm.wasm + marqdo-bridge.js
# app.static dir=static
# intro 或主区嵌入 > web.client_embed source="/static/client.mq.md"
```
### 16.2 DOM / 表单效应(D3)
与 `set_text` / `fetch` / `after` 并列(白名单;**默认无**任意脚本注入):
| 字段 | 作用 |
|------|------|
| `set_text` | `textContent` |
| `set_value` | input/textarea/select 的 `value` |
| `set_attr` | 属性;值为 `null`/`false` 则 `removeAttribute` |
| `set_class` | `className` 字符串 |
| `toggle_class` | `{ "#sel": "cls" }` 切换 class |
| `set_html` | **仅**键前缀 `#trusted` 的选择器才写 `innerHTML`;其它键忽略 |
Wire 行可选 `值选择器` / `value_from`:事件触发时把该节点内容写入实参 `value`。
事件实参默认含:`event`、`value`、`checked`、`id`(来自 event.target);`submit` 另含 `fields` 表单字典。
L1:`web.dom_patch` / `网页.DOM补丁` 合并效应键;`web.text_patch` / `网页.文本补丁` 快捷 `set_text`。
### 16.3 非目标(D)
| # | 非目标 |
|---|--------|
| D-N1 | 用 Marqdo 重写 bridge 自身 |
| D-N2 | 通用 VDOM / 客户端路由框架 |
| D-N3 | 开放无前缀的 `set_html` |
---
## 17. 路线 E — 前端能力补齐(Planned)
路线图:[browser-wasm-e.md](../roadmap/browser-wasm-e.md)。
**审视结论:** C+D 胜任中小型交互(挂载、wire、表单、单次 fetch);**不能**替代大部分前端 JS,直到 E 波补齐路由、存储、列表片段、WebSocket、更细 DOM/定时。
| 波 | 要点 |
|----|------|
| E1 | `set_style` / `focus` / 委托事件 / 键盘 |
| E2 | 受信列表/片段装配 L1 |
| E3 | `navigate` + `popstate` |
| E4 | `storage` 效应 |
| E5 | 浏览器 `ws` 效应 |
| E6 | 并行 fetch / interval / FormData |
---
## 15. 决策摘要
| 问题 | 答案 |
+35
View File
@@ -0,0 +1,35 @@
# 路线图:浏览器 Marqdo 路线 D(作者零 JS)
| | |
|---|---|
| 状态 | **Completed**(D0–D4 已落地;续作见 [browser-wasm-e.md](browser-wasm-e.md)) |
| 日期 | 2026-09-03 |
| 前置 | [browser-wasm.md](browser-wasm.md)(C0–C5 **Completed**) |
| ADR | [0002](../adr/0002-browser-marqdo-wasm.md) · [0003](../adr/0003-browser-async-effects.md) |
| 设计 | [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) §16 |
## 一句话
作者侧**零业务 JS**:页面逻辑与交互只写 `.mq.md`;官方 `marqdo-bridge.js` 仍作不透明宿主胶(加载 WASM / DOM / fetch),由 `mount` + `client_embed` 自动启动。
## 阶段
| 阶段 | 内容 | 状态 |
|------|------|------|
| **D0** | 路线图 + 设计增补 | **done** |
| **D1** | bridge `mount` + data-mq / `#marqdo-boot` 自启;hello 去掉 loader/interact/fetch.js | **done** |
| **D2** | `client_embed` / `客户端挂载`:`wasm` / `source` / `boot` | **done** |
| **D3** | DOM/表单效应 + wire 传 `value`;`dom_patch` L1 | **done** |
| **D4** | `examples/web-client-site` + skill / README | **done** |
## 非目标
- 消灭官方 bridge 文件本身(宿主胶必须存在)
- 任意 `eval(JS)` / React 式 VDOM
- 把 axum / SQLite 搬进浏览器(仍属 C 非目标)
## 验收
- 示例无作者业务 `.js`(允许构建拷贝的 `marqdo-bridge.js`)
- `ext/web` 一行挂载即可 boot + wire
- 点击、表单 input、`fetch` 效应可演示
+55
View File
@@ -0,0 +1,55 @@
# 路线图:浏览器 Marqdo 路线 E(前端能力补齐)
| | |
|---|---|
| 状态 | **Planned** |
| 日期 | 2026-09-04 |
| 前置 | [browser-wasm-d.md](browser-wasm-d.md)(D0–D4 **Completed**) |
| 设计 | [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) §16–§17 |
## 结论(能力审视)
路线 C+D 已能覆盖**中小型交互站**的常见路径:挂载会话、wire 事件、文本/表单回写、`fetch`/`after`、作者零业务 JS。
**尚不能**宣称「替代大部分 / 全部前端 JS」。缺口集中在:列表级 UI 装配、客户端路由与历史、本地持久化、实时通道、媒体/画布、以及更细的 DOM 读写与委托事件。
| 类别 | 今日 | 典型 JS 任务 | 路线 E |
|------|------|--------------|--------|
| 启动 / 会话 | `mount` / `client_embed` | 手写 loader | 已够用 |
| 点击 / 表单 | wire + `value`/`fields` | addEventListener | 扩委托 / 更多事件 |
| DOM 补丁 | `set_text`/`value`/`attr`/`class` | jQuery 式改节点 | `set_style`、`focus`、`scroll`、列表 diff |
| 网络 | 单次 `fetch` 效应 | axios / 多并行 | 并行 `fetch_all`、上传进度 |
| 定时 | `after` | setInterval | `interval` / `cancel` |
| 路由 | 无 | history / SPA | `navigate` / `popstate` wire |
| 存储 | 无 | localStorage / IDB | `storage` 效应 |
| 实时 | 服务端有 `ws`;浏览器无 | WebSocket | 浏览器 `ws` 效应 |
| 组件列表 | SSR 为主 | 客户端 render list | `set_html(#trusted*)` + 模板装配 L1 |
| 媒体 / 画布 | 无 | Audio / Canvas / WebGL | 后置(非 E 核心) |
| 原生插件 | 浏览器无 `.so` | wasm 插件 | 明确非目标 |
原则不变:官方 bridge 仍是宿主胶;业务只写 `.mq.md`;不引入通用 VDOM / 任意 `eval(JS)`。
## 阶段
| 阶段 | 内容 | 状态 |
|------|------|------|
| **E0** | 本文 + 设计 §17 能力矩阵 | **done**(文档) |
| **E1** | DOM 补齐:`set_style`、`focus`/`blur`、`scroll_into`;wire `keydown`/`keyup`;事件委托(可选 `委托` 列) | planned |
| **E2** | 列表 / 片段:`replace_children` 或受信 `#trusted*` 模板 L1(`web.client_list`);避免手写巨段 HTML | planned |
| **E3** | 客户端路由:`navigate` / `replace` 效应 + `popstate` wire;与 `ext/web` SSR 深链共存约定 | planned |
| **E4** | 持久化:`storage.get/set/remove`(local/session);可选简单 cookie 读写白名单 | planned |
| **E5** | 实时:浏览器 `ws` 效应(open / send / on_message → `mq_call`);对齐服务端 `ws` 语义 | planned |
| **E6** | 异步增强:`fetch` 并行表、`interval`+`clear`、上传 `FormData` 字段表 | planned |
## 验收(E 收口时)
- 无作者业务 JS 的情况下,可做:多页客户端导航、表单草稿存 localStorage、列表增删改、同源 WebSocket 回显。
- 冒烟 / 示例覆盖 E1–E5 各至少一例。
- 体积与安全:效应仍白名单;`set_html` 维持 `#trusted*` 前缀。
## 明确非目标(E)
- React/Vue 式 VDOM 与虚拟列表框架
- 浏览器内 SQLite / 完整 ORM
- Service Worker / PWA 全套(可另开路线)
- 用 Marqdo 重写 bridge 自身
+1 -1
View File
@@ -2,7 +2,7 @@
| | |
|---|---|
| 状态 | **Completed**(路线 C 首版功能完备) |
| 状态 | **Completed**(路线 C 首版功能完备;续作见 [browser-wasm-d.md](browser-wasm-d.md)) |
| 日期 | 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) |
+7 -7
View File
@@ -1,6 +1,6 @@
# browser-hello(WASM C1–C3)
# browser-hello(WASM C1–C4 / 路线 D)
浏览器内跑 Marqdo(路线 C)。
浏览器内跑 Marqdo。**无作者业务 JS**——只保留官方 `marqdo-bridge.js`(`marqdo wasm build` 拷贝)。
```bash
# 仓库根目录
@@ -13,9 +13,9 @@ python3 -m http.server 8765
| 页 | 说明 |
|----|------|
| [/](http://127.0.0.1:8765/) | C1:编辑源码 → `mq_run` 打印 |
| [/interact.html](http://127.0.0.1:8765/interact.html) | C3:`counter.mq.md` 交互表 → 点击改 DOM |
| [/fetch.html](http://127.0.0.1:8765/fetch.html) | C4:`fetch` / `after` 效应续体 |
| [/](http://127.0.0.1:8765/) | playground:`data-mq-playground` + textarea → `mq_run` |
| [/interact.html](http://127.0.0.1:8765/interact.html) | `counter.mq.md` wire → 点击改 DOM |
| [/fetch.html](http://127.0.0.1:8765/fetch.html) | `fetch` / `after` 效应 |
| [/form.html](http://127.0.0.1:8765/form.html) | `input` + `value` / `set_class`(D3) |
- `marqdo-bridge.js`:官方宿主桥(`boot` / `call` / `wireEvents` / `applyEffects`)
- 业务源码只有 `.mq.md`;异步见 [ADR 0003](../../doc/adr/0003-browser-async-effects.md)
自启方式:脚本上的 `data-mq-source-url` / `data-mq-playground`,或 `#marqdo-boot` JSON。详见 [browser-wasm-d.md](../../doc/roadmap/browser-wasm-d.md)。
+9 -2
View File
@@ -69,11 +69,18 @@
</head>
<body>
<h1>Marqdo</h1>
<p class="lead">C4:返回 <code>fetch</code> / <code>after</code> 效应,由官方 bridge 续体回调(ADR 0003)。业务只在 <code>fetch.mq.md</code>。<a href="./interact.html">计数器</a> · <a href="./">打印</a></p>
<p class="lead">C4/D:返回 <code>fetch</code> / <code>after</code> 效应;bridge 自启(ADR 0003)。业务只在 <code>fetch.mq.md</code>。<a href="./interact.html">计数器</a> · <a href="./form.html">表单</a> · <a href="./">打印</a></p>
<div id="status">idle</div>
<button id="load" type="button" disabled>请求 UUID</button>
<button id="ping" class="secondary" type="button" disabled>延迟 pong</button>
<pre id="log">loading…</pre>
<script type="module" src="./fetch.js"></script>
<script
type="module"
src="./marqdo-bridge.js"
data-mq-wasm="./marqdo_wasm.wasm"
data-mq-source-url="./fetch.mq.md"
data-mq-ready="#log"
data-mq-enable="#load,#ping"
></script>
</body>
</html>
-52
View File
@@ -1,52 +0,0 @@
import {
applyDomPatch,
boot,
loadWasm,
readCString,
wireEvents,
} from "./marqdo-bridge.js";
async function main() {
const log = document.getElementById("log");
const loadBtn = document.getElementById("load");
const pingBtn = document.getElementById("ping");
let exports;
try {
exports = await loadWasm("./marqdo_wasm.wasm");
} catch (e) {
log.classList.add("err");
log.textContent = String(e);
return;
}
const srcRes = await fetch("./fetch.mq.md");
if (!srcRes.ok) {
log.classList.add("err");
log.textContent = `failed to load fetch.mq.md (${srcRes.status})`;
return;
}
const source = await srcRes.text();
const result = boot(exports, source);
if (!result.ok) {
log.classList.add("err");
log.textContent = result.error || "boot failed";
return;
}
const n = wireEvents(exports, result.value, {
onError: (err) => {
log.classList.add("err");
log.textContent = err;
},
});
applyDomPatch({ set_text: { "#status": "idle" } });
const ver = readCString(exports.memory, exports.mq_version());
log.classList.remove("err");
log.textContent = `marqdo-wasm ${ver} · wired ${n} · ADR 0003 effects\nsource: fetch.mq.md`;
loadBtn.disabled = false;
pingBtn.disabled = false;
}
main();
+76
View File
@@ -0,0 +1,76 @@
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Marqdo · 表单 (D3)</title>
<style>
:root {
--ink: #1a1f1c;
--paper: #e8efe6;
--accent: #2f6f4e;
--muted: #5a6b60;
}
* { box-sizing: border-box; }
body {
margin: 0;
min-height: 100vh;
font-family: "IBM Plex Sans", "Noto Sans SC", sans-serif;
color: var(--ink);
background:
radial-gradient(700px 400px at 100% 20%, #d0e0d4 0%, transparent 50%),
linear-gradient(165deg, #f3f7f2, var(--paper));
padding: 2rem clamp(1rem, 4vw, 3rem);
}
h1 {
font-family: "IBM Plex Serif", "Noto Serif SC", serif;
font-weight: 600;
font-size: clamp(1.6rem, 3vw, 2.2rem);
margin: 0 0 0.35rem;
}
.lead { color: var(--muted); margin: 0 0 1.25rem; max-width: 38rem; }
label { display: block; font-size: 0.85rem; color: var(--muted); margin: 0.75rem 0 0.35rem; }
input[type="text"] {
width: min(24rem, 100%);
padding: 0.5rem 0.75rem;
border: 1px solid #b7c7bb;
background: rgba(255,255,255,0.75);
font: inherit;
}
#echo {
margin-top: 1rem;
font-size: 1.25rem;
min-height: 1.5em;
}
#echo.hi { color: var(--accent); font-weight: 600; }
pre {
margin-top: 1.5rem;
width: min(42rem, 100%);
padding: 0.9rem 1rem;
background: #122018;
color: #d7eadc;
overflow: auto;
font-size: 0.8rem;
line-height: 1.4;
}
.err { color: #ffb4a8; }
a { color: var(--accent); }
</style>
</head>
<body>
<h1>Marqdo</h1>
<p class="lead">D3:<code>input</code> 事件把 <code>value</code> 传入 Marqdo;<code>set_value</code> / <code>set_class</code> / <code>set_attr</code> 回写 DOM。业务只在 <code>form.mq.md</code>。<a href="./interact.html">计数器</a> · <a href="./">打印</a></p>
<label for="name">名字</label>
<input id="name" type="text" placeholder="输入…" disabled />
<div id="echo">(等待输入)</div>
<pre id="log">loading…</pre>
<script
type="module"
src="./marqdo-bridge.js"
data-mq-wasm="./marqdo_wasm.wasm"
data-mq-source-url="./form.mq.md"
data-mq-ready="#log"
data-mq-enable="#name"
></script>
</body>
</html>
+34
View File
@@ -0,0 +1,34 @@
---
title: browser form (D3)
description: input wire passes value; set_text / set_class / set_attr effects
import json:lib/json.mq.md
---
# main
`wire` =
| @ | 选择器 | 事件 | 调用 |
|---|--------|------|------|
| 1 | "#name" | input | on_input |
**`wire`**
## on_input
+ `value`=""
+ `event`=""
1. `value` != ""
*`label` = "你好," + value*
*`t` = > json.set map=None key="#echo" value=label*
*`ret` = > json.set map=None key="set_text" value=t*
*`c` = > json.set map=None key="#echo" value="hi"*
*`ret` = > json.set map=ret key="set_class" value=c*
*`attrs` = > json.set map=None key="data-name" value=value*
*`a` = > json.set map=None key="#echo" value=attrs*
**> json.set map=ret key="set_attr" value=a**
2. *
*`t` = > json.set map=None key="#echo" value="(等待输入)"*
*`ret` = > json.set map=None key="set_text" value=t*
*`c` = > json.set map=None key="#echo" value=""*
**> json.set map=ret key="set_class" value=c**
+8 -2
View File
@@ -67,7 +67,7 @@
</head>
<body>
<h1>Marqdo</h1>
<p class="lead">浏览器内 WASM 解释器(路线 C / C1):源码是 <code>.mq.md</code>,无业务手写 JS。<a href="./interact.html">交互示例 (C3)</a></p>
<p class="lead">浏览器内 WASM(路线 C/D):源码是 <code>.mq.md</code>,官方 bridge 自启 playground,无作者业务 JS。<a href="./interact.html">交互</a> · <a href="./fetch.html">fetch</a> · <a href="./form.html">表单</a></p>
<label for="src">程序</label>
<textarea id="src"># main
@@ -77,6 +77,12 @@
<button id="run" disabled>运行</button>
</div>
<pre id="out">loading wasm…</pre>
<script type="module" src="./loader.js"></script>
<script
type="module"
src="./marqdo-bridge.js"
data-mq-wasm="./marqdo_wasm.wasm"
data-mq-playground="#src,#run,#out"
data-mq-ready="#out"
></script>
</body>
</html>
+9 -2
View File
@@ -62,11 +62,18 @@
</head>
<body>
<h1>Marqdo</h1>
<p class="lead">C3:GFM 交互表装配事件;点击由 WASM 会话里的 Marqdo 函数处理并回写 DOM。<a href="./fetch.html">fetch (C4)</a> · <a href="./">打印示例</a></p>
<p class="lead">C3/D:GFM 交互表装配事件;官方 <code>mount</code> 自启,业务只在 <code>counter.mq.md</code>。<a href="./fetch.html">fetch</a> · <a href="./form.html">表单</a> · <a href="./">打印</a></p>
<div id="count">0</div>
<button id="bump" type="button" disabled>加一</button>
<button id="reset" class="secondary" type="button" disabled>清零</button>
<pre id="log">loading…</pre>
<script type="module" src="./interact.js"></script>
<script
type="module"
src="./marqdo-bridge.js"
data-mq-wasm="./marqdo_wasm.wasm"
data-mq-source-url="./counter.mq.md"
data-mq-ready="#log"
data-mq-enable="#bump,#reset"
></script>
</body>
</html>
-53
View File
@@ -1,53 +0,0 @@
import {
applyDomPatch,
boot,
loadWasm,
readCString,
wireEvents,
} from "./marqdo-bridge.js";
async function main() {
const log = document.getElementById("log");
const bump = document.getElementById("bump");
const reset = document.getElementById("reset");
let exports;
try {
exports = await loadWasm("./marqdo_wasm.wasm");
} catch (e) {
log.classList.add("err");
log.textContent = String(e);
return;
}
const srcRes = await fetch("./counter.mq.md");
if (!srcRes.ok) {
log.classList.add("err");
log.textContent = `failed to load counter.mq.md (${srcRes.status})`;
return;
}
const source = await srcRes.text();
const result = boot(exports, source);
if (!result.ok) {
log.classList.add("err");
log.textContent = result.error || "boot failed";
return;
}
const n = wireEvents(exports, result.value, {
onError: (err) => {
log.classList.add("err");
log.textContent = err;
},
});
// Ensure initial display matches Marqdo state.
applyDomPatch({ set_text: { "#count": "0" } });
const ver = readCString(exports.memory, exports.mq_version());
log.classList.remove("err");
log.textContent = `marqdo-wasm ${ver} · wired ${n} handler(s)\nsource: counter.mq.md`;
bump.disabled = false;
reset.disabled = false;
}
main();
-48
View File
@@ -1,48 +0,0 @@
import {
loadWasm,
readCString,
runSource,
} from "./marqdo-bridge.js";
const DEFAULT_SRC = `# main
> print text=Hello from browser WASM!
`;
async function main() {
const out = document.getElementById("out");
const btn = document.getElementById("run");
const src = document.getElementById("src");
if (!src.value.trim()) src.value = DEFAULT_SRC;
let exports;
try {
exports = await loadWasm("./marqdo_wasm.wasm");
} catch (e) {
out.classList.add("err");
out.textContent = String(e);
return;
}
const ver = readCString(exports.memory, exports.mq_version());
out.classList.remove("err");
out.textContent = `marqdo-wasm ${ver} ready.\n`;
btn.disabled = false;
btn.addEventListener("click", () => {
try {
const result = runSource(exports, src.value);
out.classList.toggle("err", !result.ok);
out.textContent = result.ok
? (result.stdout || "(empty stdout)") +
(result.value != null && result.value !== "None"
? `\n[return] ${typeof result.value === "string" ? result.value : JSON.stringify(result.value)}`
: "")
: result.error || "error";
} catch (e) {
out.classList.add("err");
out.textContent = String(e);
}
});
}
main();
+342 -6
View File
@@ -1,11 +1,13 @@
/**
* Canonical Marqdo browser bridge (route C). Host glue only — not app logic.
* Canonical Marqdo browser bridge (route C/D). 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
* Effects (ADR 0003 + route D): set_text, set_value, set_attr, set_class,
* toggle_class, set_html (#trusted* only), fetch, after
* Mount: mount() / data-mq-* / #marqdo-boot auto-start (author zero JS)
*/
export function readCString(memory, ptr) {
@@ -67,16 +69,196 @@ export async function loadWasm(url = "./marqdo_wasm.wasm") {
return instance.exports;
}
/** Apply C3/C4 return effects: set_text, fetch, after */
function isPlainObject(v) {
return v != null && typeof v === "object" && !Array.isArray(v);
}
/** Normalize mount options from plain object or DOM dataset. */
export function normalizeMountOptions(raw = {}) {
const o = raw && typeof raw === "object" ? raw : {};
const dataset = o.dataset || {};
const wasmUrl =
o.wasmUrl ||
o.wasm ||
dataset.mqWasm ||
dataset.wasm ||
"./marqdo_wasm.wasm";
const sourceUrl =
o.sourceUrl ||
o.source_url ||
dataset.mqSourceUrl ||
dataset.sourceUrl ||
"";
let source = o.source != null ? o.source : dataset.mqSource || "";
if (!source && typeof o.sourceInline === "string") source = o.sourceInline;
const playground =
o.playground ||
dataset.mqPlayground ||
dataset.playground ||
"";
const ready =
o.ready ||
o.readySel ||
dataset.mqReady ||
"";
const enable =
o.enable ||
dataset.mqEnable ||
"";
const noBoot =
o.noBoot === true ||
dataset.mqNoBoot === "1" ||
dataset.mqNoBoot === "true";
return {
wasmUrl: String(wasmUrl),
sourceUrl: sourceUrl ? String(sourceUrl) : "",
source: source ? String(source) : "",
playground: playground ? String(playground) : "",
ready: ready ? String(ready) : "",
enable: enable ? String(enable) : "",
noBoot,
onError: typeof o.onError === "function" ? o.onError : null,
};
}
/**
* Collect mount configs from `#marqdo-boot` JSON and `script[data-mq-*]`.
* Pure DOM scan — safe to call once after DOM ready.
*/
export function collectMountConfigs(doc = typeof document !== "undefined" ? document : null) {
if (!doc) return [];
const out = [];
const bootEl = doc.getElementById("marqdo-boot");
if (bootEl) {
try {
const json = JSON.parse(bootEl.textContent || "{}");
out.push(normalizeMountOptions(json));
} catch (e) {
console.error("marqdo-boot JSON:", e);
}
}
const scripts = doc.querySelectorAll(
"script[data-mq-source-url], script[data-mq-source], script[data-mq-playground], script[data-mq-wasm]",
);
for (const el of scripts) {
if (el.dataset.mqNoBoot === "1" || el.dataset.mqNoBoot === "true") continue;
const hasWork =
el.dataset.mqSourceUrl ||
el.dataset.mqSource ||
el.dataset.mqPlayground;
if (!hasWork && !el.dataset.mqWasm) continue;
if (!hasWork) continue;
out.push(
normalizeMountOptions({
dataset: el.dataset,
wasmUrl: el.dataset.mqWasm,
sourceUrl: el.dataset.mqSourceUrl,
source: el.dataset.mqSource,
playground: el.dataset.mqPlayground,
ready: el.dataset.mqReady,
enable: el.dataset.mqEnable,
}),
);
}
return out;
}
/** Build mq_call args from a DOM event + optional value_from selector. */
export function eventArgsFromDom(ev, valueFromSel) {
const t = ev && ev.target;
const args = {
event: ev && ev.type ? ev.type : "click",
};
if (t && typeof t === "object") {
if ("value" in t && t.value != null) args.value = String(t.value);
if ("checked" in t) args.checked = !!t.checked;
if (t.id) args.id = String(t.id);
if (typeof t.textContent === "string" && !("value" in t)) {
args.text = t.textContent;
}
}
if (valueFromSel && typeof document !== "undefined") {
const src = document.querySelector(valueFromSel);
if (src) {
if ("value" in src) args.value = String(src.value);
else args.value = src.textContent != null ? String(src.textContent) : "";
}
}
if (ev && ev.type === "submit" && t) {
const form = typeof t.closest === "function" ? t.closest("form") : t;
if (form && typeof FormData !== "undefined") {
try {
ev.preventDefault();
} catch (_) {
/* ignore */
}
const fields = {};
for (const [k, v] of new FormData(form)) {
fields[k] = String(v);
}
args.fields = fields;
}
}
return args;
}
/** Apply C3/C4/D3 return effects: DOM patches then fetch/after. */
export function applyDomPatch(value) {
if (!value || typeof value !== "object") return;
if (typeof document === "undefined") return;
const setText = value.set_text || value.setText;
if (setText && typeof setText === "object") {
if (isPlainObject(setText)) {
for (const [sel, text] of Object.entries(setText)) {
const el = document.querySelector(sel);
if (el) el.textContent = String(text);
}
}
const setValue = value.set_value || value.setValue;
if (isPlainObject(setValue)) {
for (const [sel, v] of Object.entries(setValue)) {
const el = document.querySelector(sel);
if (el && "value" in el) el.value = String(v);
}
}
const setAttr = value.set_attr || value.setAttr;
if (isPlainObject(setAttr)) {
for (const [sel, attrs] of Object.entries(setAttr)) {
const el = document.querySelector(sel);
if (!el || !isPlainObject(attrs)) continue;
for (const [name, raw] of Object.entries(attrs)) {
if (raw === null || raw === false) el.removeAttribute(name);
else el.setAttribute(name, String(raw));
}
}
}
const setClass = value.set_class || value.setClass;
if (isPlainObject(setClass)) {
for (const [sel, cls] of Object.entries(setClass)) {
const el = document.querySelector(sel);
if (el) el.className = String(cls);
}
}
const toggleClass = value.toggle_class || value.toggleClass;
if (isPlainObject(toggleClass)) {
for (const [sel, cls] of Object.entries(toggleClass)) {
const el = document.querySelector(sel);
if (el && cls) el.classList.toggle(String(cls));
}
}
const setHtml = value.set_html || value.setHtml;
if (isPlainObject(setHtml)) {
for (const [sel, html] of Object.entries(setHtml)) {
if (!String(sel).startsWith("#trusted")) continue;
const el = document.querySelector(sel);
if (el) el.innerHTML = String(html);
}
}
}
/**
@@ -180,12 +362,15 @@ export function wireEvents(exports, bootValue, { onError } = {}) {
const sel = row["选择器"] || row.selector || row.sel;
const ev = row["事件"] || row.event || "click";
const fn = row["调用"] || row.call || row.fn;
const valueFrom =
row["值选择器"] || row.value_from || row.valueFrom || row.from || "";
if (!sel || !fn) continue;
const nodes = document.querySelectorAll(sel);
nodes.forEach((node) => {
node.addEventListener(ev, () => {
node.addEventListener(ev, (domEv) => {
try {
const result = call(exports, fn, { event: ev });
const args = eventArgsFromDom(domEv, valueFrom);
const result = call(exports, fn, args);
if (!result.ok) {
if (onError) onError(result.error);
else console.error(result.error);
@@ -202,3 +387,154 @@ export function wireEvents(exports, bootValue, { onError } = {}) {
}
return rows.length;
}
function markReady(opts, message) {
if (opts.ready && typeof document !== "undefined") {
const el = document.querySelector(opts.ready);
if (el) {
el.classList?.remove?.("err");
el.textContent = message;
}
}
if (opts.enable && typeof document !== "undefined") {
for (const sel of String(opts.enable).split(",")) {
const s = sel.trim();
if (!s) continue;
document.querySelectorAll(s).forEach((n) => {
n.disabled = false;
n.removeAttribute("disabled");
});
}
}
}
function markError(opts, err) {
const msg = String(err);
if (opts.onError) opts.onError(msg);
if (opts.ready && typeof document !== "undefined") {
const el = document.querySelector(opts.ready);
if (el) {
el.classList?.add?.("err");
el.textContent = msg;
}
} else {
console.error(msg);
}
}
function wirePlayground(exports, playgroundSpec, { onError } = {}) {
const parts = String(playgroundSpec)
.split(",")
.map((s) => s.trim())
.filter(Boolean);
const sourceSel = parts[0] || "#src";
const runSel = parts[1] || "#run";
const outSel = parts[2] || "#out";
const runBtn = document.querySelector(runSel);
const src = document.querySelector(sourceSel);
const out = document.querySelector(outSel);
if (!runBtn || !src) return 0;
runBtn.disabled = false;
runBtn.removeAttribute("disabled");
runBtn.addEventListener("click", () => {
try {
const result = runSource(exports, src.value || "");
if (out) {
out.classList?.toggle?.("err", !result.ok);
out.textContent = result.ok
? (result.stdout || "(empty stdout)") +
(result.value != null && result.value !== "None"
? `\n[return] ${typeof result.value === "string" ? result.value : JSON.stringify(result.value)}`
: "")
: result.error || "error";
}
} catch (e) {
if (onError) onError(String(e));
else if (out) {
out.classList?.add?.("err");
out.textContent = String(e);
}
}
});
return 1;
}
/**
* One-shot: load wasm, boot session (or playground), wire events.
* @returns {{ exports, boot, wired }}
*/
export async function mount(rawOpts = {}) {
const opts = normalizeMountOptions(rawOpts);
const onError = (err) => markError(opts, err);
let exports;
try {
exports = await loadWasm(opts.wasmUrl);
} catch (e) {
onError(e);
throw e;
}
const ver = readCString(exports.memory, exports.mq_version());
if (opts.playground) {
const n = wirePlayground(exports, opts.playground, { onError });
markReady(opts, `marqdo-wasm ${ver} · playground ready`);
return { exports, boot: null, wired: n };
}
let source = opts.source;
if (!source && opts.sourceUrl) {
const res = await fetch(opts.sourceUrl);
if (!res.ok) {
const err = `failed to load ${opts.sourceUrl} (${res.status})`;
onError(err);
throw new Error(err);
}
source = await res.text();
}
if (!source) {
const err = "mount: need source, sourceUrl, or playground";
onError(err);
throw new Error(err);
}
const result = boot(exports, source);
if (!result.ok) {
onError(result.error || "boot failed");
throw new Error(result.error || "boot failed");
}
// If boot value is a map with effects alongside wire, apply them.
if (result.value && !Array.isArray(result.value)) {
await applyEffects(exports, result.value, { onError });
}
const n = wireEvents(exports, result.value, { onError });
const srcLabel = opts.sourceUrl || "(inline)";
markReady(opts, `marqdo-wasm ${ver} · wired ${n} handler(s)\nsource: ${srcLabel}`);
return { exports, boot: result, wired: n };
}
/** Auto-mount from DOM configs (route D). */
export async function autoMount(doc) {
const configs = collectMountConfigs(doc);
const results = [];
for (const cfg of configs) {
if (cfg.noBoot) continue;
results.push(await mount(cfg));
}
return results;
}
const g = typeof globalThis !== "undefined" ? globalThis : undefined;
if (g && g.document) {
const start = () => {
autoMount(g.document).catch((e) => console.error("marqdo autoMount:", e));
};
if (g.document.readyState === "loading") {
g.document.addEventListener("DOMContentLoaded", start);
} else {
queueMicrotask(start);
}
}
+20
View File
@@ -0,0 +1,20 @@
# web-client-site(路线 D)
服务端 `ext/web` + 浏览器 WASM 会话;**作者零业务 JS**。
```bash
# 仓库根
cargo build -p marqdo --release
cargo build --release -p marqdo_plugin_web
./target/release/marqdo ext add web
# 构建 WASM + bridge 到本示例 static/
./target/release/marqdo wasm build -o examples/web-client-site/static
# 保留 client.mq.md(wasm build 只写入 wasm/bridge)
cd examples/web-client-site
marqdo run index.mq.md
# 打开 http://127.0.0.1:18090/
```
`index.mq.md` 用 `web.client_embed source="/static/client.mq.md"` 注入自启脚本;交互在 `static/client.mq.md`。
+19
View File
@@ -0,0 +1,19 @@
---
title: web-client-site
description: SSR shell + client_embed auto-mount; author zero JS (route D)
import web:ext/web/web.mq.md
---
# main
Server page with a counter UI. Client logic lives in `static/client.mq.md`
(loaded by official bridge via `client_embed`).
*`embed` = > web.client_embed bridge="/static/marqdo-bridge.js" wasm="/static/marqdo_wasm.wasm" source="/static/client.mq.md" boot=True*
*`intro` = "<h1>Marqdo client site</h1><p>SSR + WASM session. No author JS.</p><div id=\"count\">0</div><p><button id=\"bump\" type=\"button\" disabled>Bump</button> <button id=\"reset\" type=\"button\" disabled>Reset</button></p><pre id=\"log\">booting…</pre>" + embed*
*page = > web.page title="Marqdo client site" intro=intro*
*app = > web.app page=page host="127.0.0.1" port=18090*
*app = > app.static dir="static" mount="/static"*
> `app`.listen
@@ -0,0 +1,36 @@
---
title: client counter (route D)
description: wired by client_embed auto-mount
import json:lib/json.mq.md
---
# main
*`count` = 0*
`wire` =
| @ | 选择器 | 事件 | 调用 |
|---|--------|------|------|
| 1 | "#bump" | click | bump |
| 2 | "#reset" | click | reset |
*`ready` = > json.set map=None key="#log" value="client.mq.md ready"*
*`enable_bump` = > json.set map=None key="disabled" value=False*
*`enable_reset` = > json.set map=None key="disabled" value=False*
*`attrs` = > json.set map=None key="#bump" value=enable_bump*
*`attrs` = > json.set map=attrs key="#reset" value=enable_reset*
*`boot` = > json.set map=None key="wire" value=wire*
*`boot` = > json.set map=boot key="set_text" value=ready*
**> json.set map=boot key="set_attr" value=attrs**
## bump
*`count` = count + 1*
*`label` = > str count*
*`patch` = > json.set map=None key="#count" value=label*
**> json.set map=None key="set_text" value=patch**
## reset
*`count` = 0*
*`patch` = > json.set map=None key="#count" value="0"*
**> json.set map=None key="set_text" value=patch**
@@ -0,0 +1,540 @@
/**
* Canonical Marqdo browser bridge (route C/D). 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 + route D): set_text, set_value, set_attr, set_class,
* toggle_class, set_html (#trusted* only), fetch, after
* Mount: mount() / data-mq-* / #marqdo-boot auto-start (author zero JS)
*/
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;
}
function isPlainObject(v) {
return v != null && typeof v === "object" && !Array.isArray(v);
}
/** Normalize mount options from plain object or DOM dataset. */
export function normalizeMountOptions(raw = {}) {
const o = raw && typeof raw === "object" ? raw : {};
const dataset = o.dataset || {};
const wasmUrl =
o.wasmUrl ||
o.wasm ||
dataset.mqWasm ||
dataset.wasm ||
"./marqdo_wasm.wasm";
const sourceUrl =
o.sourceUrl ||
o.source_url ||
dataset.mqSourceUrl ||
dataset.sourceUrl ||
"";
let source = o.source != null ? o.source : dataset.mqSource || "";
if (!source && typeof o.sourceInline === "string") source = o.sourceInline;
const playground =
o.playground ||
dataset.mqPlayground ||
dataset.playground ||
"";
const ready =
o.ready ||
o.readySel ||
dataset.mqReady ||
"";
const enable =
o.enable ||
dataset.mqEnable ||
"";
const noBoot =
o.noBoot === true ||
dataset.mqNoBoot === "1" ||
dataset.mqNoBoot === "true";
return {
wasmUrl: String(wasmUrl),
sourceUrl: sourceUrl ? String(sourceUrl) : "",
source: source ? String(source) : "",
playground: playground ? String(playground) : "",
ready: ready ? String(ready) : "",
enable: enable ? String(enable) : "",
noBoot,
onError: typeof o.onError === "function" ? o.onError : null,
};
}
/**
* Collect mount configs from `#marqdo-boot` JSON and `script[data-mq-*]`.
* Pure DOM scan — safe to call once after DOM ready.
*/
export function collectMountConfigs(doc = typeof document !== "undefined" ? document : null) {
if (!doc) return [];
const out = [];
const bootEl = doc.getElementById("marqdo-boot");
if (bootEl) {
try {
const json = JSON.parse(bootEl.textContent || "{}");
out.push(normalizeMountOptions(json));
} catch (e) {
console.error("marqdo-boot JSON:", e);
}
}
const scripts = doc.querySelectorAll(
"script[data-mq-source-url], script[data-mq-source], script[data-mq-playground], script[data-mq-wasm]",
);
for (const el of scripts) {
if (el.dataset.mqNoBoot === "1" || el.dataset.mqNoBoot === "true") continue;
const hasWork =
el.dataset.mqSourceUrl ||
el.dataset.mqSource ||
el.dataset.mqPlayground;
if (!hasWork && !el.dataset.mqWasm) continue;
if (!hasWork) continue;
out.push(
normalizeMountOptions({
dataset: el.dataset,
wasmUrl: el.dataset.mqWasm,
sourceUrl: el.dataset.mqSourceUrl,
source: el.dataset.mqSource,
playground: el.dataset.mqPlayground,
ready: el.dataset.mqReady,
enable: el.dataset.mqEnable,
}),
);
}
return out;
}
/** Build mq_call args from a DOM event + optional value_from selector. */
export function eventArgsFromDom(ev, valueFromSel) {
const t = ev && ev.target;
const args = {
event: ev && ev.type ? ev.type : "click",
};
if (t && typeof t === "object") {
if ("value" in t && t.value != null) args.value = String(t.value);
if ("checked" in t) args.checked = !!t.checked;
if (t.id) args.id = String(t.id);
if (typeof t.textContent === "string" && !("value" in t)) {
args.text = t.textContent;
}
}
if (valueFromSel && typeof document !== "undefined") {
const src = document.querySelector(valueFromSel);
if (src) {
if ("value" in src) args.value = String(src.value);
else args.value = src.textContent != null ? String(src.textContent) : "";
}
}
if (ev && ev.type === "submit" && t) {
const form = typeof t.closest === "function" ? t.closest("form") : t;
if (form && typeof FormData !== "undefined") {
try {
ev.preventDefault();
} catch (_) {
/* ignore */
}
const fields = {};
for (const [k, v] of new FormData(form)) {
fields[k] = String(v);
}
args.fields = fields;
}
}
return args;
}
/** Apply C3/C4/D3 return effects: DOM patches then fetch/after. */
export function applyDomPatch(value) {
if (!value || typeof value !== "object") return;
if (typeof document === "undefined") return;
const setText = value.set_text || value.setText;
if (isPlainObject(setText)) {
for (const [sel, text] of Object.entries(setText)) {
const el = document.querySelector(sel);
if (el) el.textContent = String(text);
}
}
const setValue = value.set_value || value.setValue;
if (isPlainObject(setValue)) {
for (const [sel, v] of Object.entries(setValue)) {
const el = document.querySelector(sel);
if (el && "value" in el) el.value = String(v);
}
}
const setAttr = value.set_attr || value.setAttr;
if (isPlainObject(setAttr)) {
for (const [sel, attrs] of Object.entries(setAttr)) {
const el = document.querySelector(sel);
if (!el || !isPlainObject(attrs)) continue;
for (const [name, raw] of Object.entries(attrs)) {
if (raw === null || raw === false) el.removeAttribute(name);
else el.setAttribute(name, String(raw));
}
}
}
const setClass = value.set_class || value.setClass;
if (isPlainObject(setClass)) {
for (const [sel, cls] of Object.entries(setClass)) {
const el = document.querySelector(sel);
if (el) el.className = String(cls);
}
}
const toggleClass = value.toggle_class || value.toggleClass;
if (isPlainObject(toggleClass)) {
for (const [sel, cls] of Object.entries(toggleClass)) {
const el = document.querySelector(sel);
if (el && cls) el.classList.toggle(String(cls));
}
}
const setHtml = value.set_html || value.setHtml;
if (isPlainObject(setHtml)) {
for (const [sel, html] of Object.entries(setHtml)) {
if (!String(sel).startsWith("#trusted")) continue;
const el = document.querySelector(sel);
if (el) el.innerHTML = String(html);
}
}
}
/**
* 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;
const valueFrom =
row["值选择器"] || row.value_from || row.valueFrom || row.from || "";
if (!sel || !fn) continue;
const nodes = document.querySelectorAll(sel);
nodes.forEach((node) => {
node.addEventListener(ev, (domEv) => {
try {
const args = eventArgsFromDom(domEv, valueFrom);
const result = call(exports, fn, args);
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;
}
function markReady(opts, message) {
if (opts.ready && typeof document !== "undefined") {
const el = document.querySelector(opts.ready);
if (el) {
el.classList?.remove?.("err");
el.textContent = message;
}
}
if (opts.enable && typeof document !== "undefined") {
for (const sel of String(opts.enable).split(",")) {
const s = sel.trim();
if (!s) continue;
document.querySelectorAll(s).forEach((n) => {
n.disabled = false;
n.removeAttribute("disabled");
});
}
}
}
function markError(opts, err) {
const msg = String(err);
if (opts.onError) opts.onError(msg);
if (opts.ready && typeof document !== "undefined") {
const el = document.querySelector(opts.ready);
if (el) {
el.classList?.add?.("err");
el.textContent = msg;
}
} else {
console.error(msg);
}
}
function wirePlayground(exports, playgroundSpec, { onError } = {}) {
const parts = String(playgroundSpec)
.split(",")
.map((s) => s.trim())
.filter(Boolean);
const sourceSel = parts[0] || "#src";
const runSel = parts[1] || "#run";
const outSel = parts[2] || "#out";
const runBtn = document.querySelector(runSel);
const src = document.querySelector(sourceSel);
const out = document.querySelector(outSel);
if (!runBtn || !src) return 0;
runBtn.disabled = false;
runBtn.removeAttribute("disabled");
runBtn.addEventListener("click", () => {
try {
const result = runSource(exports, src.value || "");
if (out) {
out.classList?.toggle?.("err", !result.ok);
out.textContent = result.ok
? (result.stdout || "(empty stdout)") +
(result.value != null && result.value !== "None"
? `\n[return] ${typeof result.value === "string" ? result.value : JSON.stringify(result.value)}`
: "")
: result.error || "error";
}
} catch (e) {
if (onError) onError(String(e));
else if (out) {
out.classList?.add?.("err");
out.textContent = String(e);
}
}
});
return 1;
}
/**
* One-shot: load wasm, boot session (or playground), wire events.
* @returns {{ exports, boot, wired }}
*/
export async function mount(rawOpts = {}) {
const opts = normalizeMountOptions(rawOpts);
const onError = (err) => markError(opts, err);
let exports;
try {
exports = await loadWasm(opts.wasmUrl);
} catch (e) {
onError(e);
throw e;
}
const ver = readCString(exports.memory, exports.mq_version());
if (opts.playground) {
const n = wirePlayground(exports, opts.playground, { onError });
markReady(opts, `marqdo-wasm ${ver} · playground ready`);
return { exports, boot: null, wired: n };
}
let source = opts.source;
if (!source && opts.sourceUrl) {
const res = await fetch(opts.sourceUrl);
if (!res.ok) {
const err = `failed to load ${opts.sourceUrl} (${res.status})`;
onError(err);
throw new Error(err);
}
source = await res.text();
}
if (!source) {
const err = "mount: need source, sourceUrl, or playground";
onError(err);
throw new Error(err);
}
const result = boot(exports, source);
if (!result.ok) {
onError(result.error || "boot failed");
throw new Error(result.error || "boot failed");
}
// If boot value is a map with effects alongside wire, apply them.
if (result.value && !Array.isArray(result.value)) {
await applyEffects(exports, result.value, { onError });
}
const n = wireEvents(exports, result.value, { onError });
const srcLabel = opts.sourceUrl || "(inline)";
markReady(opts, `marqdo-wasm ${ver} · wired ${n} handler(s)\nsource: ${srcLabel}`);
return { exports, boot: result, wired: n };
}
/** Auto-mount from DOM configs (route D). */
export async function autoMount(doc) {
const configs = collectMountConfigs(doc);
const results = [];
for (const cfg of configs) {
if (cfg.noBoot) continue;
results.push(await mount(cfg));
}
return results;
}
const g = typeof globalThis !== "undefined" ? globalThis : undefined;
if (g && g.document) {
const start = () => {
autoMount(g.document).catch((e) => console.error("marqdo autoMount:", e));
};
if (g.document.readyState === "loading") {
g.document.addEventListener("DOMContentLoaded", start);
} else {
queueMicrotask(start);
}
}
+56 -9
View File
@@ -3,6 +3,7 @@ title: ext/web/web
description: Official web site classes (English). Tables + methods; no bag glue.
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
import json:lib/json.mq.md
---
## ensure_plugin
@@ -53,6 +54,61 @@ preview; prefer `page.head` to attach resources to a page.
> ensure_plugin
**> web_head table=`table`**
## client_embed
+ `bridge`="/static/marqdo-bridge.js"
+ `wasm`="/static/marqdo_wasm.wasm"
+ `source`=""
+ `boot`=True
Return an HTML snippet that loads the official browser Marqdo bridge (route C/D).
With `boot` and non-empty `source` (URL path to `.mq.md`), emits `data-mq-wasm` / `data-mq-source-url` so the bridge **auto-mounts** (author zero JS).
Run `marqdo wasm build -o static` and `app.static dir=static`. Design: [browser-marqdo-wasm.md](../../doc/design/browser-marqdo-wasm.md) §16.
1. `boot`
1. `source` != ""
**"<script type=\"module\" src=\"" + bridge + "\" data-mq-wasm=\"" + wasm + "\" data-mq-source-url=\"" + source + "\"></script>"**
2. *
**"<script type=\"module\" src=\"" + bridge + "\"></script>"**
2. *
**"<script type=\"module\" src=\"" + bridge + "\" data-mq-no-boot=\"1\"></script>"**
## text_patch
+ `sel`
+ `text`
Shortcut: build a `set_text` effects map `{ set_text: { sel: text } }` for browser return values.
*`m` = > json.set map=None key=sel value=text*
**> json.set map=None key="set_text" value=m**
## dom_patch
+ `set_text`=None
+ `set_value`=None
+ `set_attr`=None
+ `set_class`=None
+ `toggle_class`=None
+ `fetch`=None
+ `after`=None
Merge browser DOM/async effect keys into one return map (omit `None` keys). Prefer over hand-rolled nested `json.set` chains.
*`out` = > json.set map=None key="_mq" value=True*
1. `set_text` != None
*`out` = > json.set map=out key="set_text" value=set_text*
1. `set_value` != None
*`out` = > json.set map=out key="set_value" value=set_value*
1. `set_attr` != None
*`out` = > json.set map=out key="set_attr" value=set_attr*
1. `set_class` != None
*`out` = > json.set map=out key="set_class" value=set_class*
1. `toggle_class` != None
*`out` = > json.set map=out key="toggle_class" value=toggle_class*
1. `fetch` != None
*`out` = > json.set map=out key="fetch" value=fetch*
1. `after` != None
*`out` = > json.set map=out key="after" value=after*
**out**
# page
+ `title`="Marqdo Web"
+ `intro`=""
@@ -127,15 +183,6 @@ 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`
+55 -9
View File
@@ -3,6 +3,7 @@ title: ext/web/网页
description: 官方网站类(中文)。表格 + 方法;不写袋式胶水。
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
import json:lib/json.mq.md
---
## 确保插件
@@ -50,6 +51,60 @@ import sys:lib/sys.mq.md
> 确保插件
**> web_head table=`表`**
## 客户端挂载
+ `桥`="/static/marqdo-bridge.js"
+ `wasm`="/static/marqdo_wasm.wasm"
+ `源`=""
+ `启动`=True
返回挂载浏览器 Marqdo(路线 C/D)的 HTML。`启动` 且 `源` 非空(客户端 `.mq.md` URL)时写入 `data-mq-wasm` / `data-mq-source-url`,官方 bridge **自动 mount**(作者零业务 JS)。
请先 `marqdo wasm build -o static`,并用 `app.静态` 提供该目录。设计见 [browser-marqdo-wasm.md](../../doc/design/browser-marqdo-wasm.md) §16。
1. `启动`
1. `源` != ""
**"<script type=\"module\" src=\"" + 桥 + "\" data-mq-wasm=\"" + wasm + "\" data-mq-source-url=\"" + 源 + "\"></script>"**
2. *
**"<script type=\"module\" src=\"" + 桥 + "\"></script>"**
2. *
**"<script type=\"module\" src=\"" + 桥 + "\" data-mq-no-boot=\"1\"></script>"**
## 文本补丁
+ `选择器`
+ `文本`
快捷构造 `set_text` 效应表。
*`m` = > json.set map=None key=选择器 value=文本*
**> json.set map=None key="set_text" value=m**
## DOM补丁
+ `set_text`=None
+ `set_value`=None
+ `set_attr`=None
+ `set_class`=None
+ `toggle_class`=None
+ `fetch`=None
+ `after`=None
合并浏览器 DOM/异步效应键为一张返回表(跳过 `None`)。
*`out` = > json.set map=None key="_mq" value=True*
1. `set_text` != None
*`out` = > json.set map=out key="set_text" value=set_text*
1. `set_value` != None
*`out` = > json.set map=out key="set_value" value=set_value*
1. `set_attr` != None
*`out` = > json.set map=out key="set_attr" value=set_attr*
1. `set_class` != None
*`out` = > json.set map=out key="set_class" value=set_class*
1. `toggle_class` != None
*`out` = > json.set map=out key="toggle_class" value=toggle_class*
1. `fetch` != None
*`out` = > json.set map=out key="fetch" value=fetch*
1. `after` != None
*`out` = > json.set map=out key="after" value=after*
**out**
# 页面
+ `标题`="站点"
+ `引言`=""
@@ -116,15 +171,6 @@ 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>"**
## 图片装配
+ `表`
+1 -1
View File
@@ -34,7 +34,7 @@ ext/llm — OpenAI-compatible chat. Design: doc/design/ext-llm.md
ext/agent — agent framework + native plugin. Design: doc/design/ext-agent.md
ext/web — HTTP / SQLite·Postgres site helpers + native plugin. **W0–W7 + P3 + W8** (middleware, CRUD+FTS, security, SEO/RSS, upload/gallery, RBAC, sitemap, favicon/head/images). **Browser embed (v0.3.2+)**: `web.client_embed` mounts WASM client scripts — build with `marqdo wasm build`; examples: examples/browser-hello/. Design: doc/design/ext-web.md · capabilities: doc/design/web-net-capabilities.md · WASM: doc/adr/0002-browser-marqdo-wasm.md · example: examples/marqdo-blog/
ext/web — HTTP / SQLite·Postgres site helpers + native plugin. **W0–W7 + P3 + W8** (middleware, CRUD+FTS, security, SEO/RSS, upload/gallery, RBAC, sitemap, favicon/head/images). **Browser embed (route D)**: `web.client_embed` auto-mounts WASM (`wasm` + `source` + `boot`) — zero author JS; build with `marqdo wasm build`; examples: examples/browser-hello/ · examples/web-client-site/. Design: doc/design/ext-web.md · capabilities: doc/design/web-net-capabilities.md · WASM: doc/adr/0002-browser-marqdo-wasm.md · roadmap D: doc/roadmap/browser-wasm-d.md · example: examples/marqdo-blog/
ext/quantum — circuits, draw, noise, formula matrix custom gates, Q7 density/viz, Q8 themed SVG (`theme=dark|light|bw`). Design: doc/design/ext-quantum.md · doc/design/ext-quantum-viz-style.md
+1 -1
View File
@@ -34,7 +34,7 @@ ext/llm(大模型)— OpenAI 兼容聊天。设计:doc/design/ext-llm.md
ext/agent(智能体)— 智能体框架 + 原生插件。设计:doc/design/ext-agent.md
ext/web(网页)— HTTP / SQLite 站点助手 + 原生插件。**W0–W7 + P3 + W8**。**浏览器挂载(v0.3.2+)**:`网页.客户端挂载` / `web.client_embed`;先 `marqdo wasm build`;示例 examples/browser-hello/。设计:doc/design/ext-web.md · WASM:doc/adr/0002-browser-marqdo-wasm.md
ext/web(网页)— HTTP / SQLite 站点助手 + 原生插件。**W0–W7 + P3 + W8**。**浏览器挂载(路线 D)**:`网页.客户端挂载` / `web.client_embed` 自动 mount(作者零业务 JS);先 `marqdo wasm build`;示例 examples/browser-hello/ · examples/web-client-site/。设计:doc/design/ext-web.md · WASM:doc/adr/0002-browser-marqdo-wasm.md · 路线 D:doc/roadmap/browser-wasm-d.md
ext/quantum(量子)— 电路、绘图、噪声、公式矩阵自定义门、Q7 密度/高级图、Q8 主题 SVG(`主题=dark|light|bw`)。设计:doc/design/ext-quantum.md · doc/design/ext-quantum-viz-style.md
+5 -4
View File
@@ -26,9 +26,10 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.
4. **Do not invent keywords** `if` / `else` / `while` / `for` / `def` / `return`. Control flow is Markdown: **`+` params** (under heading), **`1.` `2.` … branches**, **`-` loops**, arm `N. *` = else, `#` = **object/type**, `##`+ = **function/method**, `**…**` = return.
5. **Identifiers use backticks** — params `` + `name` ``. **Exemptions:** foreach `` - [item](coll) ``; footnote `` name[^key] ``; **inside italic `*…*` / bold `**…**`**, bare ids are **variables** (Python-style unified namespace) and method-call receivers are bare too. **Drop the backticks on value-expression variable names and method receivers inside `*…*` / `**…**`** — they are redundant once the `*…*`/`**…**` markers mark the segment as code: `*分类 = 分类[^苹果]*`, `**n * 2**`, `*p = > page.主体装配 组件=home*`. **Text literals must be quoted**: `*a = > text.split value=src sep=","*`. Backticks **still required** where a bare word is *not* a variable in **standalone `>` calls** (bare = text there): `` > str `n` ``, `` > `obj`.method ``. **No trailing space** inside `*…*` / `**…**` wrapped code: the closing marker must touch the last token directly (`*a = 1*`, `**n**`), never `` *a = 1 * ``.
6. **Structure lines are not wrapped in italics.** `#` `>` `+` `-` `|` lines stand alone; use `*…*` only for general statements (bindings / expressions).
7. **Paths:** In bare *expressions* `/` is division. In **call args / param defaults**, unspaced `a/b` and quoted `".marqdo/agent-kb"` are path text — no `json.parse` needed.
7. **Paths:** In bare *expressions* `/` is division. In **call args / param defaults / table cells**, unspaced `a/b` and quoted `".marqdo/agent-kb"` are path text — no `json.parse` needed. Numeric ratios that must stay text use quotes (`"1/5"`, `"16/9"`); bare `1/5` is division.
8. Prefer ending side-effect-only function bodies with a lone `---` or `***` line (or `****` empty return) so later siblings are not swallowed.
9. **`ext/**` never calls `host_*`.** Agent/OKF helpers are plugin names (`agent_kb_*`, …) after `plugin.load`. Do **not** add agent/OKF domain code to `src/host/` (core bloat). See `doc/design/ext-agent.md` §4.
10. **Browser (route C/D):** client logic is Marqdo on WASM ([ADR 0002](../../../doc/adr/0002-browser-marqdo-wasm.md)); async I/O via return effects `fetch`/`after` ([ADR 0003](../../../doc/adr/0003-browser-async-effects.md)); official bridge is **host glue only**. **Author zero business JS** — use `web.client_embed` / `网页.客户端挂载` (`wasm` + `source` + `boot`) or `data-mq-source-url` so bridge `mount`s automatically ([roadmap D](../../../doc/roadmap/browser-wasm-d.md)). DOM effects: `set_text` / `set_value` / `set_attr` / `set_class` / `toggle_class` / `set_html` only on `#trusted*` selectors.
## Markup → meaning (v0.2)
@@ -174,11 +175,11 @@ data/ # sqlite runtime (gitignore)
**Core objects (EN / ZH):** `# page`/`页面`, `# style`/`样式`, `# db`/`数据库`, `# form`/`表单`, `# app`/`应用`, `# auth`/`鉴权`, `# cache`/`缓存`, `# storage`/`存储`.
**Typical flow:** `db.init` → `page.compose_components` + `page.compose_main` → `page.head` / `page.images` / `page.meta` → `app` with `route` / `static` / `icons` / `configure` / `listen`.
**Typical flow:** `db.init` → `page.compose_components` + `page.compose_main` → `page.head` / `page.images` / `page.meta` → `app` with `route` / `static` / `icons` / `configure` / `listen`. For client interactivity: `marqdo wasm build -o static`, then `web.client_embed source="/static/client.mq.md"` (or ZH `网页.客户端挂载`) in page HTML — **no author JS** ([browser-wasm-d.md](../../doc/roadmap/browser-wasm-d.md) · [web-client-site](../../examples/web-client-site/)).
**Shipped surface (W0–W7 + P3 + W8):** middleware + JSON API (`app.configure`); transactions, pagination, FTS search (`db.migrate`, `db.fts`, `db.search`); security (argon2, CSRF, SQLite sessions, login rate limit); SEO / RSS / Markdown (`page.meta`, `route_rss`, `lib/net.markdown_parse`); upload / download / gallery; sitemap / robots / error pages / redirects; RBAC (`app.gate`, user `role`); audit timestamps + FK in `db.init`; ETag on downloads; **W8** site icons (`app.icons` → `/favicon.ico`), head resource tables (`page.head`), image assembly (`make_images` / `page.images`).
**Shipped surface (W0–W7 + P3 + W8 + route D mount):** middleware + JSON API (`app.configure`); transactions, pagination, FTS search (`db.migrate`, `db.fts`, `db.search`); security (argon2, CSRF, SQLite sessions, login rate limit); SEO / RSS / Markdown (`page.meta`, `route_rss`, `lib/net.markdown_parse`); upload / download / gallery; sitemap / robots / error pages / redirects; RBAC (`app.gate`, user `role`); audit timestamps + FK in `db.init`; ETag on downloads; **W8** site icons (`app.icons` → `/favicon.ico`), head resource tables (`page.head`), image assembly (`make_images` / `page.images`); **D** `client_embed` auto-mount + DOM effect helpers (`text_patch` / `dom_patch`).
Design: [ext-web.md](../../doc/design/ext-web.md) · assets: [web-assets-and-images.md](../../doc/design/web-assets-and-images.md) · capability matrix: [web-net-capabilities.md](../../doc/design/web-net-capabilities.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/).
Design: [ext-web.md](../../doc/design/ext-web.md) · assets: [web-assets-and-images.md](../../doc/design/web-assets-and-images.md) · capability matrix: [web-net-capabilities.md](../../doc/design/web-net-capabilities.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/) · client: [examples/web-client-site/](../../examples/web-client-site/).
Web patterns: [examples.md](examples.md) §13 · API index: [reference.md](reference.md).
+38 -4
View File
@@ -1,11 +1,16 @@
#!/usr/bin/env node
/**
* WASM ABI smoke (C1/C3): boot counter.mq.md, call bump twice.
* WASM ABI + bridge helpers smoke (C1/C3/D1).
* Usage: node tests/wasm/smoke.mjs [path/to/marqdo_wasm.wasm]
*/
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { fileURLToPath, pathToFileURL } from "url";
import {
normalizeMountOptions,
eventArgsFromDom,
applyDomPatch,
} from "../../crates/marqdo-wasm/js/marqdo-bridge.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(__dirname, "../..");
@@ -67,8 +72,8 @@ 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", {});
const c1 = call("bump", { event: "click" });
const c2 = call("bump", { event: "click", value: "x" });
if (!c1.ok || !c2.ok) {
console.error("call failed", c1, c2);
process.exit(1);
@@ -77,4 +82,33 @@ if (c2.value?.set_text?.["#count"] !== "2") {
console.error("expected count 2, got", c2.value);
process.exit(1);
}
const norm = normalizeMountOptions({
dataset: {
mqWasm: "./w.wasm",
mqSourceUrl: "./c.mq.md",
mqReady: "#log",
mqEnable: "#a,#b",
},
});
if (norm.wasmUrl !== "./w.wasm" || norm.sourceUrl !== "./c.mq.md") {
console.error("normalizeMountOptions failed", norm);
process.exit(1);
}
const args = eventArgsFromDom(
{ type: "input", target: { value: "Ada", id: "name" } },
"",
);
if (args.value !== "Ada" || args.event !== "input") {
console.error("eventArgsFromDom failed", args);
process.exit(1);
}
// DOM patch without document should no-op
applyDomPatch({ set_text: { "#x": "y" }, set_value: { "#i": "1" } });
console.log("wasm smoke ok");
console.log("bridge helpers ok");
// silence unused
void pathToFileURL;