Compare commits

...
17 Commits
Author SHA1 Message Date
cflmyandCursor ff1b846b73 release: v0.3.3 — browser author-zero-JS routes D/E/F
Ship host effects through media APIs, lib/browser + GFM authoring,
and marqdo-dev skill; bump crate versions and release docs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 10:13:28 +08:00
cflmyandCursor ad47d4a0d2 chore: gitignore browser-media wasm build artifact
Keep the example source and bridge; rebuild wasm via marqdo wasm build.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 10:06:03 +08:00
cflmyandCursor c080b79c5b feat(wasm): route F host media APIs + GFM-first browser authoring
Ship bridge effects for file/canvas/audio/observers/drag-drop with
browser-media demo; add lib/browser and marqdo-dev skill so clients
use tables/helpers instead of json.set glue.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 10:05:46 +08:00
cflmyandCursor f19f614e0d feat(wasm): finish route E gaps — multi-DOM, cookies, app CRUD/net
querySelectorAll patches, add/remove_class, append_html, remove,
clipboard/download, cookie storage; browser-app list delete + fetch_all/ws
panel. Mark E completed; plan F for file/canvas/media.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 09:11:36 +08:00
cflmyandCursor 8fbf617e05 feat(wasm): route E host effects for author-zero-JS frontend
Expand the official bridge with style/focus/list/navigate/storage/ws/
fetch_all/interval effects; relax the design rule to forbid only
author-written JS. Add browser-app demo and L1 list_html/dom_patch keys.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 09:06:21 +08:00
cflmyandCursor a9d30cdf4a 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>
2026-09-04 08:46:05 +08:00
cflmyandCursor 4c27c8afeb docs(release-skill): note gh auth via git credential fill
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 11:26:21 +08:00
cflmyandCursor 9d591674aa chore: sync Cargo.lock versions for v0.3.2
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 11:18:29 +08:00
cflmyandCursor e40d21760a release: v0.3.2 — browser WASM route C + release skill
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 11:18:13 +08:00
cflmyandCursor 2445c290c9 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>
2026-09-01 11:05:43 +08:00
cflmyandCursor 04890e0c73 feat(wasm): C5 release-wasm size profile and build reporting
Add opt-level=z/LTO strip profile, print KiB from marqdo wasm build,
optional wasm-opt, and document tree-only browser sessions.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 10:58:42 +08:00
cflmyandCursor ab52db2037 feat(wasm): C4 async fetch/after effects with bridge continuations
Accept ADR 0003: handlers return fetch/after maps; the official bridge
runs Promise/timer work and resumes via mq_call. Add fetch.mq.md demo.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 10:53:11 +08:00
cflmyandCursor aac896b044 feat(wasm): C2/C3 session boot, wire events, and interact demo
Add BrowserSession with shared entry env, mq_boot/mq_call exports,
marqdo wasm build, and a counter page driven only by counter.mq.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 10:48:46 +08:00
cflmyandCursor fb037022ba docs(wasm): document raw mq_* ABI for C1 exports
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 10:38:15 +08:00
cflmyandCursor a75b7a1c87 feat(wasm): C0/C1 browser Marqdo interpreter on wasm32
Feature-gate host/CLI deps for wasm-core, add run_source, and ship
crates/marqdo-wasm with a raw mq_run ABI plus examples/browser-hello.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 10:37:44 +08:00
cflmyandCursor f2fd4fb34e docs: lock browser Marqdo WASM plan (ADR 0002, C0–C5)
Accept route C: ship the interpreter/VM on wasm32 with a thin JS host
bridge, not transpile-to-JS. Add design, roadmap, and cross-links.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 10:06:56 +08:00
cflmyandCursor 2079577314 fix(web): admin layout, ext add native, keyframes; document quoted CSS ratios
Widen admin main/table display, ensure marqdo ext add builds/copies the
native plugin before mq install, and emit valid @keyframes from style
tables. Prefer quoted cells like "16/9" for CSS values that contain /.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 09:59:03 +08:00
83 changed files with 11647 additions and 270 deletions

No files matched your search

+144
View File
@@ -0,0 +1,144 @@
---
name: marqdo-dev
description: >-
Develop Marqdo programs and libraries the readable way: GFM tables as data,
code-as-documentation, table.put over json.set chains, lib/ext authoring.
Use when writing or refactoring .mq.md, creating lib/* or ext/*, reviewing
Marqdo style, fixing unreadable json glue, or when the user asks how to
develop Marqdo / 如何开发 marqdo.
---
# Marqdo development (author + library)
Read this **before** writing or expanding `.mq.md`. Syntax basics stay in [marqdo](../marqdo/SKILL.md); this skill is the **style and library craft** contract.
## Non-negotiable: code is documentation
A `.mq.md` file must stay readable as Markdown. If a human cannot skim the data and intent without decoding nested `json.set` / `json.append` chains, the code is wrong.
| Prefer | Avoid |
|--------|--------|
| GFM tables for maps, lists, records, wire, commands | Building the same with `json.set` / `json.append` |
| Named library helpers (`web.*`, `browser.*`, `table.*`) | Copy-paste effect-map glue in every handler |
| `table.put` for **one** dynamic key | Long `json.set` pipelines |
| `json.parse` / `json.stringify` / `json.quote` only | Using `json` as a general dict builder |
`lib/json` is for **parse / stringify / quote**. Collection edits use **GFM tables** and **`lib/table`** (`doc/design/stdlib-table.md`).
## How to shape data
### 1. GFM table geometry (memorize)
| Shape | Result |
|-------|--------|
| 1 column | list |
| ≥2 columns, **one** data row | map (headers = keys) |
| ≥2 columns, **many** rows | map of lists (column-oriented) |
| First header `@` / `行` / `row` | **list of maps** (row records) |
Cells are expressions (`doc/design/table-cell-expressions.md`): bare words = text, `` `var` `` = variable, quote paths/`/` ratios.
### 2. Good patterns
**Wire / steps / commands** — `@` record table:
```markdown
`wire` =
| @ | 选择器 | 事件 | 调用 |
|---|--------|------|------|
| 1 | "#bump" | click | bump |
```
**Multi-key return / boot** — map table with variable cells:
```markdown
`boot` =
| wire | set_text |
|------|----------|
| `wire` | `set_text` |
```
**Single dynamic key** — one `table.put` (or a helper), not a json chain:
```markdown
*`set_text` = > table.put in=None at="#log" value=msg*
**> table.put in=None at="set_text" value=set_text**
```
Better still — call a named helper:
```markdown
**> browser.set_text sel="#log" text=msg**
```
### 3. Bad pattern (do not write)
```markdown
*`ret` = > json.set map=None key="set_text" value=…*
*`ret` = > json.set map=ret key="canvas" value=…*
*`cmds` = > json.append list=cmds item=c0*
```
## Writing application `.mq.md`
1. Frontmatter: title + imports (`table`, domain libs). **Do not import `json` unless parsing strings.**
2. `# main`: state binds, then **tables** for wire/config, return boot map via table or helper.
3. `##` handlers: short prose OK; data as tables; return via `browser.*` / `web.*` / one `table.put`.
4. Blank line between comment paragraphs and code.
5. Run `marqdo run path.mq.md` from repo root.
Browser client programs: prefer `import browser:lib/browser.mq.md` (no native plugin). Server sites: `ext/web` + GFM page/style tables.
## Developing libraries (`lib/*`, `ext/*`)
### Goals
- **Authors** see tables and short calls; **library** may hide `table.put` / host calls.
- One concern per helper; name the effect (`set_text`, `canvas`, …), do not expose bag surgery.
- EN + ZH pair when shipping user-facing libs (`lib/browser.mq.md` ↔ `lib/浏览器.mq.md`, `ext/web` ↔ `ext/web/网页.mq.md`).
- `ext/**` never calls `host_*` — use plugins / public lib only (`doc/design/ext-agent.md`).
### Library checklist
- [ ] Public examples use **tables + helpers**, not json glue
- [ ] Helpers documented with a one-line purpose above `##`
- [ ] Defaults on `+` params; omit `None` fields in merged maps
- [ ] No `json.set` chains in new code — use `table.put` / `table.merge` / GFM
- [ ] `marqdo run` on a tiny demo under `examples/` or inline smoke
### Where helpers live
| Need | Place |
|------|--------|
| Browser effect maps (WASM client) | `lib/browser.mq.md` |
| Site HTML / HTTP / DB | `ext/web` classes + compose from tables |
| List/map primitives | `lib/table.mq.md` |
| Parse JSON text | `lib/json.mq.md` only |
## Refactoring existing glue
When editing a file full of `json.set`:
1. Turn static structures into GFM tables.
2. Replace repeated effect shapes with `browser.*` / `web.text_patch` / `web.dom_patch`.
3. Leave at most sparse `table.put` for dynamic keys.
4. Drop `import json:…` if unused.
## Anti-patterns
| Wrong | Right |
|-------|-------|
| `json.set` × N to build boot | GFM map table or `browser`/`web` helper |
| `json.append` to build command list | `@` record table |
| Dummy column to force a 1-key map | `table.put` or helper |
| Importing `ext/web` only for `text_patch` in WASM | `lib/browser` (no native plugin) |
| Unreadable nested maps as “clever” | Flatten into tables humans can read |
## Related
- Syntax: [marqdo/SKILL.md](../marqdo/SKILL.md) · [examples.md](../marqdo/examples.md)
- Tables: `doc/design/stdlib-table.md` · `doc/design/table-cell-expressions.md`
- Browser effects: `doc/roadmap/browser-wasm-e.md` · `doc/roadmap/browser-wasm-f.md`
- Release: [marqdo-release](../marqdo-release/SKILL.md)
+166
View File
@@ -0,0 +1,166 @@
---
name: marqdo-release
description: >-
Run a full Marqdo product release: detect latest version and ask the user for
the next tag, update CHANGELOG/README/skills/public docs, bump Cargo versions,
sync VS Code extension on branch vscode-extension when needed, build or
trigger install assets (CLI, stdlib, ext, public zip, VSIX, wasm notes), push
tag, publish GitHub Release with detailed notes, and recover from network
failures via proxy. Use when the user asks to release, cut a version, publish
vX.Y.Z, ship a GitHub release, 发版, 发布新版本, or tag marqdo.
---
# Marqdo release
Canonical release playbook for **cflmy/marqdo**. Read this skill **before** tagging or uploading assets. Details: [reference.md](reference.md).
## Hard rules
1. **Never invent the next version.** Detect current versions → **stop and ask the user** for the next SemVer (`X.Y.Z`). Do not proceed until they confirm.
2. **Never force-push** `main` / tags. **Never** `--no-verify` unless the user explicitly orders it.
3. **Never commit `vscode-extension/` on `main`** (gitignored). Extension source lives only on branch **`vscode-extension`**. See `doc/design/vscode-extension-commit.md`.
4. **Do not release from a dirty tree** (except intentional release commits you create in this flow).
5. **Tag format** is always `vX.Y.Z` matching root `Cargo.toml` `version = "X.Y.Z"`.
6. Prefer **tag push → GitHub Actions** (`.github/workflows/release.yml`) for Windows CLI + VSIX + zips. Local packaging is fallback / verification.
7. After network errors: apply [reference.md § Proxy](reference.md); retry; do not silently skip uploads.
## Defaults (after version is confirmed)
Unless the user overrides, apply these automatically — **do not re-ask**:
| Setting | Default |
|---------|---------|
| Sync / bump `vscode-extension` to same `VER` | **yes** |
| Push `main`, create annotated tag, push tag immediately (trigger CI) | **yes** |
| Release notes language | **中英双语** (Chinese first, then English section, or paired ZH/EN under each heading) |
| Skip VSIX | **no** |
| Docs-only release | **no** (full asset pipeline via CI) |
| Deploy gh-pages after release | **no** (only if user asks) |
Phase 0 asks **only** for the next version (and optional overrides). Example ask:
> 当前最新是 **vA.B.C**。请指定下一个版本号(如 `0.3.2`)。其余按默认:同步扩展、立刻打 tag 发布、中英双语说明。
## Phase 0 — Detect versions (mandatory stop)
Run in repo root (parallel OK):
```bash
python3 .cursor/skills/marqdo-release/scripts/detect_version.py
# or: rg / git tag / gh release list — see reference.md
```
Report briefly, then **ask only for the next SemVer** (defaults above). Wait for confirmation. Normalize to `VER=X.Y.Z` and `TAG=vX.Y.Z`.
## Phase 1 — Preflight
Copy and track:
```
Release progress:
- [ ] Phase 0: version confirmed by user (TAG=…)
- [ ] Phase 1: preflight green
- [ ] Phase 2: docs + version bumps committed
- [ ] Phase 3: extension branch (if needed)
- [ ] Phase 4: main pushed; tag created & pushed
- [ ] Phase 5: CI / assets / release notes verified
- [ ] Phase 6: post-release checks
```
Checks:
1. `git status` clean or only release WIP you control.
2. `git checkout main && git pull --ff-only origin main`.
3. Quick gate: `cargo test --test gold structure_hello` (and any release-critical tests the user named). Full gold suite if time allows.
4. `CHANGELOG.md` has meaningful **Unreleased** notes; if empty, draft from `git log vLAST..HEAD --oneline` and confirm with user.
5. Confirm no secrets in the commit (`*.env`, credentials).
## Phase 2 — Docs & version bumps (main)
Bump **in lockstep**:
| File | Change |
|------|--------|
| `Cargo.toml` | `version = "VER"` |
| `crates/marqdo-wasm/Cargo.toml` | same `VER` |
| `CHANGELOG.md` | Move `## Unreleased` → `## vVER — YYYY-MM-DD`; leave fresh empty `## Unreleased` |
| `README.md` | 「现状 / 如何使用最新」version strings, checkout tag, release URL |
| `.cursor/skills/marqdo/SKILL.md` | Version-sensitive bullets if any (WASM/web status); keep rules accurate |
| `public/**` | User-facing tutorials if features shipped (welcome, features/*, extensions). Prefer small factual updates over rewrites |
| `doc/roadmap/*.md` | Mark shipped waves done if this release closes them |
| `.github/workflows/release.yml` | Update **Highlights** body template to this release (CI still uses hardcoded blurb—keep in sync) |
Public HTML: regenerate before packaging / pages deploy:
```bash
./scripts/build-public.sh
# outputs under public/ (gitignored HTML); used by release zip / gh-pages
```
Commit on `main` (HEREDOC message), e.g.:
```text
release: vVER — <one-line highlight>
EOF
```
Push `main`: `git push origin main` (with proxy/`all` perms if needed).
## Phase 3 — VS Code / Cursor extension
**Default: always** bump extension to `VER` on branch `vscode-extension` (skip only if user said so).
1. `git fetch origin vscode-extension`
2. Work on `vscode-extension` branch (not main):
- Bump `vscode-extension/package.json` `version` to `VER`.
- Update `engines` / CLI version hints in extension README if present.
- `npm ci && npm run compile`
3. Commit & `git push origin vscode-extension`.
4. Return to `main`. **Do not** add `vscode-extension/` to main.
## Phase 4 — Tag & trigger CI
```bash
git tag -a "TAG" -m "TAG"
git push origin "TAG"
```
This runs `.github/workflows/release.yml` (Windows): CLI exe/zip, stdlib zip, ext zip, source zip, public zip, VSIX.
If tag push fails: [reference.md § Proxy](reference.md), retry once; then report.
## Phase 5 — Release notes & assets
1. Wait for Actions success: `gh run list --workflow=Release --limit 3` / open the run URL.
2. Ensure GitHub Release for `TAG` exists with assets (workflow uses `softprops/action-gh-release`).
3. **Rewrite release body** (workflow body is a stub) with **中英双语** — see [reference.md § Notes template](reference.md). `gh release edit TAG --notes-file …`.
4. Include: Highlights, Breaking, Install (`ext add`, plugins build), Downloads table, WASM (`marqdo wasm build`), links to CHANGELOG/README, extension branch note.
5. Optional Linux local extras (not required if CI green): `marqdo wasm build` smoke; document in notes that wasm is built from source via CLI.
Local Windows fallback: `scripts/release-full.ps1 -Tag TAG -Upload` (see script header).
## Phase 6 — Post-release
1. `gh release view TAG` — confirm assets + notes.
2. `git status` clean; `main` synced.
3. Tell user: release URL `https://github.com/cflmy/marqdo/releases/tag/TAG`.
4. Optional: `./scripts/deploy-public.ps1` / pages workflow if user wants user-site refresh.
5. Open fresh `## Unreleased` already done in Phase 2.
## Failure matrix (short)
| Failure | Action |
|---------|--------|
| `gh` / git TLS or proxy `7890` refused | Unset bad proxy; use working `HTTP(S)_PROXY` or `required_permissions: ["all"]`; see reference |
| Tag exists | Stop; ask user to bump or delete tag (no force on shared tags without explicit order) |
| CI red | Fix on main, move tag only if user explicitly allows delete+re-push tag |
| VSIX missing | Fetch `vscode-extension`, build locally, `gh release upload TAG dist/*.vsix` |
| Partial assets | Re-run workflow or upload missing files only |
## Do not
- Ship without user-confirmed version.
- Hardcode release highlights only in Actions YAML and forget CHANGELOG.
- Commit `target/`, `dist/`, `*.wasm`, or `public/**/*.html` unless project policy changes.
- Merge extension tree into `main`.
+305
View File
@@ -0,0 +1,305 @@
# Marqdo release — reference
Companion to [SKILL.md](SKILL.md). Use during a release; keep SKILL short.
## Detect versions (commands)
```bash
# From repo root
python3 .cursor/skills/marqdo-release/scripts/detect_version.py
# or manually:
git fetch --tags origin 2>/dev/null || true
echo "Cargo: $(sed -n 's/^version = \"\(.*\)\"/\1/p' Cargo.toml | head -1)"
echo "wasm: $(sed -n 's/^version = \"\(.*\)\"/\1/p' crates/marqdo-wasm/Cargo.toml | head -1)"
echo "tags: $(git tag -l 'v*' --sort=-v:refname | head -3 | tr '\n' ' ')"
gh release list --limit 3 2>/dev/null || true
```
**SemVer guidance for the ask (do not choose for the user):**
| Kind | When |
|------|------|
| patch `x.y.(z+1)` | Fixes, docs, no public API / MQ surface break |
| minor `x.(y+1).0` | New features (WASM route C, new ext APIs) backward compatible |
| major `(x+1).0.0` | Breaking MQ / CLI / plugin ABI |
## Asset matrix (CI tag `v*`)
Produced by `.github/workflows/release.yml` on **windows-latest**:
| Asset | Role |
|-------|------|
| `marqdo-VER-x86_64-pc-windows-msvc.exe` | CLI (stdlib embedded) |
| `marqdo-VER-x86_64-pc-windows-msvc.zip` | `marqdo.exe` + `lib/` |
| `marqdo-VER-stdlib.zip` | `lib/` only |
| `marqdo-VER-ext.zip` | Official `ext/` L1 |
| `marqdo-VER-source.zip` | `git archive` of tagged commit |
| `marqdo-VER.vsix` | VS Code / Cursor (from branch `vscode-extension`) |
| `marqdo-VER-public.zip` | Static user docs (`marqdo view output public`) |
Not CI-uploaded (document in notes): Linux/macOS build from source; WASM via `marqdo wasm build` → `dist/wasm/`.
## Doc sync checklist (Phase 2 detail)
### CHANGELOG.md
1. Ensure `## Unreleased` lists everything shipping.
2. Rename to `## vVER — YYYY-MM-DD` (use release day in Asia/Shanghai unless user says otherwise).
3. Add a short **Highlights** subsection (install snippet + 3–6 bullets).
4. Insert empty:
```markdown
## Unreleased
### Added
### Fixed
### Changed
```
### README.md
Update every user-visible version pin, typically:
- Section title `## 现状(vVER)`
- `### 如何使用最新 Marqdo(vVER)`
- `git checkout vVER`
- Release URL `…/releases/tag/vVER`
Keep install / `ext add` / plugin build instructions accurate for this release.
### `.cursor/skills/marqdo/SKILL.md`
- Sync hard rules / feature bullets that this release changes (e.g. WASM, web).
- Do **not** dump full CHANGELOG into the skill.
- If release-only process changed, point to `.cursor/skills/marqdo-release/`.
### `public/` (author Markdown sources)
User tutorials under `public/` (not generated HTML). Update when:
- New CLI (`marqdo wasm …`, `ext add`, `version`)
- New tutorials (browser hello, web client embed)
- Version badges / “requires vVER” lines
Then regenerate HTML for zip/pages:
```bash
./scripts/build-public.sh
# Windows: powershell -File ./scripts/build-public.ps1
```
HTML under `public/**/*.html` is typically gitignored — zip still ships from CI `marqdo view output public`.
### Workflow stub
Edit `.github/workflows/release.yml` `body:` **Highlights** so the first auto body matches this tag (agent still replaces with full notes via `gh release edit`).
### Roadmaps / ADRs
If this release closes a wave: set status Completed in `doc/roadmap/*`; leave ADRs immutable (link from CHANGELOG).
## Extension checklist (Phase 3 detail)
Branch policy: `doc/design/vscode-extension-commit.md`.
```bash
git fetch origin vscode-extension
git checkout vscode-extension
# edit vscode-extension/package.json version → VER
# npm ci && npm run compile
git add vscode-extension/
git commit -m "$(cat <<'EOF'
vscode-extension: bump to VER for release
EOF
)"
git push origin vscode-extension
git checkout main
```
Local VSIX only (fallback):
```bash
git fetch origin vscode-extension
git checkout origin/vscode-extension -- vscode-extension
(cd vscode-extension && npm ci && npm run compile && npx @vscode/vsce package --no-dependencies -o "../dist/marqdo-VER.vsix")
# cleanup ignored tree if desired
gh release upload "vVER" "dist/marqdo-VER.vsix" --clobber
```
## Defaults (mirror of SKILL)
| Setting | Default |
|---------|---------|
| Sync `vscode-extension` to `VER` | yes |
| Push main + annotated tag immediately | yes |
| Release notes | 中英双语 |
| Skip VSIX / docs-only / deploy pages | no |
Phase 0 asks **only** for the next version unless the user wants overrides.
## Notes template (中英双语 — default)
Save as `/tmp/marqdo-vVER-notes.md` then:
```bash
gh release edit "vVER" --notes-file /tmp/marqdo-vVER-notes.md
```
```markdown
## Marqdo vVER
### 亮点 / Highlights
- **中文** … / **EN** …
- …
### 安装 / Install
```bash
git clone https://github.com/cflmy/marqdo.git && cd marqdo
git checkout vVER
cargo build --release
./target/release/marqdo version
cargo build --release -p marqdo_plugin_web -p marqdo_plugin_agent -p marqdo_plugin_quantum
marqdo ext add web && marqdo ext add agent && marqdo ext add quantum
# 中文 id:网页 / 智能体 / 量子
```
**浏览器 WASM / Browser WASM**
```bash
marqdo wasm build
# → dist/wasm/marqdo_wasm_bg.wasm + marqdo-bridge.js
# examples: examples/browser-hello/
```
### 破坏性变更 / Breaking changes
- 无 / None
- …
### 下载 / Downloads
| Asset | 内容 / Contents |
|-------|-----------------|
| `marqdo-*-windows-msvc.exe` | CLI(内置 stdlib) |
| `marqdo-*-windows-msvc.zip` | exe + `lib/` |
| `marqdo-*-stdlib.zip` | 仅 `lib/` |
| `marqdo-*-ext.zip` | 官方 `ext/` |
| `marqdo-*-source.zip` | 源码快照 |
| `marqdo-*.vsix` | VS Code / Cursor 扩展 |
| `marqdo-*-public.zip` | 用户文档站 |
扩展源码分支 / Extension branch: **`vscode-extension`** ([policy](https://github.com/cflmy/marqdo/blob/main/doc/design/vscode-extension-commit.md)).
### 链接 / Links
- [CHANGELOG](https://github.com/cflmy/marqdo/blob/main/CHANGELOG.md)
- [README](https://github.com/cflmy/marqdo/blob/main/README.md)
```
## Proxy & auth (network recovery)
Symptoms seen in this project: broken local proxy on `127.0.0.1:7890`, TLS failures, `gh` needing token, Cursor sandbox blocking git/gh.
### Diagnose
```bash
env | grep -iE 'proxy|PROXY' || true
curl -sI https://github.com | head -5
gh auth status
```
### Fix order
1. **Unset bad proxy** if connection refused:
```bash
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY all_proxy
```
2. **Set a working proxy** only if the user provides one (or known working):
```bash
export HTTPS_PROXY=http://HOST:PORT
export HTTP_PROXY=http://HOST:PORT
```
3. **Agent Shell**: retry `git push` / `gh` with `required_permissions: ["all"]` (and `full_network` if needed).
4. **`gh` auth**: if `gh auth status` fails, ask user to `gh auth login` or set `GH_TOKEN` / `GITHUB_TOKEN` for the session — **never commit tokens**. Fallback used in this repo: load password from `git credential fill` (`protocol=https` / `host=github.com`) into `GH_TOKEN` for the session only, then delete the temp env file.
5. **Git remote**: prefer `https://github.com/cflmy/marqdo.git`; SSH needs keys.
6. **Partial upload**:
```bash
gh release upload "vVER" dist/FILE --clobber
```
7. **Re-run CI** without retagging (if tag already correct):
```bash
gh workflow run Release --ref "vVER" # only if workflow_dispatch exists; else fix + new patch tag
```
Current Release workflow is **tag-push only**. Red CI after tag → fix on `main`, then either new patch tag or **user-approved** delete+recreate tag (dangerous; prefer patch).
## Local Windows fallback
```powershell
powershell -File ./scripts/release-full.ps1 -Tag vVER -Upload
# -SkipVsix / -SkipPublic / -DeployPages as needed
```
Also: `scripts/release-windows.ps1`, `scripts/publish-release.py` if present.
## Commit message style
```text
release: vVER — <highlight>
```
Extension:
```text
vscode-extension: bump to VER for release
```
## Pre-tag test suggestions
Minimum:
```bash
cargo test --test gold structure_hello
./target/release/marqdo version # after cargo build --release
```
Stronger (time permitting):
```bash
cargo test --test gold
cargo test -p marqdo-wasm -- --nocapture # if wasm tests exist
# optional Node: node tests/wasm/smoke.mjs after marqdo wasm build
```
## Ask-user prompt (copy)
```text
版本探测结果:
- Cargo.toml: A.B.C
- crates/marqdo-wasm: …
- 最新 git tag: v…
- 最新 GitHub Release: v…
- CHANGELOG Unreleased: 有 / 无(摘要:…)
请指定下一个版本号(例如 0.3.2)。
默认(无需确认):同步 vscode-extension 同号、立刻 push tag 发版、发布说明中英双语。
若要改默认请一并说明。
```
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Detect Marqdo version sources for release Phase 0. Never invent next SemVer."""
from __future__ import annotations
import re
import subprocess
import sys
from pathlib import Path
# …/marqdo/.cursor/skills/marqdo-release/scripts/this.py → parents[4] = repo root
ROOT = Path(__file__).resolve().parents[4]
def cargo_version(path: Path) -> str | None:
if not path.is_file():
return None
m = re.search(r'^version\s*=\s*"([^"]+)"', path.read_text(encoding="utf-8"), re.M)
return m.group(1) if m else None
def run(cmd: list[str]) -> str:
try:
out = subprocess.check_output(cmd, cwd=ROOT, stderr=subprocess.DEVNULL, text=True)
return out.strip()
except (subprocess.CalledProcessError, FileNotFoundError):
return ""
def main() -> int:
cargo = cargo_version(ROOT / "Cargo.toml")
wasm = cargo_version(ROOT / "crates" / "marqdo-wasm" / "Cargo.toml")
tags = run(["git", "tag", "-l", "v*", "--sort=-v:refname"])
latest_tag = tags.splitlines()[0] if tags else "(none)"
gh_list = run(["gh", "release", "list", "--limit", "3"])
latest_gh = "(gh unavailable)"
if gh_list:
# first column is tag name for `gh release list`
latest_gh = gh_list.splitlines()[0].split("\t")[0].strip()
changelog = ROOT / "CHANGELOG.md"
unreleased = False
unreleased_preview = ""
if changelog.is_file():
text = changelog.read_text(encoding="utf-8")
m = re.search(r"^## Unreleased\s*\n(.*?)(?=^## |\Z)", text, re.M | re.S)
if m:
body = m.group(1).strip()
# nonempty if any bullet or non-heading content beyond empty section headers
content_lines = [
ln
for ln in body.splitlines()
if ln.strip() and not re.match(r"^###\s+", ln.strip())
]
unreleased = bool(content_lines)
unreleased_preview = " | ".join(content_lines[:3])[:200]
print("=== Marqdo version detect (do NOT invent next; ask the user) ===")
print(f"repo: {ROOT}")
print(f"Cargo.toml: {cargo or '(missing)'}")
print(f"marqdo-wasm: {wasm or '(missing)'}")
print(f"latest git tag: {latest_tag}")
print(f"latest gh release: {latest_gh}")
print(f"Unreleased notes: {'YES' if unreleased else 'NO/empty'}")
if unreleased_preview:
print(f"Unreleased peek: {unreleased_preview}")
if cargo and latest_tag.lstrip("v") != cargo:
print("WARN: Cargo version != latest tag (expected during pre-bump or lag)")
if cargo and wasm and cargo != wasm:
print("WARN: root Cargo.toml and marqdo-wasm versions differ — sync before release")
print()
print("ASK USER: next SemVer X.Y.Z (tag will be vX.Y.Z)")
return 0
if __name__ == "__main__":
sys.exit(main())
+15 -4
View File
@@ -16,6 +16,10 @@ Marqdo = **Markdown markers as syntax**. A `.mq.md` file is both documentation a
Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.md`. Deeper tables: [reference.md](reference.md). Copy-paste patterns: [examples.md](examples.md).
**Authoring / library craft** (GFM-first, no json glue, how to develop Marqdo): use **[marqdo-dev](../marqdo-dev/SKILL.md)** whenever writing or refactoring `.mq.md`, `lib/*`, or `ext/*`.
**Product release** (tag, CHANGELOG, README, public docs, VSIX, GitHub assets): use [marqdo-release](../marqdo-release/SKILL.md) — detect latest version, **ask the user for the next SemVer**, then follow that playbook. Do not invent a version number.
## Hard rules (do not violate)
1. **File suffix** must be `.mq.md` (never plain `.md` for executable sources).
@@ -24,9 +28,12 @@ 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/E/F):** client logic is Marqdo on WASM; official bridge is host glue and **may** implement lists, routing, storage, WebSocket, canvas, file read, observers — authors **must not hand-write business JS**. Use `web.client_embed` / `data-mq-source-url` auto-mount. Client effects: prefer **GFM tables + `lib/browser`** ([marqdo-dev](../marqdo-dev/SKILL.md)).
11. **Code-as-documentation / no bag glue:** Prefer **GFM tables** for maps, lists, wire, commands. Prefer **`table.put` / named helpers** over `json.set` / `json.append` chains. `lib/json` is for parse/stringify/quote only — not a dict builder. Unreadable json pipelines are a style bug.
## Markup → meaning (v0.2)
@@ -172,11 +179,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_*` → `app` + `static` / `listen`. Client: `marqdo wasm build -o static` + `web.client_embed source="/static/client.mq.md"` — **no author JS**; bridge may implement rich host effects ([browser-wasm-e.md](../../doc/roadmap/browser-wasm-e.md) · [browser-app](../../examples/browser-app/)).
**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).
@@ -225,7 +232,9 @@ Design: [ext-quantum.md](../../doc/design/ext-quantum.md) · Q7: [ext-quantum-q7
| Forgetting `---` after nested `##` helper | Add `---` / `***` / `****` |
| Import `lib/text` then call bare `split` | `> text.split …` (qualified) |
| Import `lib/text` then call `拆分` | Match file language (`text.split`, not 文本) |
| `json.set` / `json.append` to build maps or lists | GFM tables; sparse `table.put`; named helpers (`browser.*`, `web.*`) |
| `json.set` to build page parts | GFM tables + `page.compose_*` / `web.page` methods |
| Import `json` for every browser handler | `import browser:lib/browser.mq.md` + tables ([marqdo-dev](../marqdo-dev/SKILL.md)) |
| Mix `web.page` and `网页.页面` in one file | One import language per `.mq.md` |
| Call `host_web_*` from `ext/web` | Use `# app` / `# db` methods; plugin ABI only |
| Call `host_*` from `ext/quantum` | Use `# circuit` / `# density` methods; plugin ABI only |
@@ -241,6 +250,8 @@ Design: [ext-quantum.md](../../doc/design/ext-quantum.md) · Q7: [ext-quantum-q7
- [ ] `# main` exists when the file is an entry program
- [ ] Nested functions ended with `---` / `***` / `****` when needed
- [ ] Imports and call names share the same language file
- [ ] Data shaped as **GFM tables** (or short helpers) — no `json.set` / `json.append` glue
- [ ] Web sites: tables + web classes only (no JSON glue); `data/` gitignored
- [ ] Browser client: `lib/browser` + tables when returning effects
- [ ] Quantum draw: quote `kind=` / `theme=`; rebuild plugin → `ext add quantum` before view
- [ ] `marqdo run` succeeds (or errors addressed)
+26
View File
@@ -78,6 +78,7 @@ Greeting via a nested function:
> print text=`果`
```
## 6b. Map table + footnote get
```markdown
@@ -109,6 +110,31 @@ Row-oriented records (SQL-like): first header `@` / `行` / `row` → list of ma
*名 = 订单[^1][^品名]*
```
## 6c. Browser effects — tables + lib/browser (not json.set)
```markdown
---
import browser:lib/browser.mq.md
---
# main
`wire` =
| @ | 选择器 | 事件 | 调用 |
|---|--------|------|------|
| 1 | "#bump" | click | bump |
**`wire`**
## bump
*`count` = count + 1*
*`label` = > str count*
**> browser.set_text sel="#count" text=label**
```
Do **not** build effect maps with `json.set` chains. See [marqdo-dev](../marqdo-dev/SKILL.md).
## 7. Import text stdlib
```markdown
+2 -1
View File
@@ -44,12 +44,13 @@ Import one file; use **that** file’s function names.
|-----------|-----------|-------------------------|
| `lib/text.mq.md` | `lib/文本.mq.md` | text helpers / 去空白·拆分·拼接… |
| `lib/table.mq.md` | `lib/表.mq.md` | `put`/`改` + list/map(见 `doc/design/stdlib-table.md`) |
| `lib/browser.mq.md` | `lib/浏览器.mq.md` | WASM client effect helpers(GFM + `set_text`/`canvas`/…;见 marqdo-dev) |
| `lib/fs.mq.md` | `lib/文件.mq.md` | filesystem |
| `lib/sys.mq.md` | `lib/系统.mq.md` | process / cwd / load_dotenv |
| `lib/plugin.mq.md` | `lib/插件.mq.md` | load native ABI plugins (`doc/design/ext-abi.md`) |
| `lib/time.mq.md` | `lib/时间.mq.md` | time/format |
| `lib/net.mq.md` | `lib/网络.mq.md` | HTTP(S) helpers (+ optional headers) |
| `lib/json.mq.md` | (see design) | JSON (+ `quote`) |
| `lib/json.mq.md` | (see design) | **parse / stringify / quote only** — not a dict builder |
| `lib/math.mq.md` | `lib/数学.mq.md` | num, trig, random, formula, plot |
| `lib/foreign.mq.md` | `lib/外联.mq.md` | run foreign fenced blocks |
| `ext/llm.mq.md` | `ext/大模型.mq.md` | `# llm` / `# 大模型` object + chat methods |
+4 -4
View File
@@ -92,10 +92,10 @@ jobs:
body: |
## Marqdo ${{ github.ref_name }}
### Highlights — v0.3.1
- **W8**: favicon / head assets / image assembly (`app.icons`, `page.head`, `make_images`)
- Fix: absolute `entry_dir` for relative entry scripts (no nested `tests/ext/tests/ext`)
- **`ext/web`**: W0–W7 + P3 + W8; **`ext/quantum`** Q7/Q8; **`ext/agent`** A1–A4
### 亮点 / Highlights — v0.3.3
- **浏览器作者零业务 JS(D/E/F)**:bridge 自启;DOM/路由/storage/ws/文件/Canvas/音频/Observer/拖放;`lib/browser` + GFM
- **Browser author-zero-JS (routes D/E/F)**: host effects + `lib/browser`; examples `browser-hello` / `browser-app` / `browser-media`
- Skill: `marqdo-dev`(代码即文档 / 禁止 json.set 胶水)
- Install: `marqdo ext list` / `marqdo ext add llm|agent|web|quantum`
- Native plugins: `cargo build --release -p marqdo_plugin_*` then `ext add`
- Details: [CHANGELOG](https://github.com/cflmy/marqdo/blob/main/CHANGELOG.md) · [README](https://github.com/cflmy/marqdo/blob/main/README.md)
+7
View File
@@ -39,6 +39,13 @@ spike/.pytest_cache/
**/__pycache__/
*.pyc
# 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
/examples/browser-app/marqdo_wasm.wasm
/examples/browser-media/marqdo_wasm.wasm
# Local sqlite / scratch
/data/
/tmp/
+58
View File
@@ -2,6 +2,64 @@
## Unreleased
### Added
### Fixed
### Changed
## v0.3.3 — 2026-09-04
### Highlights
**浏览器作者零业务 JS(路线 D/E/F)**:官方 bridge 自启 + 宿主效应补齐(DOM/路由/storage/ws/文件/Canvas/音频/Observer/拖放);`lib/browser` + GFM 表格写法;新增 [marqdo-dev](.cursor/skills/marqdo-dev/SKILL.md) 开发约定。
```bash
git checkout v0.3.3
cargo build --release
marqdo wasm build
# examples: browser-hello / browser-app / browser-media / web-client-site
```
### Added
- **路线 D(作者零 JS)**:[roadmap](doc/roadmap/browser-wasm-d.md) · 设计 §16。官方 bridge `mount` / `data-mq-*` 自启;`client_embed` 带 `wasm`/`source`/`boot`;DOM 效应;`examples/web-client-site/`。
- **路线 E(前端补齐)**:[browser-wasm-e.md](doc/roadmap/browser-wasm-e.md)。多节点 DOM、`add_class`/`remove_class`、cookie、clipboard/download、`fetch_all`/`ws`/`interval`;示例 [browser-app](examples/browser-app/)。
- **路线 F(媒体/文件,F1–F5)**:[browser-wasm-f.md](doc/roadmap/browser-wasm-f.md)。`read_file`、Canvas 2D、Audio beep、Intersection/ResizeObserver、drag/drop;示例 [browser-media](examples/browser-media/)。
- **`lib/browser` / `lib/浏览器`**:WASM 客户端效应助手(GFM 表格 + named helpers;勿用 `json.set` 链)。
- **Skill `marqdo-dev`**:代码即文档 / GFM-first / 库开发约定。
### Changed
- 浏览器示例(hello / app / media / web-client)改为表格 + `lib/browser`;`ext/web` 效应助手改用 `table.put`。
- 标准库模块表收录 `browser`;路线 F 收口 F1–F5(F6 Service Worker 仍可选)。
## v0.3.2 — 2026-09-01
### Highlights
**浏览器 Marqdo(路线 C)首版完备**:`wasm-core`、`marqdo wasm build`、会话 ABI、DOM/`fetch`/`after` 效应、官方 bridge、体积与冒烟;并修 Admin 长内容布局、`ext add` 原生插件预检、`@keyframes` 与样式表 `/` 比率约定。
```bash
git checkout v0.3.2
cargo build --release
marqdo wasm build
marqdo ext add web # 改插件后请重新 add
```
### Added
- **浏览器 Marqdo(路线 C)**: [ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [design](doc/design/browser-marqdo-wasm.md) · [roadmap C0–C5](doc/roadmap/browser-wasm.md)。
- **C0/C1**:`wasm-core` feature 门控;`run_source`;crate `crates/marqdo-wasm`(`mq_run` ABI);示例 [examples/browser-hello](examples/browser-hello/)。
- **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。
- **发版 Skill**:`.cursor/skills/marqdo-release/`(探测版本 → 用户确认 → 文档/资产/扩展/Release 说明)。
### Fixed
- **Admin UI**:主区取消 `max-width:56rem` 限制,表格外包可横向滚动的 `.table-wrap`,单元格完整展示并自动换行;表单加宽且 textarea 可随内容增高。
- **`marqdo ext add`**:安装含原生插件的扩展时**先**定位/自动 `cargo build` 再拷贝 `.mq.md`,避免只装上文稿、运行时报 `native plugin not found`;扩大 `.so` 搜索路径。
- **`web_style` / 样式装配**:正确输出 `@keyframes` 块(停点为嵌套规则,不再写成 `0%: opacity: 0`)。
- **样式表含 `/` 的值**:文档明确**引号优先**(`"16/9"`、`"1/5"`);不引入靠空格消歧的表单元格比率折叠。
## v0.3.1 — 2026-08-29
### Highlights
Generated
+9 -1
View File
@@ -1018,7 +1018,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
[[package]]
name = "marqdo"
version = "0.3.1"
version = "0.3.3"
dependencies = [
"anyhow",
"assert_cmd",
@@ -1040,6 +1040,14 @@ dependencies = [
"zeroize",
]
[[package]]
name = "marqdo-wasm"
version = "0.3.3"
dependencies = [
"marqdo",
"serde_json",
]
[[package]]
name = "marqdo_plugin_agent"
version = "0.1.0"
+41 -9
View File
@@ -1,6 +1,6 @@
[package]
name = "marqdo"
version = "0.3.1"
version = "0.3.3"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo — Markdown markers as an interpreted programming language"
@@ -10,25 +10,48 @@ repository = "https://github.com/cflmy/marqdo"
[[bin]]
name = "marqdo"
path = "src/main.rs"
required-features = ["cli"]
[features]
default = ["native"]
native = ["cli", "view", "net-host", "plugin-host", "exec-host", "fs-host", "tty"]
cli = ["dep:clap"]
view = ["dep:tiny_http"]
net-host = ["dep:ureq", "dep:idna_adapter", "dep:zeroize"]
plugin-host = ["dep:libloading"]
exec-host = []
fs-host = []
tty = ["dep:libc"]
wasm-core = []
[dependencies]
anyhow = "1"
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
clap = { version = "=4.4.18", features = ["derive"] }
clap = { version = "=4.4.18", features = ["derive"], optional = true }
pulldown-cmark = "0.12"
serde_json = "1"
thiserror = "1"
tiny_http = "0.12"
tiny_http = { version = "0.12", optional = true }
# Pin for Cargo/rustc 1.81 (newer rustls/idna/zeroize need edition2024).
ureq = { version = "=2.9.7", default-features = false, features = ["tls", "gzip"] }
idna_adapter = "=1.1.0"
zeroize = "=1.8.1"
libloading = "=0.8.6"
ureq = { version = "=2.9.7", default-features = false, features = ["tls", "gzip"], optional = true }
idna_adapter = { version = "=1.1.0", optional = true }
zeroize = { version = "=1.8.1", optional = true }
libloading = { version = "=0.8.6", optional = true }
include_dir = "0.7"
libc = "0.2"
libc = { version = "0.2", optional = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
# No `wasmbind`: keeps cdylib free of wasm-bindgen imports (raw mq_* ABI).
chrono = { version = "0.4", default-features = false, features = ["alloc", "std"] }
[workspace]
members = ["plugins/demo", "plugins/agent", "plugins/web", "plugins/quantum"]
members = [
"plugins/demo",
"plugins/agent",
"plugins/web",
"plugins/quantum",
"crates/marqdo-wasm",
]
resolver = "2"
[dev-dependencies]
@@ -37,3 +60,12 @@ predicates = "=3.1.0"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "time", "net"] }
tokio-tungstenite = "0.24"
futures-util = "0.3"
# Size-oriented profile for `marqdo-wasm` (C5). Use: cargo build -p marqdo-wasm --profile release-wasm --target wasm32-unknown-unknown
[profile.release-wasm]
inherits = "release"
lto = true
codegen-units = 1
opt-level = "z"
strip = true
panic = "abort"
+12 -7
View File
@@ -99,7 +99,7 @@ marqdo catalog public -o .marqdo
---
## 现状(v0.3.1)
## 现状(v0.3.3)
- 映射与解释器:Phase I 树遍历 + 字节码后端可用;金样例在 `tests/`
- **对象**:`#` = 类型/构造,`##`+ = 函数/方法;见 [objects.md](doc/design/objects.md)
@@ -107,7 +107,7 @@ marqdo catalog public -o .marqdo
- **`marqdo debug`**:独立调试页(断点 / 单步 / locals;默认端口 7430;页面 favicon / 品牌使用官方 Logo)
- **`marqdo catalog` / `sync`**:OKF 风格 YAML + 模块概念页
- **`marqdo version --check`**:与 GitHub 最新 release 对比
- 标准库:**内置于二进制**(v0.1.2+);磁盘 `lib/` 或 `MARQDO_LIB` 可覆盖。模块含文本、文件、系统、时间、JSON、网络、数学、外联、插件、**自写回**、**子任务**
- 标准库:**内置于二进制**(v0.1.2+);磁盘 `lib/` 或 `MARQDO_LIB` 可覆盖。模块含文本、表、**浏览器效应**、文件、系统、时间、JSON、网络、数学、外联、插件、**自写回**、**子任务**
- **官方扩展库 `ext/`**(**非** stdlib,本版收口):
- **`web`**:W0–W7 + P3 + **W8**(favicon / Head 资源 / 图片装配,见 [web-assets-and-images.md](doc/design/web-assets-and-images.md));示例 [marqdo-blog](examples/marqdo-blog/);生产路径见 [web-asgi-servers-and-marqdo.md](doc/design/web-asgi-servers-and-marqdo.md)(反向代理 → 嵌入式 `listen`,非 Daphne/Uvicorn)
- **`quantum`**:Q0–Q7 + Q8a/b 主题 SVG;示例 [quantum-entanglement](examples/quantum-entanglement/)
@@ -117,14 +117,15 @@ 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)
- **浏览器 Marqdo(WASM)**:`marqdo wasm build` + 官方 bridge 自启(作者零业务 JS;桥内可含列表/路由/storage/ws/文件/Canvas/音频/Observer/拖放);`lib/browser` + GFM;`web.client_embed`;示例 [browser-hello](examples/browser-hello/) · [browser-app](examples/browser-app/) · [browser-media](examples/browser-media/) · [web-client-site](examples/web-client-site/)([ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [D](doc/roadmap/browser-wasm-d.md) · [E](doc/roadmap/browser-wasm-e.md) · [F](doc/roadmap/browser-wasm-f.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)
### 如何使用最新 Marqdo(v0.3.3)
```bash
# 1) 源码安装(跟 tag 或 main)
git clone https://github.com/cflmy/marqdo.git && cd marqdo
git checkout v0.3.1 # 或留在 main
git checkout v0.3.3 # 或留在 main
cargo build --release
export PATH="$PWD/target/release:$PATH"
marqdo version
@@ -148,8 +149,12 @@ marqdo ext add llm # 或:大模型
marqdo run examples/marqdo-blog/index.mq.md
# 浏览器打开终端打印的 listen 地址;/favicon.ico 与 logo 装配见 W8
# 5) Windows:也可从 GitHub Releases 下载 exe / zip / vsix
# https://github.com/cflmy/marqdo/releases/tag/v0.3.1
# 5) 浏览器 WASM(可选)
marqdo wasm build
# → dist/wasm/ … 见 examples/browser-hello/
# 6) Windows:也可从 GitHub Releases 下载 exe / zip / vsix
# https://github.com/cflmy/marqdo/releases/tag/v0.3.3
```
开发期也可用 `cargo run -- …` 代替已安装的 `marqdo`:
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "marqdo-wasm"
version = "0.3.3"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo interpreter as WebAssembly (browser host bridge)"
repository = "https://github.com/cflmy/marqdo"
publish = false
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
marqdo = { path = "../..", default-features = false, features = ["wasm-core"] }
serde_json = "1"
+21
View File
@@ -0,0 +1,21 @@
# Marqdo browser WASM (route C)
Raw `cdylib` exports — no `wasm-bindgen` CLI required.
| Export | Role |
|--------|------|
| `mq_alloc` / `mq_dealloc` | linear memory |
| `mq_run` | one-shot `# main` (C1) |
| `mq_boot` / `mq_call` | session + handlers (C3) |
| `mq_version` | version C string |
```bash
# from repo root (C5 size profile)
marqdo wasm build -o examples/browser-hello
# or:
cargo build -p marqdo-wasm --target wasm32-unknown-unknown --profile release-wasm
```
Prints size in KiB; runs `wasm-opt -Oz` when Binaryen is on `PATH`.
See [doc/design/browser-marqdo-wasm.md](../../doc/design/browser-marqdo-wasm.md).
File diff suppressed because it is too large. Load diff
+201
View File
@@ -0,0 +1,201 @@
//! Browser export surface for Marqdo (ADR 0002 / C1–C3).
//!
//! Raw `cdylib` ABI (no wasm-bindgen CLI):
//! - `mq_alloc` / `mq_dealloc`
//! - `mq_run` — one-shot `# main` (C1)
//! - `mq_boot` — start session; return value often a `wire` table (C3)
//! - `mq_call` — `(name_ptr, name_len, args_ptr, args_len) ->` JSON result (C3)
//! - `mq_version`
//!
//! Packed results: little-endian `u32` length + UTF-8 JSON
//! `{ ok, stdout, error, value }`.
use std::alloc::{alloc, dealloc, Layout};
use std::cell::RefCell;
use std::ptr;
use std::slice;
use marqdo::{run_source, value_as_json, BrowserSession, RunOptions};
use serde_json::json;
thread_local! {
static SESSION: RefCell<Option<BrowserSession>> = const { RefCell::new(None) };
}
/// Allocate `size` bytes in WASM linear memory (alignment 1).
#[no_mangle]
pub extern "C" fn mq_alloc(size: usize) -> *mut u8 {
if size == 0 {
return ptr::null_mut();
}
let layout = match Layout::from_size_align(size, 1) {
Ok(l) => l,
Err(_) => return ptr::null_mut(),
};
unsafe { alloc(layout) }
}
/// Free a buffer previously returned by [`mq_alloc`], [`mq_run`], [`mq_boot`], or [`mq_call`].
#[no_mangle]
pub extern "C" fn mq_dealloc(ptr: *mut u8, size: usize) {
if ptr.is_null() || size == 0 {
return;
}
let layout = match Layout::from_size_align(size, 1) {
Ok(l) => l,
Err(_) => return,
};
unsafe { dealloc(ptr, layout) }
}
/// One-shot run (C1). Does not keep a session.
#[no_mangle]
pub extern "C" fn mq_run(ptr: *const u8, len: usize) -> *mut u8 {
let source = match read_utf8(ptr, len) {
Ok(s) => s,
Err(e) => return pack_json(&err_json(&e)),
};
pack_json(&run_to_json(&source))
}
/// Boot a session: run `# main`, keep entry env. Replaces any prior session.
#[no_mangle]
pub extern "C" fn mq_boot(ptr: *const u8, len: usize) -> *mut u8 {
let source = match read_utf8(ptr, len) {
Ok(s) => s,
Err(e) => return pack_json(&err_json(&e)),
};
match BrowserSession::boot(&source) {
Ok((sess, value)) => {
let stdout = String::new();
let value_json = match value_as_json(&value) {
Ok(j) => j,
Err(e) => return pack_json(&err_json(&e)),
};
SESSION.with(|s| *s.borrow_mut() = Some(sess));
pack_json(&json!({
"ok": true,
"stdout": stdout,
"error": null,
"value": value_json,
}))
}
Err(e) => {
SESSION.with(|s| *s.borrow_mut() = None);
pack_json(&err_json(&format!("{e:#}")))
}
}
}
/// Call a function in the current session.
/// `args` is UTF-8 JSON object of named arguments (may be `{}`).
#[no_mangle]
pub extern "C" fn mq_call(
name_ptr: *const u8,
name_len: usize,
args_ptr: *const u8,
args_len: usize,
) -> *mut u8 {
let name = match read_utf8(name_ptr, name_len) {
Ok(s) => s,
Err(e) => return pack_json(&err_json(&e)),
};
let args = match read_utf8(args_ptr, args_len) {
Ok(s) => s,
Err(e) => return pack_json(&err_json(&e)),
};
SESSION.with(|cell| {
let mut guard = cell.borrow_mut();
let Some(sess) = guard.as_mut() else {
return pack_json(&err_json("no session — call mq_boot first"));
};
match sess.call(&name, &args) {
Ok(value) => {
let stdout = sess.take_stdout();
let value_json = match value_as_json(&value) {
Ok(j) => j,
Err(e) => return pack_json(&err_json(&e)),
};
pack_json(&json!({
"ok": true,
"stdout": stdout,
"error": null,
"value": value_json,
}))
}
Err(e) => pack_json(&err_json(&format!("{e:#}"))),
}
})
}
/// Package version (NUL-terminated C string in static memory — do not free).
#[no_mangle]
pub extern "C" fn mq_version() -> *const u8 {
concat!(env!("CARGO_PKG_VERSION"), "\0").as_ptr()
}
fn read_utf8(ptr: *const u8, len: usize) -> Result<String, String> {
if ptr.is_null() || len == 0 {
return Ok(String::new());
}
let bytes = unsafe { slice::from_raw_parts(ptr, len) };
String::from_utf8(bytes.to_vec()).map_err(|e| format!("not utf-8: {e}"))
}
fn run_to_json(source: &str) -> serde_json::Value {
let mut opts = RunOptions::default();
opts.allow_fs_write = false;
opts.allow_exec = false;
opts.allow_net = false;
opts.sleep_limit_ms = Some(0);
match run_source(source, &opts) {
Ok(cap) => match value_as_json(&cap.value) {
Ok(value) => json!({
"ok": true,
"stdout": cap.stdout,
"error": null,
"value": value,
}),
Err(e) => err_json(&e),
},
Err(e) => err_json(&format!("{e:#}")),
}
}
fn err_json(msg: &str) -> serde_json::Value {
json!({
"ok": false,
"stdout": "",
"error": msg,
"value": null,
})
}
fn pack_json(v: &serde_json::Value) -> *mut u8 {
let s = v.to_string();
let bytes = s.as_bytes();
let total = 4 + bytes.len();
let out = mq_alloc(total);
if out.is_null() {
return ptr::null_mut();
}
unsafe {
let len = bytes.len() as u32;
ptr::copy_nonoverlapping(len.to_le_bytes().as_ptr(), out, 4);
ptr::copy_nonoverlapping(bytes.as_ptr(), out.add(4), bytes.len());
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn run_hello_json() {
let v = run_to_json("# main\n\n> print text=Hello World!\n");
assert_eq!(v["ok"], true);
assert_eq!(v["stdout"], "Hello World!\n");
}
}
+5 -1
View File
@@ -59,7 +59,11 @@
| [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:前端能力补齐(Completed)** |
| [roadmap/browser-wasm-f.md](roadmap/browser-wasm-f.md) | **路线 F:媒体/文件/Canvas 等(Completed,F1–F5;v0.3.3)** |
| [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 优势 |
+57
View File
@@ -0,0 +1,57 @@
# ADR 0002:浏览器内 Marqdo = WASM 解释器(路线 C)
| | |
|---|---|
| 状态 | **Accepted** |
| 日期 | 2026-09-01 |
| 决策者 | chaungming + 协作 |
| 相关 | [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) · [roadmap/browser-wasm.md](../roadmap/browser-wasm.md) · [interpreter.md](../roadmap/interpreter.md) · [0001](0001-implementation-language.md) |
---
## 背景
`ext/web` 已把站点装配成「源码以 `.mq.md` 为主、服务端 Rust 解释执行」。作者面仍缺**浏览器内**的同一语言:事件、局部状态、客户端 fetch/WS 回调今天要么手写 JS,要么完全不做。
候选路线:
| 代号 | 做法 |
|------|------|
| **A** | 服务端驱动 + 极薄固定增强(类 HTMX) |
| **B** | 把 Marqdo **编译/翻译成 JavaScript** |
| **C** | 把 **Rust 解释器/字节码 VM 编成 WASM**,浏览器跑同一套语义 |
产品叙事目标:**网络项目源码树可以只有 `.mq.md`**(JS/WASM 为生成或发行物,不是第二作者语言)。
---
## 决策
1. **选定路线 C**:浏览器内运行 **与主机同构的 Marqdo 语义**(parse → tree 和/或 bytecode VM),制品为 `marqdo.wasm` + 极薄 JS 宿主桥。
2. **不选定 B 作为主路径**:翻译到 JS 易语义漂移,长期要维护两套后端;B 至多作实验,不替代 C。
3. **A 不对立**:内容站 / SSR / 表单 POST 仍以服务端 `ext/web` 为主;C 负责「必须在客户端执行的 Marqdo」。
4. **同一内核、两套宿主**:`server`(今日 CLI + axum 插件)与 `browser`(DOM / `fetch` / 定时器 / storage);**不是**把 axum、`plugins/web`、SQLite 服务端塞进浏览器。
5. **另开设计与路线图**(见相关链接);实现按 **C0→C5** 切片,金样对齐主机行为。
6. **与「编译 mq.md → WASM 机器码」区分**:本 ADR 是 **解释器/VM 上 WASM**;把 `.mq.md` 直接编译成独立 wasm 模块仍属 `interpreter.md` Phase III 可选项,**另案**,不替代本决策。
---
## 后果
- 核心库必须可 **feature-gate** 掉 `libloading` / `ureq` / `tiny_http` / TTY `libc` 等,以便 `wasm32-unknown-unknown` 链接。
- 新增公共 API:`run_source`(内存源码 + 可选导入图),供 WASM 与测试共用。
- 浏览器侧宿主 API 以表驱动「交互装配」暴露(对称于 `样式装配`);`ext/**` 仍不直接调 `host_*`。
- 发行物可包含 `.wasm` / 生成的 loader;**作者仓库可不提交手写业务 JS**。
- view 断点 / 静态文档站调试可复用同一 WASM 解释器(与 `next-phase.md` 所述一致)。
---
## 否决 / 非目标(本 ADR)
| 方案 / 目标 | 原因 |
|-------------|------|
| 以 B(编译到 JS)为主交付 | 语义双轨;与「一种语言」冲突 |
| 浏览器内完整复刻 `plugins/web` 服务器 | 协议与权限模型不同;服务端仍 axum |
| 浏览器 `dlopen` 原生插件 | WASM 无 POSIX 动态库模型 |
| v1 消灭一切 JS 字节 | 胶水与发行 loader 允许存在;禁止的是**业务手写 JS** |
| 用 Daphne/ASGI 托管 Marqdo | 已否决,见 [web-asgi-servers-and-marqdo.md](../design/web-asgi-servers-and-marqdo.md) |
+48
View File
@@ -0,0 +1,48 @@
# ADR 0003:浏览器异步 I/O(fetch / 定时)— 效应表 + 续体回调
| | |
|---|---|
| 状态 | **Accepted** |
| 日期 | 2026-09-01 |
| 决策者 | chaungming + 协作 |
| 相关 | [0002-browser-marqdo-wasm.md](0002-browser-marqdo-wasm.md) · [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) · [roadmap/browser-wasm.md](../roadmap/browser-wasm.md) |
---
## 背景
Marqdo 调用面今日以**同步**为主。浏览器 `fetch` / `setTimeout` 是异步的;若在 WASM 里阻塞等待,会卡死 UI,且 `wasm32-unknown-unknown` 无真实阻塞 HTTP。
C3 已有:`mq_call` 返回 Map(如 `set_text`)由官方 bridge 执行。C4 在同一通道上扩展异步效应。
---
## 决策
1. **不**在语言内核引入 async/await 关键字或假同步 `fetch`。
2. 处理器返回值可含**效应字段**(与 `set_text` 并列),由 **JS bridge** 执行:
- `fetch`: `{ url, method?, then, headers?, body? }`
- `after`: `{ ms, then }`(定时续体)
3. 异步完成后 bridge 调用 `mq_call(then, payload)`:
- fetch 成功/失败:`{ ok, status, body, error? }`
- after:`{ ok: true }`
4. 能力默认关网络语义仍由**返回效应**显式开启(站点作者主动返回 `fetch`);CORS / 鉴权仍是浏览器与服务端责任。
5. 服务端 `lib/net` / `plugins/web` **不变**;本 ADR 仅浏览器 WASM 宿主。
---
## 后果
- 作者用表格/Map 声明「请求谁、完成后调谁」,无手写业务 JS。
- Bridge 必须串行处理效应(先 `set_text`,再调度 `fetch`/`after`)。
- 深层 Promise 链靠多次 `then` 回调;不在 C4 做通用 async 运行时。
---
## 否决
| 方案 | 原因 |
|------|------|
| WASM 内同步阻塞 `fetch` | 卡死主线程;平台不支持 |
| 编译期把 Marqdo 译成 async JS | 回到路线 B |
| 在核心加 `await` 关键字 | 违反 Markup-as-Syntax / 关键字纪律 |
+397
View File
@@ -0,0 +1,397 @@
# 浏览器 Marqdo(WASM 解释器)设计
| | |
|---|---|
| 状态 | **Accepted(设计锁定)** · 实现见路线图 C0–C5 |
| 日期 | 2026-09-01 |
| ADR | [0002-browser-marqdo-wasm.md](../adr/0002-browser-marqdo-wasm.md) |
| 路线图 | [roadmap/browser-wasm.md](../roadmap/browser-wasm.md) |
| 相关 | [ext-web.md](ext-web.md) · [bytecode.md](bytecode.md) · [web-assets-and-images.md](web-assets-and-images.md) · [table-cell-expressions.md](table-cell-expressions.md) |
---
## 0. 一句话
**源码只有 `.mq.md`;浏览器跑与 CLI 同构的 Marqdo VM(WASM);JS 只做宿主桥与加载器,不做业务语言。**
---
## 1. 目标与非目标
### 1.1 目标
| # | 目标 |
|---|------|
| G1 | 浏览器内执行合法 `.mq.md`(至少 `# main` + 打印/绑定/分支/循环/表/调用) |
| G2 | 与主机 **tree**(及后续 **bytecode**)金样在共享子集上 stdout/返回值一致 |
| G3 | 作者用 GFM 表声明交互(选择器 / 事件 / 调用),对称于 `样式装配` |
| G4 | 仓库源码树可不含业务 `.js`;允许提交或由工具生成 `marqdo.wasm` + 官方 loader |
| G5 | `import lib/…` 在浏览器可用(嵌入式 `lib/` 或打包进 wasm) |
### 1.2 非目标(本波 / C0–C3)
| # | 非目标 |
|---|--------|
| N1 | 在浏览器复刻 axum、`web_listen`、SQLite 服务端、admin UI |
| N2 | `plugin.load` 加载原生 `.so` / 浏览器内 dlopen |
| N3 | 把整站 `plugins/web` ABI 原样搬进 WASM |
| N4 | 把 `.mq.md` 编译成独立机器码 WASM(异于「解释器上 WASM」) |
| N5 | 强制内容站必须加载 WASM(纯 SSR 站可继续零客户端逻辑) |
---
## 2. 架构
```
┌─────────────────────────────────────────────────────────┐
│ Page (HTML shell from ext/web SSR or static) │
│ ┌──────────────┐ ┌─────────────────────────────────┐ │
│ │ DOM / CSS │ │ Official JS loader (thin) │ │
│ └──────▲───────┘ │ - WebAssembly.instantiate │ │
│ │ bridge │ - marqdo_run_source / on_event │ │
│ │ └──────────────┬──────────────────┘ │
│ │ │ │
│ │ ┌──────────▼──────────┐ │
│ │ │ marqdo.wasm │ │
│ │ │ parse → load → │ │
│ └──────────────│ Interpreter | Vm │ │
│ host_dom_* │ HostContext(browser)│ │
│ host_fetch_* │ embedded lib/ │ │
│ └─────────────────────┘ │
└─────────────────────────────────────────────────────────┘
Server (unchanged):
marqdo run / plugins/web (axum) — SSR, DB, auth, full site
```
**原则:** 一套语言语义;**HostContext 分型**(`native` vs `browser`),不是两套语法。
---
## 3. 与现有流水线对齐
主机今日(见 `src/lib.rs`):
```
path → fs::read → load_module → Interpreter|Vm → HostContext(native)
```
浏览器目标:
```
source: &str (+ optional import map)
→ load_module_from_memory
→ Interpreter|Vm (capture stdout)
→ HostContext(browser caps)
→ { ok, stdout, value_json, error }
```
公共库 API(C0/C1 必须落地):
| API | 职责 |
|-----|------|
| `run_source(source, opts) -> Result<RunCapture>` | 无路径入口;cwd/fs_root 虚拟 |
| `RunOptions` 浏览器默认 | `allow_fs_write=false`, `allow_exec=false`, `allow_net=false`(net 经显式 bridge 再开) |
| `load` 导入 | `lib/**` → `embedded_lib`;用户模块 → JS 注入的 `HashMap<path, source>` |
后端优先级:
1. **C1:tree**(与默认 CLI 一致,调试简单)
2. **C2+:bytecode** 可选(体积/性能;金样双后端)
---
## 4. Cargo / 制品布局
### 4.1 Feature 门(核心 crate `marqdo`)
| Feature | 默认(native) | `wasm-core` | 作用 |
|---------|----------------|-------------|------|
| `cli` | on | off | `main` / clap 仅 bin |
| `view` | on | off | `tiny_http` 文档浏览器 |
| `net-host` | on | off | `ureq` HTTP 客户端 |
| `plugin-host` | on | off | `libloading` 原生插件 |
| `exec-host` | on | off | `std::process` / foreign |
| `fs-host` | on | off | 真实磁盘读写(可读可后续经 VFS 桥) |
| `wasm-core` | off | on | 浏览器子集编译开关 |
`wasm32-unknown-unknown` 构建:**不得**链接 `libloading`、`ureq`、`tiny_http`、TTY `libc`。
### 4.2 包
| 路径 | 角色 |
|------|------|
| `marqdo`(根) | 核心;feature-gate |
| `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` 对齐 |
发行:`marqdo wasm build`(C2 CLI 糖)或 `wasm-pack build crates/marqdo-wasm`。
---
## 5. 宿主能力矩阵
| 能力 | Native | Browser C1 | Browser C3+ |
|------|--------|------------|-------------|
| `print` / 捕获 stdout | ✓ | ✓ → 可镜像 `console` | ✓ |
| `input` | stdin / preset | **仅 preset / JS 喂入** | 可选 prompt 桥 |
| builtins / 表 / 算术 | ✓ | ✓ | ✓ |
| `lib/math` `lib/json` `lib/collection` | ✓ | ✓(embedded) | ✓ |
| `lib/fs` 真磁盘 | ✓ | ✗ 明确报错 | 可选 OPFS/VFS 桥 |
| `lib/net` ureq | ✓ | ✗ | `fetch` 桥(异步模型见 §7) |
| `plugin.load` | ✓ | ✗ | ✗(改 L1 浏览器专用) |
| `exec` / foreign | ✓ | ✗ | ✗ |
| DOM / 事件 | ✗ | stub | **交互装配** |
| `sleep` | thread | 0 或 JS timer(异步) | timer |
错误策略:**显式失败**(诊断字符串含 `unavailable in browser wasm`),禁止静默空成功。
---
## 6. 交互装配(C3,对称样式装配)
### 6.1 作者面(示例)
```markdown
---
import json:lib/json.mq.md
---
# main
*`count` = 0*
`wire` =
| @ | 选择器 | 事件 | 调用 |
|---|--------|------|------|
| 1 | "#bump" | click | bump |
**`wire`**
## 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**
```
`# main` 的返回值是 **wire 表**(`@` 行向记录列表)。Loader 调用 `mq_boot`,再 `wireEvents`。
### 6.2 桥约定
| 步骤 | API |
|------|-----|
| 启动 | `mq_boot(source)` → `{ ok, value }`;`value` = wire 列表或 `{ wire: [...] }` |
| 事件 | Loader `addEventListener` → `mq_call(fn, {"event":"click"})` |
| 回写 | 返回 Map 可含 `set_text`: `{ "#sel": "text" }`(仅 `textContent`) |
行键名认:`选择器`/`selector`、`事件`/`event`、`调用`/`call`。
含 `/` 的 CSS 等单元格仍 **引号优先**(见 [table-cell-expressions.md](table-cell-expressions.md))。
L1 `浏览器.交互装配`(ext)可后置;C3 以 bridge + 返回 wire 表即可验收。
---
## 7. 异步模型(C4)
锁定:[ADR 0003](../adr/0003-browser-async-effects.md)。
处理器返回 Map 可含(与 `set_text` 并列):
| 字段 | 含义 | 完成后 `mq_call` 实参 |
|------|------|----------------------|
| `fetch` | `{ url, method?, then, headers?, body? }` | `{ ok, status, body, error? }` |
| `after` | `{ ms, then }` | `{ ok: true }` |
Bridge:`applyEffects(exports, value)` — 先 DOM,再调度异步;**不**在 WASM 内阻塞。
示例见 `examples/browser-hello/fetch.mq.md`。
---
## 8. 安全
| 项 | 规则 |
|----|------|
| 默认能力 | 无磁盘写、无 exec、无任意 net |
| 源码来源 | 同源或构建时嵌入;不默认 `eval` 远程不可信脚本除非站点显式开启 |
| DOM | 仅经装配表/白名单 API;不暴露任意 `innerHTML` 字符串执行第三方脚本 |
| CSRF / Cookie | 浏览器 Marqdo **不替代**服务端鉴权;cookie 仍走 HTTP |
---
## 9. 与 `ext/web` 分工
| 层 | 负责 |
|----|------|
| 服务端 `plugins/web` | 路由、DB、会话、SSR HTML、样式/头/图装配 |
| 页面壳 | `头装配` 挂 `module` → `marqdo-bridge.js`;`static` 提供 `.wasm` |
| 浏览器 L1 | `客户端挂载` / `client_embed`;效应约定见 ADR 0003 |
| 核心 / crate | `run_source`、`BrowserSession`、`marqdo-wasm` ABI |
挂载示例:
```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/`)。
---
## 10. 测试与验收
| 级 | 内容 |
|----|------|
| 单元 | `run_source("…# main\n> print…")` native 与 wasm 同测 |
| 金样子集 | `tests/structure/hello.mq.md` 等无 fs/net/plugin 的样例 |
| 浏览器冒烟 | `examples/browser-hello`:按钮点击 → Marqdo 函数 → 改 DOM 文本 |
| 回归 | CI:`cargo test` native;另 job `wasm-pack build` / `cargo check --target wasm32-unknown-unknown --no-default-features --features wasm-core` |
---
## 11. 文档与技能同步
- ADR 0002、本文、路线图 C0–C5。
- `.cursor/skills/marqdo/SKILL.md`:补充「浏览器 WASM / 交互装配 / 引号 CSS」。
- `CHANGELOG`:Unreleased 记录设计锁定与各 C 完成项。
---
## 12. 风险
| 风险 | 缓解 |
|------|------|
| wasm 体积过大 | `release-wasm` profile(`opt-level=z` + LTO + strip);`marqdo wasm build` 打印 KiB,有则跑 `wasm-opt -Oz` |
| 异步拖垮语言 | ADR 0003 效应表;不阻塞 WASM |
| Feature-gate 伤 native | 默认 features = 今日行为;CI 全绿再合 |
| 作者误以浏览器替代服务器安全 | 文档强调鉴权在服务端 |
| 会话要 bytecode | **未做**:`BrowserSession` 固定 tree(缺 entry-env invoke);`run_source` 已支持 bytecode |
---
## 14. C5 硬化(已落地)
| 项 | 状态 |
|----|------|
| `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 断点复用 | **非本版目标** |
---
## 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 | 作者手写业务 JS / TS(官方桥内机制允许) |
| D-N3 | ~~开放无前缀的 set_html~~(E 已允许任意选择器;内容由 MQ 产出) |
---
## 17. 路线 E — 前端能力补齐(Active)
路线图:[browser-wasm-e.md](../roadmap/browser-wasm-e.md)。
**原则:** 唯一硬禁是**作者手写业务 JS**。官方 bridge 可实现列表装配、路由、storage、WebSocket、内部模板/轻量 VDOM 等;作者只写 `.mq.md` + 效应表。
| 波 | 要点 |
|----|------|
| E1 | `set_style` / `focus` / `blur` / `scroll_into`;wire `委托`;键盘事件 |
| E2 | `set_html` / `replace_children` / `render_list` |
| E3 | `navigate` + `popstate`(选择器 `window`) |
| E4 | `storage` `{ op, key, value?, scope?, then? }` |
| E5 | `ws` `{ op: open\|send\|close, … }` |
| E6 | `fetch_all` / `interval` / `clear_interval` / fetch `fields` |
### 17.1 效应速查(E)
| 字段 | 含义 |
|------|------|
| `set_style` | `{ "#sel": { color: "red" } }` 或 `{ "#sel": "color:red" }` |
| `focus` / `blur` | `"#sel"` 或选择器数组 |
| `scroll_into` | `"#sel"` |
| `set_html` / `append_html` / `replace_children` | 写/追加 HTML(MQ 产出;XSS 自负) |
| `render_list` | `{ "#sel": { tag, items } }` |
| `remove` | 选择器或数组,删除节点 |
| `add_class` / `remove_class` | classList |
| `navigate` | `{ url, replace?: bool }` |
| `storage` | `{ op, key, value?, scope?: local\|session\|cookie, days?, then? }` |
| `ws` | `{ op: open\|send\|close, … }` |
| `fetch_all` | `{ requests: []\|map, then }` |
| `interval` / `clear_interval` | 定时 |
| `clipboard` / `download` | 剪贴板 / 触发下载 |
| `fetch.fields` | → FormData |
Wire 列:`委托` / `delegate` = 在容器上监听,目标须 `closest(delegate)`;选择器 `window` 绑 `window`。
## 15. 决策摘要
| 问题 | 答案 |
|------|------|
| 路线? | **C**:解释器/VM → WASM |
| 作者语言? | 仅 `.mq.md` |
| JS 角色? | Loader + 宿主桥 |
| 服务端? | 保留;不塞进浏览器 |
| 第一步实现? | C0 门控可编译 + C1 `run_source` 打印闭环 |
+11 -4
View File
@@ -52,14 +52,21 @@ Future optional ext domains get their own subdirs (e.g. `ext/web/`, `ext/quantum
| `web` | `web/web.mq.md`, `web/网页.mq.md`, **`native/libweb.so`** — 见 [ext-web.md](ext-web.md) · [roadmap](../roadmap/ext-web.md) |
| `quantum` | `quantum/quantum.mq.md`, `quantum/量子.mq.md`, **`native/libquantum.so`** — 见 [ext-quantum.md](ext-quantum.md) · [roadmap](../roadmap/ext-quantum.md) |
`add agent` copies the built native plugin into `MARQDO_EXT/native/`. Build it first:
`add agent` / `add web` / `add quantum` **先定位原生插件**,再复制 `.mq.md`:
1. 在 `CARGO_TARGET_DIR`、`target/{debug,release}`、源码 `ext` 旁的 `target/`、可执行文件旁等路径查找 `lib{name}.so`(或 `.dll` / `.dylib`)
2. 找不到则自动执行 `cargo build -p marqdo_plugin_{name}`,再安装到 `MARQDO_EXT/native/`
3. 写入 `{name}.plugin` 绝对路径提示,供 `plugin.native_path` 解析
这样不会出现「只装了 `.mq.md`、运行时报 native plugin not found」的半安装状态。
```bash
cargo build -p marqdo_plugin_agent
marqdo ext add agent
# 推荐:在仓库根目录
marqdo ext add web
# 等价于找到或编好 libweb.so 后拷入 ~/.marqdo/ext/native/
```
Without install, runtime resolves the plugin via `plugin.native_path name=agent` (see [ext-abi.md](ext-abi.md)): `MARQDO_AGENT_PLUGIN` → `CARGO_TARGET_DIR/{debug,release}/` → cwd `target/…` → beside `marqdo` binary → `MARQDO_EXT/native/`.
Without a prior install, runtime still resolves via `plugin.native_path name=web` (see [ext-abi.md](ext-abi.md)): `MARQDO_WEB_PLUGIN` → `CARGO_TARGET_DIR/{debug,release}/` → cwd `target/…` → beside `marqdo` binary → `MARQDO_EXT/native/`.
## Tests
+1 -1
View File
@@ -268,7 +268,7 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置
| **首列表头 `@` / `行` / `row`** | **行向** `List` of `Map`(标记列不进入字段;任意数据行数) |
| 重复表头 | 诊断错误 |
**数据单元格是表达式**(与调用实参值语法相同:裸词、数字、`` `var` ``、算术、引号串;URL / `gpt-4o-mini` 等按路径·连字符折叠为文本)。表头仍是键名文本。细则:[table-cell-expressions.md](table-cell-expressions.md)。
**数据单元格是表达式**(与调用实参值语法相同:裸词、数字、`` `var` ``、算术、引号串;URL / `gpt-4o-mini` 等按路径·连字符折叠为文本;含 `/` 的 CSS 比率等请用引号 `"1/5"`,裸 `1/5` 为除法)。表头仍是键名文本。细则:[table-cell-expressions.md](table-cell-expressions.md)。
```markdown
*`k` = secret *
+3 -2
View File
@@ -2,7 +2,7 @@
| | |
|---|---|
| 状态 | **已落地**:text/table/fs/sys/time/json/net/math/foreign/**plugin** |
| 状态 | **已落地**:text/table/fs/sys/time/json/net/math/foreign/**plugin**/browser |
| 日期 | 2026-08-07 |
| 原则 | 全部经 frontmatter **导入**;除 JSON 外中英分文件;内核保持少而精 |
| 相关 | [stdlib.md](stdlib.md) · [stdlib-i18n.md](stdlib-i18n.md) · [ext-abi.md](ext-abi.md) · [ext-llm.md](ext-llm.md) · [ext-agent.md](ext-agent.md) · [**module-namespace.md**](module-namespace.md)(导入命名空间;**M1/M2 已落地**:`库.成员` / `库.对象.成员` / `use`) |
@@ -17,10 +17,11 @@
|--------|--------|--------|------|
| 文本 | `lib/text.mq.md` | `lib/文本.mq.md` | 已有 |
| 表 | `lib/table.mq.md` | `lib/表.mq.md` | 已有(`put`/`改` + list/map;见 [stdlib-table.md](stdlib-table.md)) |
| 浏览器效应 | `lib/browser.mq.md` | `lib/浏览器.mq.md` | WASM 客户端效应助手(GFM + helpers;勿用 `json.set` 链) |
| 文件 | `lib/fs.mq.md` | `lib/文件.mq.md` | 已有 |
| 系统 | `lib/sys.mq.md` | `lib/系统.mq.md` | 已有(含 `load_dotenv`) |
| 时间 | `lib/time.mq.md` | `lib/时间.mq.md` | 已有 |
| JSON | `lib/json.mq.md` | **同文件** | 已有(含 `quote`) |
| JSON | `lib/json.mq.md` | **同文件** | **仅** parse / stringify / quote;集合请用 table / GFM |
| 网络 | `lib/net.mq.md` | `lib/网络.mq.md` | 已有(HTTPS + headers) |
| 数学 | `lib/math.mq.md` | `lib/数学.mq.md` | 已有 |
| 外联 | `lib/foreign.mq.md` | `lib/外联.mq.md` | 已有 |
+6 -3
View File
@@ -44,10 +44,11 @@ v1 把 GFM 数据单元格一律收成 **字面量**(`Int` / `Text`)。结
| `` `api_key` `` | 变量引用 |
| `` `a` + `b` `` | 普通表达式 |
| `True` / `假` / `None` | 布尔 / 空 |
| `"https://…"` / `".marqdo/x"` | 引号字符串(可含 `/`、插值) |
| `"https://…"` / `".marqdo/x"` / `"1/5"` / `"16/9"` | 引号字符串(可含 `/`、插值;**CSS 比率等含 `/` 的值请用引号**,勿依赖空格消歧) |
| `https://api.openai.com/v1` | **路径折叠**:无空格的 `Text/Text/…` 除法链收成整段文本(同调用实参) |
| `gpt-4o-mini` | **连字符散文**:不拆成减法(同调用实参) |
| `` /about ``、`` /chat/completions `` | 以 `/` 开头的路径散文 → 整段文本 |
| `1/5` | **整数除法**(同表达式 / 调用实参;今日整除得 `0`)——要文本请写 `"1/5"` |
| 空单元格 | 空文本 `""` |
### 2.2 表头仍是键名文本
@@ -111,9 +112,10 @@ v1 把 GFM 数据单元格一律收成 **字面量**(`Int` / `Text`)。结
|--------|------|
| 纯中文/英文词、整数 | **不变** |
| `gpt-4o-mini`、URL、`/path` | **不变**(折叠规则与调用实参一致) |
| 真正要做除法 / 减法 | 用空格或括号:`` `n` / 2 ``、`` `a` - 1 ``;或先在表外算再 `` `x` `` 填入 |
| 真正要做除法 / 减法 | 裸写 `1/5` 或空格/括号:`` `n` / 2 ``、`` `a` - 1 ``;或先在表外算再 `` `x` `` 填入 |
| CSS / 含 `/` 的散文值 | **引号优先**:`"1/5"`、`"16/9"`、`"image/png"`(不靠空格把算术「关掉」) |
破坏性:几乎无。唯一需注意的是「想在单元格里写算术且两侧是裸词」——与调用实参同一套消歧。
破坏性:几乎无。唯一需注意的是「想在单元格里写算术且两侧是裸词」——与调用实参同一套消歧;含 `/` 的**文本**一律用引号。
---
@@ -132,6 +134,7 @@ v1 把 GFM 数据单元格一律收成 **字面量**(`Int` / `Text`)。结
|----|------|
| 金样 | 横表单元格 `` `var` `` 读环境;竖表旧金样全绿 |
| 路径 | `https://…`、`/chat/completions`、`gpt-4o-mini` 仍为文本 |
| 含 `/` 文本 | 表单元格用引号:`"1/5"`、`"16/9"`;裸 `1/5` 为除法 |
| 扩展 | `ext/ai/llm` 构造可用表写入运行时字段,去掉无必要的 `json.set` 链 |
| 文档 | 本页 + roadmap T5 + markdown-mapping §9 同步 |
+1 -1
View File
@@ -34,7 +34,7 @@
| 中 | 静态类型 / 可维护 AST | 长期改解释器不疼 |
| 中 | CLI 与打包 | 单二进制或 `npx`/等价体验 |
| 低 | 极致性能 | v0 样例很小 |
| 低 | 浏览器内运行 | 可后置 |
| 低 | 浏览器内运行 | **已后置落地规划**:见 [ADR 0002](../adr/0002-browser-marqdo-wasm.md)(WASM 解释器) |
非准则:跟风、先写再选、与「生成 OKF」强绑某一云厂商。
+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` 效应可演示
+32
View File
@@ -0,0 +1,32 @@
# 路线图:浏览器 Marqdo 路线 E(前端能力补齐)
| | |
|---|---|
| 状态 | **Completed** |
| 日期 | 2026-09-04 |
| 前置 | [browser-wasm-d.md](browser-wasm-d.md)(D0–D4 **Completed**) |
| 续作 | [browser-wasm-f.md](browser-wasm-f.md)(媒体 / 文件 / Canvas 等) |
| 设计 | [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) §16–§17 |
## 原则(已修正)
**禁止的只有:作者手写业务 JS。**
官方 `marqdo-bridge.js` / 构建生成物可以包含任意宿主机制(含轻量列表装配、路由、存储、WebSocket、内部模板等)。
## 阶段
| 阶段 | 内容 | 状态 |
|------|------|------|
| **E0** | 原则修正 + 能力矩阵 | **done** |
| **E1** | `set_style` / `focus` / `blur` / `scroll_into`;键盘;wire `委托`;多节点 `querySelectorAll` | **done** |
| **E2** | `set_html` / `append_html` / `replace_children` / `render_list` / `remove`;L1 `list_html` | **done** |
| **E3** | `navigate` / `replace`;`window`+`popstate` | **done** |
| **E4** | `storage` local/session/**cookie** | **done** |
| **E5** | `ws` open/send/close + callbacks | **done** |
| **E6** | `fetch_all`(数组或 map)/ `interval` / FormData / `clipboard` / `download` | **done** |
| **E7** | `add_class` / `remove_class`;示例列表真删除 + net 面板 | **done** |
## 验收
- [examples/browser-app/](../../examples/browser-app/):列表 CRUD、storage、三页路由、interval、fetch_all、ws、clipboard、download
- 冒烟:`tests/wasm/smoke.mjs`
+26
View File
@@ -0,0 +1,26 @@
# 路线图:浏览器 Marqdo 路线 F(进阶宿主能力)
| | |
|---|---|
| 状态 | **Completed**(F1–F5;F6 Service Worker 可选未做) |
| 日期 | 2026-09-04 |
| 发布 | **v0.3.3** |
| 前置 | [browser-wasm-e.md](browser-wasm-e.md)(E **Completed**) |
| 写法 | 客户端 `.mq.md`:**GFM 表格 + `lib/browser`**,禁止 `json.set` 链([marqdo-dev](../../.cursor/skills/marqdo-dev/SKILL.md)) |
## 原则
同 E:禁止作者手写业务 JS;官方 bridge 可扩展。作者数据与效应用**可读表格/助手**表达。
## 阶段
| 阶段 | 内容 | 状态 |
|------|------|------|
| **F1** | `read_file` → text / DataURL → `mq_call` | **done** |
| **F2** | Canvas 2D 指令表(`canvas.commands`) | **done** |
| **F3** | Audio play / pause / stop;`src=beep` Web Audio | **done** |
| **F4** | `observe` / `unobserve`(Intersection / Resize) | **done** |
| **F5** | drag/drop wire + `data-drag` / `drop_text` | **done** |
| **F6** | Service Worker / 离线缓存 | optional / skipped |
示例:[examples/browser-media/](../../examples/browser-media/) · 助手:`lib/browser.mq.md`。
+40
View File
@@ -0,0 +1,40 @@
# 路线图:浏览器 Marqdo(WASM)
| | |
|---|---|
| 状态 | **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) |
| 阶段 | 内容 | 状态 |
|------|------|------|
| **C0** | feature 门控;`wasm32` check | **done** |
| **C1** | `run_source` + `mq_run` | **done** |
| **C2** | loader + `marqdo wasm build`(含 bridge 拷贝) | **done** |
| **C3** | session wire + `set_text` | **done** |
| **C4** | `fetch` / `after` 效应 | **done** |
| **C5** | `release-wasm` 体积;冒烟;站点挂载文档 / L1 | **done** |
## 交付物
| 产物 | 路径 |
|------|------|
| 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` / `网页.客户端挂载` |
## 明确非目标(本版不做)
- 浏览器会话 bytecode(缺 entry-env invoke;一发 `run_source` 已支持 bytecode)
- 把 axum / SQLite 服务端搬进 WASM
- 业务手写 JS 框架
## 进度
| 日期 | 记录 |
|------|------|
| 2026-09-01 | C0–C5 完结并 push;收口 bridge 规范路径 + 冒烟 + 挂载 L1 |
+2 -1
View File
@@ -109,7 +109,8 @@ Phase I 对齐 Crafting Interpreters 的 **jlox(树遍历)**;Phase II 对
- 更完整表达式文法、错误模型、外联围栏 FFI
- 生成 OKF 依赖目录
- (可选)另一后端:编译到 Python/WASM——**另开 ADR**,不替代自研语义
- (可选)另一后端:编译到 Python/WASM——**另开 ADR**,不替代自研语义
- **浏览器内运行(路线 C)**:解释器/VM 上 WASM(**非**把 `.mq.md` 译成 JS)——已锁定 [ADR 0002](../adr/0002-browser-marqdo-wasm.md) · [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) · [roadmap/browser-wasm.md](browser-wasm.md)
---
+1 -1
View File
@@ -174,7 +174,7 @@ flowchart LR
### 风险与边界
- 静态 `gh-pages` **无法**真断点(无常驻 VM);调试仅 **live view**(或未来 WASM 解释器)。
- 静态 `gh-pages` **无法**真断点(无常驻 VM);调试仅 **live view**(或 [浏览器 WASM 解释器](browser-wasm.md) C5)。
- 字节码调试可晚于树遍历一个迭代。
---
+21
View File
@@ -0,0 +1,21 @@
# browser-app(路线 E)
作者**零业务 JS**;逻辑用 **GFM 表格 + `lib/browser`**(无 `json.set` 链)。
| 能力 | 演示 |
|------|------|
| 列表 CRUD | 添加 / 委托删除(`bag` + `set_html`) |
| storage | 草稿 localStorage |
| navigate | `/` `/about` `/net` + `popstate` |
| interval | 计时起停 |
| fetch_all | 并行两个 uuid |
| ws | `wss://echo.websocket.events`(依赖外网) |
| clipboard / download | 复制/下载列表文本 |
```bash
cargo build -p marqdo --release
./target/release/marqdo wasm build -o examples/browser-app
cd examples/browser-app && python3 -m http.server 8766
```
写法:[marqdo-dev](../../.cursor/skills/marqdo-dev/SKILL.md) · 路线图:[browser-wasm-e.md](../../doc/roadmap/browser-wasm-e.md)。
+283
View File
@@ -0,0 +1,283 @@
---
title: browser-app (route E+)
description: list CRUD, storage, navigate, interval, fetch_all, ws — GFM + lib/browser
import browser:lib/browser.mq.md
import table:lib/table.mq.md
import text:lib/text.mq.md
---
# main
*`ticks` = 0*
*`bag` = ""*
*`path` = "/"*
*`ws_id` = "echo"*
`wire` =
| @ | 选择器 | 事件 | 调用 | 委托 | 值选择器 |
|---|--------|------|------|------|----------|
| 1 | "#add" | click | add | | "#draft" |
| 2 | "#save" | click | save_draft | | "#draft" |
| 3 | "#load" | click | load_draft | | |
| 4 | "#start-tick" | click | start_tick | | |
| 5 | "#stop-tick" | click | stop_tick | | |
| 6 | "#nav-home" | click | go_home | | |
| 7 | "#nav-about" | click | go_about | | |
| 8 | "#nav-net" | click | go_net | | |
| 9 | "window" | popstate | on_pop | | |
| 10 | "#items" | click | on_item | "button[data-id]" | |
| 11 | "#fetch-all" | click | do_fetch_all | | |
| 12 | "#ws-open" | click | ws_open | | |
| 13 | "#ws-send" | click | ws_send | | "#ws-msg" |
| 14 | "#ws-close" | click | ws_close | | |
| 15 | "#copy-log" | click | copy_log | | |
| 16 | "#dl-list" | click | dl_list | | |
`nav` =
| url | replace |
|-----|---------|
| / | False |
`st` =
| op | key | then |
|----|-----|------|
| get | mq-draft | on_draft |
`boot` =
| wire | navigate | storage |
|------|----------|---------|
| `wire` | `nav` | `st` |
**boot**
## add
+ `value`=""
1. `value` != ""
1. `bag` == ""
*`bag` = value*
2. *
*`bag` = bag + "\n" + value*
*`parts` = > text.str_split s=bag sep="\n"*
*`html` = ""*
- [item](parts)
1. `item` != ""
*`html` = html + "<li><span>" + item + "</span> <button type=\"button\" data-id=\"" + item + "\">删</button></li>"*
*`ret` = > browser.set_html sel="#items" html=html*
*`clr` = > browser.set_value sel="#draft" value=""*
*`ret` = > browser.merge a=ret b=clr*
*`f` = > browser.focus sel="#draft"*
**> browser.merge a=ret b=f**
2. *
****
## on_item
+ `data_id`=""
1. `data_id` != ""
*`parts` = > text.str_split s=bag sep="\n"*
*`next` = ""*
- [item](parts)
1. `item` != ""
1. `item` != `data_id`
1. `next` == ""
*`next` = item*
2. *
*`next` = next + "\n" + item*
*`bag` = next*
*`parts2` = > text.str_split s=bag sep="\n"*
*`html` = ""*
- [item](parts2)
1. `item` != ""
*`html` = html + "<li><span>" + item + "</span> <button type=\"button\" data-id=\"" + item + "\">删</button></li>"*
*`ret` = > browser.set_html sel="#items" html=html*
*`msg` = "removed " + data_id*
*`t` = > browser.set_text sel="#log" text=msg*
**> browser.merge a=ret b=t**
2. *
****
## save_draft
+ `value`=""
`st` =
| op | key | value |
|----|-----|-------|
| set | mq-draft | `value` |
*`msg` = > browser.set_text sel="#log" text="draft saved"*
*`s` = > browser.storage spec=st*
**> browser.merge a=msg b=s**
## load_draft
`st` =
| op | key | then |
|----|-----|------|
| get | mq-draft | on_draft |
**> browser.storage spec=st**
## on_draft
+ `ok`=True
+ `value`=""
+ `found`=False
1. `found`
*`ret` = > browser.set_value sel="#draft" value=value*
*`msg` = > browser.set_text sel="#log" text="draft loaded"*
**> browser.merge a=ret b=msg**
2. *
**> browser.set_text sel="#log" text="no draft"**
## start_tick
**> browser.interval ms=1000 then="on_tick" id="tick"**
## stop_tick
**> browser.clear_interval id="tick"**
## on_tick
+ `ok`=True
+ `id`=""
*`ticks` = ticks + 1*
*`label` = > str ticks*
**> browser.set_text sel="#tick" text=label**
## go_home
*`path` = "/"*
**> show_path**
## go_about
*`path` = "/about"*
**> show_path**
## go_net
*`path` = "/net"*
**> show_path**
## on_pop
+ `path`=""
*`path` = path*
**> show_path**
## show_path
*`hide` = > table.put in=None at="hidden" value=""*
*`show` = > table.put in=None at="hidden" value=False*
1. `path` == "/about"
`attrs` =
| #panel-about | #panel-home | #panel-net |
|--------------|-------------|------------|
| `show` | `hide` | `hide` |
2. *
1. `path` == "/net"
`attrs` =
| #panel-net | #panel-home | #panel-about |
|------------|-------------|--------------|
| `show` | `hide` | `hide` |
2. *
`attrs` =
| #panel-home | #panel-about | #panel-net |
|-------------|--------------|------------|
| `show` | `hide` | `hide` |
*`label` = "path: " + path*
*`ret` = > browser.set_text sel="#path" text=label*
*`a` = > browser.wrap key="set_attr" value=attrs*
*`ret` = > browser.merge a=ret b=a*
*`nav` = > browser.navigate url=path*
**> browser.merge a=ret b=nav**
## do_fetch_all
`reqs` =
| @ | url |
|---|-----|
| 1 | "https://httpbin.org/uuid" |
| 2 | "https://httpbin.org/uuid" |
*`msg` = > browser.set_text sel="#net-out" text="fetch_all…"*
*`fa` = > browser.fetch_all requests=reqs then="on_fetch_all"*
**> browser.merge a=msg b=fa**
## on_fetch_all
+ `ok`=True
+ `results`=None
**> browser.set_text sel="#net-out" text="fetch_all done (see console / results in session)"**
## ws_open
`w` =
| op | id | url | then_open | then_message | then_error | then_close |
|----|----|-----|-----------|--------------|------------|------------|
| open | `ws_id` | "wss://echo.websocket.events" | on_ws_open | on_ws_msg | on_ws_err | on_ws_close |
**> browser.ws spec=w**
## on_ws_open
+ `ok`=True
+ `id`=""
**> browser.set_text sel="#net-out" text="ws open"**
## on_ws_msg
+ `ok`=True
+ `data`=""
*`msg` = "ws ← " + data*
**> browser.set_text sel="#net-out" text=msg**
## on_ws_err
+ `ok`=False
+ `error`=""
*`msg` = "ws error: " + error*
**> browser.set_text sel="#net-out" text=msg**
## on_ws_close
+ `ok`=True
**> browser.set_text sel="#net-out" text="ws closed"**
## ws_send
+ `value`=""
`w` =
| op | id | data |
|----|----|------|
| send | `ws_id` | `value` |
**> browser.ws spec=w**
## ws_close
`w` =
| op | id |
|----|----|
| close | `ws_id` |
**> browser.ws spec=w**
## copy_log
*`msg` = > browser.set_text sel="#log" text="copied bag to clipboard"*
*`c` = > browser.clipboard text=bag*
**> browser.merge a=msg b=c**
## dl_list
*`msg` = > browser.set_text sel="#log" text="download started"*
*`d` = > browser.download body=bag filename="items.txt"*
**> browser.merge a=msg b=d**
+96
View File
@@ -0,0 +1,96 @@
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Marqdo · browser-app (route E)</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: linear-gradient(165deg, #f3f7f2, var(--paper));
padding: 2rem clamp(1rem, 4vw, 3rem);
}
h1 { font-family: "IBM Plex Serif", "Noto Serif SC", serif; margin: 0 0 0.35rem; }
.lead { color: var(--muted); max-width: 42rem; }
nav a { margin-right: 0.75rem; color: var(--accent); }
section { margin: 1.5rem 0; padding: 1rem 0; border-top: 1px solid #c5d4c9; }
#path { font-family: ui-monospace, monospace; color: var(--muted); }
#items { list-style: none; padding: 0; margin: 0.75rem 0; }
#items li {
display: flex; align-items: center; gap: 0.5rem;
padding: 0.4rem 0.6rem; margin-bottom: 0.35rem;
background: rgba(255,255,255,0.65); border: 1px solid #b7c7bb;
}
#items button { margin-left: auto; }
input[type="text"] { padding: 0.45rem 0.65rem; border: 1px solid #b7c7bb; width: min(16rem, 70%); }
button {
padding: 0.45rem 0.9rem; border: 0; background: var(--accent); color: #f5faf6;
font: inherit; cursor: pointer; margin: 0.2rem 0.35rem 0.2rem 0;
}
button.secondary { background: #3a4740; }
#tick, #net-out { font-variant-numeric: tabular-nums; }
#net-out {
min-height: 2.5rem; padding: 0.6rem 0.75rem; background: rgba(255,255,255,0.55);
border: 1px solid #b7c7bb; white-space: pre-wrap; word-break: break-all;
}
pre {
margin-top: 1rem; padding: 0.85rem 1rem; background: #122018; color: #d7eadc;
font-size: 0.8rem; overflow: auto; max-width: 42rem;
}
.err { color: #ffb4a8; }
</style>
</head>
<body>
<h1>Marqdo browser-app</h1>
<p class="lead">路线 E:列表 CRUD / storage / navigate / interval / fetch_all / ws / clipboard / download — <strong>无作者业务 JS</strong>。</p>
<p id="path">path: /</p>
<nav>
<a href="#/" id="nav-home">首页</a>
<a href="#/about" id="nav-about">关于</a>
<a href="#/net" id="nav-net">网络</a>
</nav>
<section id="panel-home">
<h2>待办</h2>
<input id="draft" type="text" placeholder="新项…" disabled />
<button id="add" type="button" disabled>添加</button>
<button id="save" class="secondary" type="button" disabled>存草稿</button>
<button id="load" class="secondary" type="button" disabled>读草稿</button>
<button id="copy-log" class="secondary" type="button" disabled>复制列表</button>
<button id="dl-list" class="secondary" type="button" disabled>下载列表</button>
<ul id="items"></ul>
<p>计时:<span id="tick">0</span>s
<button id="start-tick" type="button" disabled>开始</button>
<button id="stop-tick" class="secondary" type="button" disabled>停止</button>
</p>
</section>
<section id="panel-about" hidden>
<h2>关于</h2>
<p>作者只写 <code>app.mq.md</code>。官方 bridge 提供 DOM / 路由 / storage / ws / fetch_all 等宿主能力。</p>
</section>
<section id="panel-net" hidden>
<h2>网络</h2>
<p id="net-out">idle</p>
<button id="fetch-all" type="button" disabled>fetch_all ×2 uuid</button>
<button id="ws-open" type="button" disabled>WS 打开</button>
<input id="ws-msg" type="text" placeholder="ws 消息" disabled />
<button id="ws-send" type="button" disabled>WS 发送</button>
<button id="ws-close" class="secondary" type="button" disabled>WS 关闭</button>
</section>
<pre id="log">loading…</pre>
<script
type="module"
src="./marqdo-bridge.js"
data-mq-wasm="./marqdo_wasm.wasm"
data-mq-source-url="./app.mq.md"
data-mq-ready="#log"
data-mq-enable="#draft,#add,#save,#load,#start-tick,#stop-tick,#fetch-all,#ws-open,#ws-msg,#ws-send,#ws-close,#copy-log,#dl-list"
></script>
</body>
</html>
File diff suppressed because it is too large. Load diff
+21
View File
@@ -0,0 +1,21 @@
# browser-hello(WASM C1–C4 / 路线 D)
浏览器内跑 Marqdo。**无作者业务 JS**——只保留官方 `marqdo-bridge.js`(`marqdo wasm build` 拷贝)。客户端 `.mq.md` 用 **GFM 表格 + `lib/browser`**。
```bash
# 仓库根目录
cargo build -p marqdo --release
./target/release/marqdo wasm build -o examples/browser-hello
cd examples/browser-hello
python3 -m http.server 8765
```
| 页 | 说明 |
|----|------|
| [/](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) |
自启方式:脚本上的 `data-mq-source-url` / `data-mq-playground`,或 `#marqdo-boot` JSON。详见 [browser-wasm-d.md](../../doc/roadmap/browser-wasm-d.md)。
+27
View File
@@ -0,0 +1,27 @@
---
title: browser counter (C3)
description: wire table + browser.set_text — no json glue
import browser:lib/browser.mq.md
---
# main
*`count` = 0*
`wire` =
| @ | 选择器 | 事件 | 调用 |
|---|--------|------|------|
| 1 | "#bump" | click | bump |
| 2 | "#reset" | click | reset |
**`wire`**
## bump
*`count` = count + 1*
*`label` = > str count*
**> browser.set_text sel="#count" text=label**
## reset
*`count` = 0*
**> browser.set_text sel="#count" text="0"**
+86
View File
@@ -0,0 +1,86 @@
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Marqdo · fetch / after (C4)</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(800px 420px at 0% 100%, #d5e4d8 0%, transparent 55%),
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; }
#status {
font-family: "IBM Plex Mono", ui-monospace, monospace;
font-size: 0.95rem;
line-height: 1.45;
white-space: pre-wrap;
word-break: break-all;
min-height: 4rem;
margin: 1rem 0 1.25rem;
padding: 0.85rem 1rem;
background: rgba(255,255,255,0.55);
border: 1px solid #b7c7bb;
}
button {
margin-right: 0.5rem;
margin-bottom: 0.4rem;
padding: 0.55rem 1.1rem;
border: 0;
background: var(--accent);
color: #f5faf6;
font: inherit;
cursor: pointer;
}
button.secondary { background: #3a4740; }
button:disabled { opacity: 0.5; cursor: wait; }
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">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="./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>
+42
View File
@@ -0,0 +1,42 @@
---
title: browser fetch (C4)
description: fetch/after effects via lib/browser — no json glue
import browser:lib/browser.mq.md
---
# main
`wire` =
| @ | 选择器 | 事件 | 调用 |
|---|--------|------|------|
| 1 | "#load" | click | load |
| 2 | "#ping" | click | ping |
**`wire`**
## load
*`msg` = > browser.set_text sel="#status" text="loading…"*
*`req` = > browser.fetch url="https://httpbin.org/uuid" then="on_uuid"*
**> browser.merge a=msg b=req**
## on_uuid
+ `ok`
+ `status`
+ `body`=""
+ `error`=""
1. ok
**> browser.set_text sel="#status" text=body**
2. *
**> browser.set_text sel="#status" text="fetch failed"**
## ping
*`msg` = > browser.set_text sel="#status" text="wait 600ms…"*
*`t` = > browser.after ms=600 then="on_ping"*
**> browser.merge a=msg b=t**
## on_ping
+ `ok`=True
**> browser.set_text sel="#status" text="pong"**
+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>
+33
View File
@@ -0,0 +1,33 @@
---
title: browser form (D3)
description: input wire passes value; effects via lib/browser
import browser:lib/browser.mq.md
import table:lib/table.mq.md
---
# main
`wire` =
| @ | 选择器 | 事件 | 调用 |
|---|--------|------|------|
| 1 | "#name" | input | on_input |
**`wire`**
## on_input
+ `value`=""
+ `event`=""
1. `value` != ""
*`label` = "你好," + value*
*`ret` = > browser.set_text sel="#echo" text=label*
*`cls` = > browser.set_class sel="#echo" class="hi"*
*`ret` = > browser.merge a=ret b=cls*
*`attrs` = > table.put in=None at="data-name" value=value*
*`attr` = > browser.set_attr sel="#echo" attrs=attrs*
**> browser.merge a=ret b=attr**
2. *
*`ret` = > browser.set_text sel="#echo" text="(等待输入)"*
*`cls` = > browser.set_class sel="#echo" class=""*
**> browser.merge a=ret b=cls**
+88
View File
@@ -0,0 +1,88 @@
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Marqdo browser hello (WASM C1)</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(1200px 600px at 10% -10%, #c5dcc8 0%, transparent 55%),
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;
letter-spacing: -0.02em;
}
.lead { color: var(--muted); margin: 0 0 1.5rem; max-width: 36rem; }
label { display: block; font-size: 0.85rem; color: var(--muted); margin-bottom: 0.35rem; }
textarea {
width: min(40rem, 100%);
min-height: 10rem;
padding: 0.75rem 0.9rem;
border: 1px solid #b7c7bb;
border-radius: 2px;
background: rgba(255,255,255,0.7);
font-family: "IBM Plex Mono", ui-monospace, monospace;
font-size: 0.9rem;
line-height: 1.45;
}
button {
margin-top: 0.85rem;
padding: 0.55rem 1.1rem;
border: 0;
background: var(--accent);
color: #f5faf6;
font: inherit;
cursor: pointer;
}
button:disabled { opacity: 0.5; cursor: wait; }
pre {
margin-top: 1.25rem;
width: min(40rem, 100%);
padding: 0.9rem 1rem;
background: #122018;
color: #d7eadc;
overflow: auto;
font-size: 0.85rem;
line-height: 1.4;
}
.err { color: #ffb4a8; }
</style>
</head>
<body>
<h1>Marqdo</h1>
<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
> print text=Hello from browser WASM!
</textarea>
<div>
<button id="run" disabled>运行</button>
</div>
<pre id="out">loading wasm…</pre>
<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>
+79
View File
@@ -0,0 +1,79 @@
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Marqdo · 交互装配 (C3)</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(900px 500px at 90% 0%, #cfe0d2 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.5rem; max-width: 36rem; }
#count {
font-family: "IBM Plex Serif", serif;
font-size: 4rem;
line-height: 1;
margin: 1rem 0 1.25rem;
letter-spacing: -0.04em;
}
button {
margin-right: 0.5rem;
padding: 0.55rem 1.1rem;
border: 0;
background: var(--accent);
color: #f5faf6;
font: inherit;
cursor: pointer;
}
button.secondary { background: #3a4740; }
pre {
margin-top: 1.5rem;
width: min(40rem, 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">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="./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>
File diff suppressed because it is too large. Load diff
+20
View File
@@ -0,0 +1,20 @@
# browser-media(路线 F)
作者**零业务 JS**;`.mq.md` 用 **GFM 表格 + `lib/browser`**(禁止 `json.set` 链)。
| 能力 | 演示 |
|------|------|
| read_file | 文本 / DataURL |
| canvas | `@` 指令表 |
| audio | beep(Web Audio) |
| observe | Intersection + Resize |
| drag/drop | `data-drag` → `drop_text` |
```bash
cargo build -p marqdo --release
./target/release/marqdo wasm build -o examples/browser-media
cd examples/browser-media && python3 -m http.server 8767
```
写法约定见 [.cursor/skills/marqdo-dev/SKILL.md](../../.cursor/skills/marqdo-dev/SKILL.md)。
路线图:[browser-wasm-f.md](../../doc/roadmap/browser-wasm-f.md)。
+98
View File
@@ -0,0 +1,98 @@
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Marqdo · browser-media (route F)</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: linear-gradient(165deg, #f3f7f2, var(--paper));
padding: 2rem clamp(1rem, 4vw, 3rem);
}
h1 { font-family: "IBM Plex Serif", "Noto Serif SC", serif; margin: 0 0 0.35rem; }
.lead { color: var(--muted); max-width: 42rem; }
section { margin: 1.5rem 0; padding: 1rem 0; border-top: 1px solid #c5d4c9; }
button {
padding: 0.45rem 0.9rem; border: 0; background: var(--accent); color: #f5faf6;
font: inherit; cursor: pointer; margin: 0.2rem 0.35rem 0.2rem 0;
}
button.secondary { background: #3a4740; }
#pad {
display: block; background: #fff; border: 1px solid #b7c7bb;
margin-top: 0.75rem;
}
#chips { display: flex; gap: 0.5rem; flex-wrap: wrap; margin: 0.75rem 0; }
#chips span {
padding: 0.45rem 0.75rem; background: rgba(255,255,255,0.75);
border: 1px dashed #2f6f4e; cursor: grab; user-select: none;
}
#dropzone {
min-height: 3.5rem; padding: 0.85rem; border: 2px dashed #7a9584;
background: rgba(255,255,255,0.45); color: var(--muted);
}
#beacon {
margin-top: 8rem; padding: 2rem; background: #2f6f4e; color: #f5faf6;
text-align: center;
}
#preview { margin-top: 0.5rem; min-height: 1rem; }
pre {
margin-top: 1rem; padding: 0.85rem 1rem; background: #122018; color: #d7eadc;
font-size: 0.8rem; overflow: auto; max-width: 42rem;
}
.err { color: #ffb4a8; }
</style>
</head>
<body>
<h1>Marqdo browser-media</h1>
<p class="lead">路线 F:文件 / Canvas / Audio / Observer / 拖放 — <strong>无作者业务 JS</strong>。</p>
<section>
<h2>F1 文件</h2>
<input id="file" type="file" accept="image/*,text/*,.txt,.md" disabled />
<button id="read-text" type="button" disabled>读文本</button>
<button id="read-dataurl" type="button" disabled>读 DataURL</button>
<div id="preview"></div>
</section>
<section>
<h2>F2 Canvas · F3 Audio</h2>
<button id="draw" type="button" disabled>绘制</button>
<button id="play" type="button" disabled>蜂鸣</button>
<canvas id="pad" width="280" height="120"></canvas>
</section>
<section>
<h2>F4 Observer</h2>
<button id="watch" type="button" disabled>开始观察</button>
<button id="unwatch" class="secondary" type="button" disabled>停止</button>
<p id="obs">idle</p>
<p>向下滚动可触发 Intersection;改窗口大小触发 Resize。</p>
</section>
<section>
<h2>F5 拖放</h2>
<div id="chips">
<span draggable="true" data-drag="alpha">alpha</span>
<span draggable="true" data-drag="beta">beta</span>
<span draggable="true" data-drag="gamma">gamma</span>
</div>
<div id="dropzone">拖到这里</div>
</section>
<div id="beacon">beacon(滚到可见)</div>
<pre id="log">loading…</pre>
<script
type="module"
src="./marqdo-bridge.js"
data-mq-wasm="./marqdo_wasm.wasm"
data-mq-source-url="./media.mq.md"
data-mq-ready="#log"
data-mq-enable="#file,#read-text,#read-dataurl,#draw,#play,#watch,#unwatch"
></script>
</body>
</html>
File diff suppressed because it is too large. Load diff
+162
View File
@@ -0,0 +1,162 @@
---
title: browser-media (route F)
description: file / canvas / audio / observers / drag — GFM tables + lib/browser
import browser:lib/browser.mq.md
import table:lib/table.mq.md
---
# main
Route F demo: author data stays in tables; effects via `browser.*`.
*`obs_on` = False*
`wire` =
| @ | 选择器 | 事件 | 调用 | 委托 |
|---|--------|------|------|------|
| 1 | "#read-text" | click | read_text | |
| 2 | "#read-dataurl" | click | read_dataurl | |
| 3 | "#draw" | click | draw_box | |
| 4 | "#play" | click | play_tone | |
| 5 | "#watch" | click | start_watch | |
| 6 | "#unwatch" | click | stop_watch | |
| 7 | "#chips" | dragstart | on_drag | "[data-drag]" |
| 8 | "#dropzone" | dragover | on_dragover | |
| 9 | "#dropzone" | drop | on_drop | |
*`ready` = > browser.set_text sel="#log" text="ready (route F)"*
*`boot` = > table.put in=None at="wire" value=wire*
**> browser.merge a=boot b=ready**
## read_text
**> browser.read_file sel="#file" then="on_file" as="text"**
## read_dataurl
**> browser.read_file sel="#file" then="on_file" as="data_url"**
## on_file
+ `ok`=False
+ `name`=""
+ `size`=0
+ `body`=""
+ `data_url`=""
+ `as`=""
+ `error`=""
1. `ok`
1. `as` == "data_url"
*`n` = > len value=data_url*
*`ns` = > str `n`*
*`preview` = name + " data_url chars=" + ns*
*`ret` = > browser.set_text sel="#log" text=preview*
1. `data_url` != ""
*`h` = "<img alt=\"preview\" src=\"" + data_url + "\" style=\"max-width:12rem;max-height:8rem\" />"*
*`img` = > browser.set_html sel="#preview" html=h*
**> browser.merge a=ret b=img**
2. *
**ret**
2. *
*`n` = > len value=body*
*`ns` = > str `n`*
*`ss` = > str `size`*
*`preview` = name + " (" + ss + " B, chars=" + ns + ") ok"*
**> browser.set_text sel="#log" text=preview**
2. *
*`preview` = "file error: " + error*
**> browser.set_text sel="#log" text=preview**
## draw_box
Canvas commands as a readable `@` table:
`commands` =
| @ | op | x | y | w | h | fill | stroke | text |
|---|----|---|---|---|---|------|--------|------|
| 1 | fillrect | 10 | 10 | 120 | 80 | "#2f6f4e" | | |
| 2 | strokerect | 20 | 20 | 100 | 60 | | "#122018" | |
| 3 | filltext | 40 | 55 | | | "#f5faf6" | | Marqdo |
*`cv` = > browser.canvas sel="#pad" commands=commands clear=True*
*`msg` = > browser.set_text sel="#log" text="canvas drawn"*
**> browser.merge a=cv b=msg**
## play_tone
*`tone` = > browser.audio op="play" id="demo" src="beep" freq=523 ms=220*
*`msg` = > browser.set_text sel="#log" text="audio beep"*
**> browser.merge a=tone b=msg**
## start_watch
*`obs_on` = True*
`obs` =
| @ | kind | sel | id | then | threshold |
|---|------|-----|----|------|-----------|
| 1 | intersect | "#beacon" | beacon | on_intersect | 0.25 |
| 2 | resize | "#pad" | pad | on_resize | |
*`o` = > browser.observe specs=obs*
*`msg` = > browser.set_text sel="#log" text="observers on"*
**> browser.merge a=o b=msg**
## stop_watch
*`obs_on` = False*
`ids` =
| @ | id |
|---|----|
| 1 | beacon |
| 2 | pad |
*`u` = > browser.unobserve specs=ids*
*`msg` = > browser.set_text sel="#log" text="observers off"*
**> browser.merge a=u b=msg**
## on_intersect
+ `intersecting`=False
+ `ratio`=0
1. `obs_on`
*`state` = "hidden"*
1. `intersecting`
*`state` = "visible"*
2. *
---
*`r` = > str `ratio`*
*`msg` = "beacon " + state + " ratio=" + r*
**> browser.set_text sel="#obs" text=msg**
2. *
****
## on_resize
+ `width`=0
+ `height`=0
1. `obs_on`
*`w` = > str `width`*
*`h` = > str `height`*
*`msg` = "pad size " + w + "×" + h*
**> browser.set_text sel="#obs" text=msg**
2. *
****
## on_drag
+ `drag`=""
*`msg` = "dragging: " + drag*
**> browser.set_text sel="#log" text=msg**
## on_dragover
****
## on_drop
+ `drop_text`=""
*`msg` = "dropped: " + drop_text*
*`h` = "<strong>" + drop_text + "</strong>"*
*`t` = > browser.set_text sel="#log" text=msg*
*`box` = > browser.set_html sel="#dropzone" html=h*
**> browser.merge a=t b=box**
+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,30 @@
---
title: client counter (route D)
description: wired by client_embed auto-mount; GFM + lib/browser
import browser:lib/browser.mq.md
import table:lib/table.mq.md
---
# main
*`count` = 0*
`wire` =
| @ | 选择器 | 事件 | 调用 |
|---|--------|------|------|
| 1 | "#bump" | click | bump |
| 2 | "#reset" | click | reset |
*`ready` = > browser.set_text sel="#log" text="client.mq.md ready"*
*`boot` = > table.put in=None at="wire" value=wire*
**> browser.merge a=boot b=ready**
## bump
*`count` = count + 1*
*`label` = > str count*
**> browser.set_text sel="#count" text=label**
## reset
*`count` = 0*
**> browser.set_text sel="#count" text="0"**
File diff suppressed because it is too large. Load diff
+128 -2
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 table:lib/table.mq.md
---
## ensure_plugin
@@ -24,8 +25,11 @@ Load the ABI v2 `web` plugin once.
Assemble a GFM style table into a CSS string. Two shapes are accepted:
`|选择器|属性|值|` rule rows (arbitrary selectors; rows sharing a selector are
merged, and a leading `|媒体|` column groups rows into `@media` blocks), or
`|属性|值|` property rows wrapped as `.name { … }`. Styles stay as data tables,
`make_style` turns them into CSS — 样式即数据、装配即函数.
`|属性|值|` property rows wrapped as `.name { … }`. Selectors starting with
`@keyframes name` emit keyframe blocks (`属性` = stop `from`/`to`/`N%`,
`值` = `prop: val` or use `@keyframes name from` + normal 属性/值). Quote CSS
values that contain `/` (e.g. `"16/9"`, `"1/5"`); bare `1/5` is integer division.
Styles stay as data tables, `make_style` turns them into CSS — 样式即数据、装配即函数.
> ensure_plugin
**> web_style name=`name` table=`table`**
@@ -50,6 +54,128 @@ 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.
Prefer authoring with `lib/browser` + GFM tables in client `.mq.md` ([marqdo-dev](../../.cursor/skills/marqdo-dev/SKILL.md)).
*`m` = > table.put in=None at=sel value=text*
**> table.put in=None at="set_text" value=m**
## dom_patch
+ `set_text`=None
+ `set_value`=None
+ `set_attr`=None
+ `set_class`=None
+ `toggle_class`=None
+ `set_style`=None
+ `set_html`=None
+ `render_list`=None
+ `navigate`=None
+ `storage`=None
+ `ws`=None
+ `fetch`=None
+ `fetch_all`=None
+ `after`=None
+ `interval`=None
+ `clear_interval`=None
+ `focus`=None
+ `blur`=None
+ `scroll_into`=None
+ `canvas`=None
+ `audio`=None
+ `read_file`=None
+ `observe`=None
+ `unobserve`=None
+ `wire`=None
Merge browser effect keys into one return map (omit `None`). Route E/F effects included.
*`out` = > table.put in=None at="_mq" value=True*
1. `set_text` != None
*`out` = > table.put in=`out` at="set_text" value=set_text*
1. `set_value` != None
*`out` = > table.put in=`out` at="set_value" value=set_value*
1. `set_attr` != None
*`out` = > table.put in=`out` at="set_attr" value=set_attr*
1. `set_class` != None
*`out` = > table.put in=`out` at="set_class" value=set_class*
1. `toggle_class` != None
*`out` = > table.put in=`out` at="toggle_class" value=toggle_class*
1. `set_style` != None
*`out` = > table.put in=`out` at="set_style" value=set_style*
1. `set_html` != None
*`out` = > table.put in=`out` at="set_html" value=set_html*
1. `render_list` != None
*`out` = > table.put in=`out` at="render_list" value=render_list*
1. `navigate` != None
*`out` = > table.put in=`out` at="navigate" value=navigate*
1. `storage` != None
*`out` = > table.put in=`out` at="storage" value=storage*
1. `ws` != None
*`out` = > table.put in=`out` at="ws" value=ws*
1. `fetch` != None
*`out` = > table.put in=`out` at="fetch" value=fetch*
1. `fetch_all` != None
*`out` = > table.put in=`out` at="fetch_all" value=fetch_all*
1. `after` != None
*`out` = > table.put in=`out` at="after" value=after*
1. `interval` != None
*`out` = > table.put in=`out` at="interval" value=interval*
1. `clear_interval` != None
*`out` = > table.put in=`out` at="clear_interval" value=clear_interval*
1. `focus` != None
*`out` = > table.put in=`out` at="focus" value=focus*
1. `blur` != None
*`out` = > table.put in=`out` at="blur" value=blur*
1. `scroll_into` != None
*`out` = > table.put in=`out` at="scroll_into" value=scroll_into*
1. `canvas` != None
*`out` = > table.put in=`out` at="canvas" value=canvas*
1. `audio` != None
*`out` = > table.put in=`out` at="audio" value=audio*
1. `read_file` != None
*`out` = > table.put in=`out` at="read_file" value=read_file*
1. `observe` != None
*`out` = > table.put in=`out` at="observe" value=observe*
1. `unobserve` != None
*`out` = > table.put in=`out` at="unobserve" value=unobserve*
1. `wire` != None
*`out` = > table.put in=`out` at="wire" value=wire*
**out**
## list_html
+ `sel`
+ `tag`="li"
+ `items`
Build a `render_list` effect: `{ render_list: { sel: { tag, items } } }`.
*`spec` = > table.put in=None at="tag" value=tag*
*`spec` = > table.put in=`spec` at="items" value=items*
*`m` = > table.put in=None at=sel value=spec*
**> table.put in=None at="render_list" value=m**
# page
+ `title`="Marqdo Web"
+ `intro`=""
+124
View File
@@ -3,6 +3,7 @@ title: ext/web/网页
description: 官方网站类(中文)。表格 + 方法;不写袋式胶水。
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
import table:lib/table.mq.md
---
## 确保插件
@@ -24,6 +25,9 @@ import sys:lib/sys.mq.md
把 GFM 样式表装配成一段 CSS 文本。支持两种表形:
`|选择器|属性|值|` 规则行(选择器任意,同一选择器多行合并成一条规则;
加 `|媒体|` 列即可分组进 `@media` 块),或 `|属性|值|` 属性行(按 `.名 { … }` 包裹)。
选择器以 `@keyframes 名` 开头时输出关键帧块(`属性` 为停点 `from`/`to`/`N%`,
`值` 写 `opacity: 0` 等声明;也可用 `@keyframes 名 from` + 普通属性/值)。
含 `/` 的 CSS 值请加引号(如 `"16/9"`、`"1/5"`),否则按表达式除法求值。
样式即数据、装配即函数 —— 主题模块据此把样式表拼成完整样式表。
> 确保插件
@@ -47,6 +51,126 @@ 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` 效应表。客户端优先 `lib/浏览器` + GFM 表格。
*`m` = > table.put in=None at=选择器 value=文本*
**> table.put in=None at="set_text" value=m**
## DOM补丁
+ `set_text`=None
+ `set_value`=None
+ `set_attr`=None
+ `set_class`=None
+ `toggle_class`=None
+ `set_style`=None
+ `set_html`=None
+ `render_list`=None
+ `navigate`=None
+ `storage`=None
+ `ws`=None
+ `fetch`=None
+ `fetch_all`=None
+ `after`=None
+ `interval`=None
+ `clear_interval`=None
+ `focus`=None
+ `blur`=None
+ `scroll_into`=None
+ `canvas`=None
+ `audio`=None
+ `read_file`=None
+ `observe`=None
+ `unobserve`=None
+ `wire`=None
合并浏览器效应键(含路线 E/F)为一张返回表(跳过 `None`)。
*`out` = > table.put in=None at="_mq" value=True*
1. `set_text` != None
*`out` = > table.put in=`out` at="set_text" value=set_text*
1. `set_value` != None
*`out` = > table.put in=`out` at="set_value" value=set_value*
1. `set_attr` != None
*`out` = > table.put in=`out` at="set_attr" value=set_attr*
1. `set_class` != None
*`out` = > table.put in=`out` at="set_class" value=set_class*
1. `toggle_class` != None
*`out` = > table.put in=`out` at="toggle_class" value=toggle_class*
1. `set_style` != None
*`out` = > table.put in=`out` at="set_style" value=set_style*
1. `set_html` != None
*`out` = > table.put in=`out` at="set_html" value=set_html*
1. `render_list` != None
*`out` = > table.put in=`out` at="render_list" value=render_list*
1. `navigate` != None
*`out` = > table.put in=`out` at="navigate" value=navigate*
1. `storage` != None
*`out` = > table.put in=`out` at="storage" value=storage*
1. `ws` != None
*`out` = > table.put in=`out` at="ws" value=ws*
1. `fetch` != None
*`out` = > table.put in=`out` at="fetch" value=fetch*
1. `fetch_all` != None
*`out` = > table.put in=`out` at="fetch_all" value=fetch_all*
1. `after` != None
*`out` = > table.put in=`out` at="after" value=after*
1. `interval` != None
*`out` = > table.put in=`out` at="interval" value=interval*
1. `clear_interval` != None
*`out` = > table.put in=`out` at="clear_interval" value=clear_interval*
1. `focus` != None
*`out` = > table.put in=`out` at="focus" value=focus*
1. `blur` != None
*`out` = > table.put in=`out` at="blur" value=blur*
1. `scroll_into` != None
*`out` = > table.put in=`out` at="scroll_into" value=scroll_into*
1. `canvas` != None
*`out` = > table.put in=`out` at="canvas" value=canvas*
1. `audio` != None
*`out` = > table.put in=`out` at="audio" value=audio*
1. `read_file` != None
*`out` = > table.put in=`out` at="read_file" value=read_file*
1. `observe` != None
*`out` = > table.put in=`out` at="observe" value=observe*
1. `unobserve` != None
*`out` = > table.put in=`out` at="unobserve" value=unobserve*
1. `wire` != None
*`out` = > table.put in=`out` at="wire" value=wire*
**out**
## 列表HTML
+ `选择器`
+ `标签`="li"
+ `项`
构造 `render_list` 效应。
*`spec` = > table.put in=None at="tag" value=标签*
*`spec` = > table.put in=`spec` at="items" value=项*
*`m` = > table.put in=None at=选择器 value=spec*
**> table.put in=None at="render_list" value=m**
# 页面
+ `标题`="站点"
+ `引言`=""
+236
View File
@@ -0,0 +1,236 @@
---
title: lib/browser
description: >-
Readable browser effect helpers for WASM clients. Prefer GFM tables + these
helpers; do not build effects with json.set chains.
import table:lib/table.mq.md
---
## set_text
+ `sel`
+ `text`
Build set_text effect map for the official bridge.
*`m` = > table.put in=None at=sel value=text*
**> table.put in=None at="set_text" value=m**
## set_html
+ `sel`
+ `html`
Build set_html effect map.
*`m` = > table.put in=None at=sel value=html*
**> table.put in=None at="set_html" value=m**
## set_value
+ `sel`
+ `value`
Build set_value effect map.
*`m` = > table.put in=None at=sel value=value*
**> table.put in=None at="set_value" value=m**
## set_class
+ `sel`
+ `class`
Build set_class effect map.
*`m` = > table.put in=None at=sel value=class*
**> table.put in=None at="set_class" value=m**
## set_attr
+ `sel`
+ `attrs`
Build set_attr effect map; attrs is usually a small map of attribute names to values.
*`m` = > table.put in=None at=sel value=attrs*
**> table.put in=None at="set_attr" value=m**
## wrap
+ `key`
+ `value`
Single-key effect map wrapper.
**> table.put in=None at=key value=value**
## merge
+ `a`
+ `b`
Merge two effect maps; right-hand keys win.
**> table.merge a=`a` b=`b`**
## canvas
+ `sel`
+ `commands`
+ `clear`=True
Build canvas effect; commands is usually an @ GFM table.
`spec` =
| sel | clear | commands |
|-----|-------|----------|
| `sel` | `clear` | `commands` |
**> table.put in=None at="canvas" value=spec**
## audio
+ `op`="play"
+ `id`="default"
+ `src`=""
+ `freq`=None
+ `ms`=None
+ `sel`=""
Build audio effect for the bridge.
*`spec` = > table.put in=None at="op" value=op*
*`spec` = > table.put in=`spec` at="id" value=id*
1. `src` != ""
*`spec` = > table.put in=`spec` at="src" value=src*
1. `freq` != None
*`spec` = > table.put in=`spec` at="freq" value=freq*
1. `ms` != None
*`spec` = > table.put in=`spec` at="ms" value=ms*
1. `sel` != ""
*`spec` = > table.put in=`spec` at="sel" value=sel*
**> table.put in=None at="audio" value=spec**
## read_file
+ `sel`
+ `then`
+ `as`="text"
Build read_file effect.
`spec` =
| sel | as | then |
|-----|----|------|
| `sel` | `as` | `then` |
**> table.put in=None at="read_file" value=spec**
## observe
+ `specs`
Build observe effect; specs is one map or an @ list of maps.
**> table.put in=None at="observe" value=specs**
## unobserve
+ `specs`
Build unobserve effect; specs is a map or @ list with id.
**> table.put in=None at="unobserve" value=specs**
## focus
+ `sel`
**> table.put in=None at="focus" value=sel**
## navigate
+ `url`
+ `replace`=False
`spec` =
| url | replace |
|-----|---------|
| `url` | `replace` |
**> table.put in=None at="navigate" value=spec**
## storage
+ `spec`
**> table.put in=None at="storage" value=spec**
## interval
+ `ms`
+ `then`
+ `id`="default"
`spec` =
| ms | then | id |
|----|------|----|
| `ms` | `then` | `id` |
**> table.put in=None at="interval" value=spec**
## clear_interval
+ `id`="default"
*`spec` = > table.put in=None at="id" value=id*
**> table.put in=None at="clear_interval" value=spec**
## fetch
+ `url`
+ `then`
+ `method`="GET"
`spec` =
| url | then | method |
|-----|------|--------|
| `url` | `then` | `method` |
**> table.put in=None at="fetch" value=spec**
## fetch_all
+ `requests`
+ `then`
`spec` =
| requests | then |
|----------|------|
| `requests` | `then` |
**> table.put in=None at="fetch_all" value=spec**
## after
+ `ms`
+ `then`
`spec` =
| ms | then |
|----|------|
| `ms` | `then` |
**> table.put in=None at="after" value=spec**
## ws
+ `spec`
**> table.put in=None at="ws" value=spec**
## clipboard
+ `text`
*`spec` = > table.put in=None at="text" value=text*
**> table.put in=None at="clipboard" value=spec**
## download
+ `body`
+ `filename`="download.txt"
+ `mime`="text/plain;charset=utf-8"
`spec` =
| body | filename | mime |
|------|----------|------|
| `body` | `filename` | `mime` |
**> table.put in=None at="download" value=spec**
+235
View File
@@ -0,0 +1,235 @@
---
title: lib/浏览器
description: >-
浏览器效应助手(WASM 客户端)。优先 GFM 表格 + 本库;勿用 json.set 链拼效应。
import table:lib/table.mq.md
---
## 设文本
+ `选择器`
+ `文本`
构造 set_text 效应。
*`m` = > table.put in=None at=选择器 value=文本*
**> table.put in=None at="set_text" value=m**
## 设HTML
+ `选择器`
+ `html`
构造 set_html 效应。
*`m` = > table.put in=None at=选择器 value=html*
**> table.put in=None at="set_html" value=m**
## 设值
+ `选择器`
+ `值`
构造 set_value 效应。
*`m` = > table.put in=None at=选择器 value=值*
**> table.put in=None at="set_value" value=m**
## 设类
+ `选择器`
+ `类`
构造 set_class 效应。
*`m` = > table.put in=None at=选择器 value=类*
**> table.put in=None at="set_class" value=m**
## 设属性
+ `选择器`
+ `属性`
构造 set_attr 效应。
*`m` = > table.put in=None at=选择器 value=属性*
**> table.put in=None at="set_attr" value=m**
## 包装
+ `键`
+ `值`
单键效应包装。
**> table.put in=None at=键 value=值**
## 合并
+ `甲`
+ `乙`
合并两张效应表,右侧优先。
**> table.merge a=`甲` b=`乙`**
## 画布
+ `选择器`
+ `命令`
+ `清空`=True
构造 canvas 效应;命令一般为 @ 行表。
`spec` =
| sel | clear | commands |
|-----|-------|----------|
| `选择器` | `清空` | `命令` |
**> table.put in=None at="canvas" value=spec**
## 音频
+ `操作`="play"
+ `id`="default"
+ `源`=""
+ `频率`=None
+ `毫秒`=None
+ `选择器`=""
构造 audio 效应。
*`spec` = > table.put in=None at="op" value=操作*
*`spec` = > table.put in=`spec` at="id" value=id*
1. `源` != ""
*`spec` = > table.put in=`spec` at="src" value=源*
1. `频率` != None
*`spec` = > table.put in=`spec` at="freq" value=频率*
1. `毫秒` != None
*`spec` = > table.put in=`spec` at="ms" value=毫秒*
1. `选择器` != ""
*`spec` = > table.put in=`spec` at="sel" value=选择器*
**> table.put in=None at="audio" value=spec**
## 读文件
+ `选择器`
+ `然后`
+ `格式`="text"
构造 read_file 效应。
`spec` =
| sel | as | then |
|-----|----|------|
| `选择器` | `格式` | `然后` |
**> table.put in=None at="read_file" value=spec**
## 观察
+ `规格`
构造 observe 效应。
**> table.put in=None at="observe" value=规格**
## 取消观察
+ `规格`
构造 unobserve 效应。
**> table.put in=None at="unobserve" value=规格**
## 聚焦
+ `选择器`
**> table.put in=None at="focus" value=选择器**
## 导航
+ `url`
+ `替换`=False
`spec` =
| url | replace |
|-----|---------|
| `url` | `替换` |
**> table.put in=None at="navigate" value=spec**
## 存储
+ `规格`
**> table.put in=None at="storage" value=规格**
## 定时
+ `毫秒`
+ `然后`
+ `id`="default"
`spec` =
| ms | then | id |
|----|------|----|
| `毫秒` | `然后` | `id` |
**> table.put in=None at="interval" value=spec**
## 清定时
+ `id`="default"
*`spec` = > table.put in=None at="id" value=id*
**> table.put in=None at="clear_interval" value=spec**
## 拉取
+ `url`
+ `然后`
+ `方法`="GET"
`spec` =
| url | then | method |
|-----|------|--------|
| `url` | `然后` | `方法` |
**> table.put in=None at="fetch" value=spec**
## 拉取全部
+ `请求`
+ `然后`
`spec` =
| requests | then |
|----------|------|
| `请求` | `然后` |
**> table.put in=None at="fetch_all" value=spec**
## 延后
+ `毫秒`
+ `然后`
`spec` =
| ms | then |
|----|------|
| `毫秒` | `然后` |
**> table.put in=None at="after" value=spec**
## 套接字
+ `规格`
**> table.put in=None at="ws" value=规格**
## 剪贴板
+ `文本`
*`spec` = > table.put in=None at="text" value=文本*
**> table.put in=None at="clipboard" value=spec**
## 下载
+ `正文`
+ `文件名`="download.txt"
+ `mime`="text/plain;charset=utf-8"
`spec` =
| body | filename | mime |
|------|----------|------|
| `正文` | `文件名` | `mime` |
**> table.put in=None at="download" value=spec**
+16 -23
View File
@@ -1211,16 +1211,6 @@ fn flash_html(flash: Option<&str>) -> String {
}
}
fn truncate_cell(s: &str, max: usize) -> String {
let mut it = s.chars();
let head: String = it.by_ref().take(max).collect();
if it.next().is_some() {
format!("{head}…")
} else {
head
}
}
fn admin_shell(st: &AppState, title: &str, active: Option<&str>, inner: &str) -> String {
let tables = st
.db_url
@@ -1270,7 +1260,7 @@ fn admin_shell(st: &AppState, title: &str, active: Option<&str>, inner: &str) ->
<style>
:root {{ --ink:#1c1917; --muted:#78716c; --paper:#fafaf9; --line:#e7e5e4; --accent:#0f766e; --ok:#166534; --err:#b91c1c; --side:#f5f5f4; }}
* {{ box-sizing:border-box; }}
body {{ margin:0; font-family:"IBM Plex Sans","Noto Sans SC",sans-serif; background:var(--paper); color:var(--ink); min-height:100vh; display:grid; grid-template-columns:14rem 1fr; }}
body {{ margin:0; font-family:"IBM Plex Sans","Noto Sans SC",sans-serif; background:var(--paper); color:var(--ink); min-height:100vh; display:grid; grid-template-columns:14rem minmax(0,1fr); }}
@media (max-width:720px) {{ body {{ grid-template-columns:1fr; }} .admin-nav {{ border-right:0; border-bottom:1px solid var(--line); }} }}
.admin-nav {{ background:var(--side); border-right:1px solid var(--line); padding:1.1rem 1rem 1.5rem; }}
.admin-nav .brand {{ display:block; font-weight:600; font-size:1.05rem; margin-bottom:1rem; color:var(--ink); }}
@@ -1280,7 +1270,7 @@ body {{ margin:0; font-family:"IBM Plex Sans","Noto Sans SC",sans-serif; backgro
.admin-nav .nav-label {{ margin:1.1rem 0 .35rem; font-size:.75rem; text-transform:uppercase; letter-spacing:.04em; color:var(--muted); }}
.admin-nav .nav-foot {{ margin-top:1.5rem; font-size:.9rem; }}
.admin-nav .muted {{ color:var(--muted); font-size:.9rem; }}
.admin-main {{ padding:1.25rem 1.5rem 2rem; max-width:56rem; }}
.admin-main {{ padding:1.25rem 1.5rem 2rem; min-width:0; width:100%; max-width:none; overflow-x:auto; }}
.admin-main h1 {{ margin:0 0 .35rem; font-size:1.65rem; }}
.crumbs {{ color:var(--muted); font-size:.85rem; margin-bottom:1rem; }}
.crumbs a {{ color:var(--muted); }}
@@ -1290,21 +1280,23 @@ body {{ margin:0; font-family:"IBM Plex Sans","Noto Sans SC",sans-serif; backgro
.btn:hover {{ filter:brightness(1.05); }}
.btn-muted {{ background:#78716c; }}
.btn-ghost {{ background:transparent; color:var(--accent)!important; border:1px solid var(--line); }}
table.data {{ width:100%; border-collapse:collapse; background:#fff; border:1px solid var(--line); border-radius:6px; overflow:hidden; }}
table.data th,table.data td {{ border-bottom:1px solid var(--line); padding:.55rem .7rem; text-align:left; vertical-align:top; font-size:.92rem; }}
table.data th {{ background:#f5f5f4; font-weight:600; }}
.table-wrap {{ width:100%; overflow-x:auto; -webkit-overflow-scrolling:touch; border:1px solid var(--line); border-radius:6px; background:#fff; }}
table.data {{ width:100%; min-width:100%; border-collapse:collapse; background:#fff; }}
table.data th,table.data td {{ border-bottom:1px solid var(--line); padding:.55rem .7rem; text-align:left; vertical-align:top; font-size:.92rem; word-break:break-word; overflow-wrap:anywhere; white-space:pre-wrap; }}
table.data th {{ background:#f5f5f4; font-weight:600; white-space:nowrap; }}
table.data tr:last-child td {{ border-bottom:0; }}
table.data .actions {{ white-space:nowrap; }}
table.data .actions {{ white-space:nowrap; overflow-wrap:normal; word-break:normal; }}
.empty {{ background:#fff; border:1px dashed var(--line); border-radius:6px; padding:2rem 1.25rem; text-align:center; color:var(--muted); }}
.empty strong {{ display:block; color:var(--ink); margin-bottom:.35rem; font-size:1.05rem; }}
.flash {{ padding:.65rem .85rem; border-radius:4px; margin:0 0 1rem; }}
.flash.ok {{ background:#ecfdf5; color:var(--ok); border:1px solid #a7f3d0; }}
.flash.err {{ background:#fef2f2; color:var(--err); border:1px solid #fecaca; }}
.danger {{ color:var(--err); }}
.site-form {{ max-width:28rem; margin-top:.5rem; }}
.site-form {{ max-width:min(48rem,100%); width:100%; margin-top:.5rem; }}
.site-form form {{ display:grid; gap:.85rem; }}
.site-form label {{ display:grid; gap:.25rem; font-size:.9rem; }}
.site-form input,.site-form textarea {{ padding:.5rem .6rem; border:1px solid var(--line); border-radius:4px; font:inherit; background:#fff; }}
.site-form input,.site-form textarea {{ padding:.5rem .6rem; border:1px solid var(--line); border-radius:4px; font:inherit; background:#fff; width:100%; box-sizing:border-box; }}
.site-form textarea {{ min-height:8rem; resize:vertical; field-sizing:content; }}
.site-form input[readonly] {{ background:#f5f5f4; color:var(--muted); }}
.site-form .err {{ color:var(--err); font-size:.85rem; }}
.site-form .actions {{ display:flex; gap:.75rem; align-items:center; flex-wrap:wrap; }}
@@ -1363,14 +1355,14 @@ async fn admin_home(
"<div class=\"empty\"><strong>No tables</strong>Initialize a table via <code>db.init</code> / <code>数据库.初始化</code>.</div>",
);
} else {
inner.push_str("<table class=\"data\"><thead><tr><th>Table</th><th></th></tr></thead><tbody>");
inner.push_str("<div class=\"table-wrap\"><table class=\"data\"><thead><tr><th>Table</th><th></th></tr></thead><tbody>");
for t in &tables {
inner.push_str(&format!(
"<tr><td><a href=\"/admin/{t}\">{t}</a></td><td class=\"actions\"><a class=\"btn\" href=\"/admin/{t}/new\">New</a></td></tr>",
t = esc(t)
));
}
inner.push_str("</tbody></table>");
inner.push_str("</tbody></table></div>");
}
Html(admin_shell(&st, "Admin", None, &inner)).into_response()
}
@@ -1433,7 +1425,7 @@ async fn admin_table(
esc(&table)
));
} else {
inner.push_str("<table class=\"data\"><thead><tr>");
inner.push_str("<div class=\"table-wrap\"><table class=\"data\"><thead><tr>");
for c in &cols {
inner.push_str(&format!("<th>{}</th>", esc(c)));
}
@@ -1450,7 +1442,8 @@ async fn admin_table(
other => other.to_string(),
})
.unwrap_or_default();
inner.push_str(&format!("<td>{}</td>", esc(&truncate_cell(&cell, 80))));
// Show full cell text; CSS wraps / table-wrap scrolls when needed.
inner.push_str(&format!("<td>{}</td>", esc(&cell)));
}
let id = m
.get("id")
@@ -1468,7 +1461,7 @@ async fn admin_table(
}
inner.push_str("</tr>");
}
inner.push_str("</tbody></table>");
inner.push_str("</tbody></table></div>");
}
Html(admin_shell(&st, &table, Some(&table), &inner)).into_response()
}
+238 -109
View File
@@ -310,13 +310,16 @@ pub fn normalize_slot(name: &str) -> String {
/// Style table → CSS text.
///
/// Three table shapes are supported:
/// Table shapes:
/// 1. Rule rows `|媒体|选择器|属性|值|` — rows grouped by `媒体` emit
/// `@media { … }` blocks; rows sharing a selector are merged into one rule.
/// 2. Rule rows `|选择器|属性|值|` — each row emits `selector { prop: value; }`,
/// rows sharing a selector are merged into one rule. `selector` may be any
/// CSS selector (`aside.side`, `ul.side-nav a:hover`).
/// 3. Plain property rows `|属性|值|` — emitted as `.name { prop: value; }`.
/// 4. **`@keyframes`** — selector `@keyframes name` (optional stop in the
/// selector: `@keyframes name from`) or stop in the `属性` column:
/// `|@keyframes fade|from|opacity: 0|` → nested keyframe rules.
///
/// Examples (rule shape):
/// ```text
@@ -327,8 +330,9 @@ pub fn normalize_slot(name: &str) -> String {
/// | 选择器 | 属性 | 值 |
/// |--------|------|-----|
/// | aside.side | padding | 2rem 1.25rem |
/// | aside.side | background | #f5f5f4 |
/// | ul.side-nav a:hover | color | var(--accent) |
/// | @keyframes pulse | 0% | opacity: 0 |
/// | @keyframes pulse | 100% | opacity: 1 |
/// | @keyframes pulse from | opacity | 0 |
/// ```
pub fn as_css_named(name: &str, table: &Value) -> String {
let name = normalize_ref(name);
@@ -338,9 +342,6 @@ pub fn as_css_named(name: &str, table: &Value) -> String {
let mut out = String::new();
match table {
Value::Object(m) => {
// Column-first table object: `{选择器:[…], 属性:[…], 值:[…], 媒体:[…]}`
// (how GFM tables reach the plugin). Row-major maps (one rule per map)
// are handled too: if 选择器 is a scalar, treat it as a single row.
let sels = pick(m, SEL_KEYS).map(as_str_list).unwrap_or_default();
let props = pick(m, PROP_KEYS).map(as_str_list).unwrap_or_default();
let vals = pick(m, VAL_KEYS).map(as_str_list).unwrap_or_default();
@@ -359,117 +360,201 @@ pub fn as_css_named(name: &str, table: &Value) -> String {
)
})
.collect();
// Group by media then selector; or plain `.name { … }` when no selectors.
let mut by_media: Vec<(String, Vec<(String, Vec<String>)>)> = Vec::new();
let mut plain: Vec<String> = Vec::new();
for (media, sel, p, v) in rows {
if p.is_empty() {
continue;
}
let decl = format!(" {p}: {v};");
if !media.is_empty() {
let group = match by_media.iter_mut().find(|(mq, _)| *mq == media) {
Some((_, g)) => g,
None => {
by_media.push((media.clone(), Vec::new()));
let (_, g) = by_media.last_mut().unwrap();
g
}
};
push_rule(group, &sel, decl);
} else if !sel.is_empty() {
let group = match by_media.iter_mut().find(|(mq, _)| mq.is_empty()) {
Some((_, g)) => g,
None => {
by_media.push((String::new(), Vec::new()));
let (_, g) = by_media.last_mut().unwrap();
g
}
};
push_rule(group, &sel, decl);
} else {
plain.push(decl);
}
}
for (media, rules) in by_media {
if media.is_empty() {
for (sel, decls) in rules {
out.push_str(&format!("{} {{\n{}\n}}\n", sel, decls.join("\n")));
}
} else {
let inner = rules
.iter()
.map(|(sel, decls)| format!("{} {{\n{}\n}}", sel, decls.join("\n")))
.collect::<Vec<_>>()
.join("\n");
out.push_str(&format!("@media {} {{\n{}\n}}\n", media, inner));
}
}
if !plain.is_empty() {
out.push_str(&format!(".{} {{\n{}\n}}\n", name, plain.join("\n")));
}
emit_css_rows(&rows, &name, &mut out);
}
Value::Array(rows) => {
// Group rule rows by media query and selector; plain rows as `.name { … }`.
let mut by_media: Vec<(String, Vec<(String, Vec<String>)>)> = Vec::new();
let mut plain: Vec<String> = Vec::new();
for row in rows {
let Some(m) = row.as_object() else { continue };
let media = pick(m, MEDIA_KEYS).map(cell_str).unwrap_or_default();
let sel = pick(m, SEL_KEYS).map(cell_str).unwrap_or_default();
let p = pick(m, PROP_KEYS).map(cell_str).unwrap_or_default();
let v = pick(m, VAL_KEYS).map(cell_str).unwrap_or_default();
if p.is_empty() {
continue;
}
let decl = format!(" {p}: {v};");
if !media.is_empty() {
let group = match by_media.iter_mut().find(|(mq, _)| *mq == media) {
Some((_, g)) => g,
None => {
by_media.push((media.clone(), Vec::new()));
let (_, g) = by_media.last_mut().unwrap();
g
}
};
push_rule(group, &sel, decl);
} else if !sel.is_empty() {
let group = match by_media.iter_mut().find(|(mq, _)| mq.is_empty()) {
Some((_, g)) => g,
None => {
by_media.push((String::new(), Vec::new()));
let (_, g) = by_media.last_mut().unwrap();
g
}
};
push_rule(group, &sel, decl);
} else {
plain.push(decl);
}
}
for (media, rules) in by_media {
if media.is_empty() {
for (sel, decls) in rules {
out.push_str(&format!("{} {{\n{}\n}}\n", sel, decls.join("\n")));
}
} else {
let inner = rules
.iter()
.map(|(sel, decls)| format!("{} {{\n{}\n}}", sel, decls.join("\n")))
.collect::<Vec<_>>()
.join("\n");
out.push_str(&format!("@media {} {{\n{}\n}}\n", media, inner));
}
}
if !plain.is_empty() {
out.push_str(&format!(".{} {{\n{}\n}}\n", name, plain.join("\n")));
}
let rows: Vec<(String, String, String, String)> = rows
.iter()
.filter_map(|row| {
let m = row.as_object()?;
Some((
pick(m, MEDIA_KEYS).map(cell_str).unwrap_or_default(),
pick(m, SEL_KEYS).map(cell_str).unwrap_or_default(),
pick(m, PROP_KEYS).map(cell_str).unwrap_or_default(),
pick(m, VAL_KEYS).map(cell_str).unwrap_or_default(),
))
})
.collect();
emit_css_rows(&rows, &name, &mut out);
}
_ => {}
}
out
}
/// Parse `@keyframes name` or `@keyframes name stop` from a selector cell.
fn parse_keyframes_sel(sel: &str) -> Option<(String, Option<String>)> {
let t = sel.trim();
if t.len() < 10 || !t[..10].eq_ignore_ascii_case("@keyframes") {
return None;
}
let rest = t[10..].trim();
if rest.is_empty() {
return None;
}
// First token = animation name; optional second = keyframe stop.
let mut parts = rest.split_whitespace();
let anim = parts.next()?.to_string();
let stop = parts.next().map(|s| s.to_string());
Some((anim, stop))
}
fn is_keyframe_stop(s: &str) -> bool {
let t = s.trim();
if t.is_empty() {
return false;
}
if t.eq_ignore_ascii_case("from") || t.eq_ignore_ascii_case("to") {
return true;
}
// 0%, 50%, 100.5%, etc.
let stripped = t.trim_end_matches('%');
!stripped.is_empty()
&& stripped
.chars()
.all(|c| c.is_ascii_digit() || c == '.')
&& t.ends_with('%')
}
fn keyframe_decl_lines(css_prop: &str, value: &str) -> Vec<String> {
// Value may be a full declaration (`opacity: 0`) or bare value when the
// CSS property lived in the selector form `@keyframes name from` + 属性.
let v = value.trim().trim_end_matches(';').trim();
if v.is_empty() {
return Vec::new();
}
if v.contains(':') {
v.split(';')
.map(|p| p.trim())
.filter(|p| !p.is_empty())
.map(|p| format!(" {p};"))
.collect()
} else if !css_prop.is_empty() && !is_keyframe_stop(css_prop) {
// `@keyframes name from` + 属性=opacity + 值=0
vec![format!(" {css_prop}: {v};")]
} else {
// Bare value — prefer `opacity: 0` in the 值 column.
vec![format!(" {v};")]
}
}
fn push_keyframe(
groups: &mut Vec<(String, Vec<(String, Vec<String>)>)>,
anim: &str,
stop: &str,
decls: Vec<String>,
) {
if anim.is_empty() || stop.is_empty() || decls.is_empty() {
return;
}
let anim_group = match groups.iter_mut().find(|(n, _)| n == anim) {
Some((_, g)) => g,
None => {
groups.push((anim.to_string(), Vec::new()));
&mut groups.last_mut().unwrap().1
}
};
match anim_group.iter_mut().find(|(s, _)| s == stop) {
Some((_, d)) => d.extend(decls),
None => anim_group.push((stop.to_string(), decls)),
}
}
fn emit_css_rows(rows: &[(String, String, String, String)], class_name: &str, out: &mut String) {
let mut by_media: Vec<(String, Vec<(String, Vec<String>)>)> = Vec::new();
let mut by_keyframes: Vec<(String, Vec<(String, Vec<String>)>)> = Vec::new();
let mut plain: Vec<String> = Vec::new();
for (media, sel, p, v) in rows {
let media = media.trim();
let sel = sel.trim();
let p = p.trim();
let v = v.trim();
if let Some((anim, stop_in_sel)) = parse_keyframes_sel(sel) {
let stop_from_sel = stop_in_sel.is_some();
let (stop, prop_for_decl) = match stop_in_sel {
Some(s) => (s, p.to_string()),
None => {
// 属性 = keyframe stop (from / to / N%); 值 = declaration(s)
if !is_keyframe_stop(p) {
continue;
}
(p.to_string(), String::new())
}
};
let decls = if stop_from_sel {
keyframe_decl_lines(&prop_for_decl, v)
} else {
keyframe_decl_lines("", v)
};
let decls = if decls.is_empty() && !v.is_empty() && !prop_for_decl.is_empty() {
keyframe_decl_lines(&prop_for_decl, v)
} else {
decls
};
push_keyframe(&mut by_keyframes, &anim, &stop, decls);
continue;
}
if p.is_empty() {
continue;
}
let decl = format!(" {p}: {v};");
if !media.is_empty() {
let group = match by_media.iter_mut().find(|(mq, _)| *mq == media) {
Some((_, g)) => g,
None => {
by_media.push((media.to_string(), Vec::new()));
let (_, g) = by_media.last_mut().unwrap();
g
}
};
push_rule(group, sel, decl);
} else if !sel.is_empty() {
let group = match by_media.iter_mut().find(|(mq, _)| mq.is_empty()) {
Some((_, g)) => g,
None => {
by_media.push((String::new(), Vec::new()));
let (_, g) = by_media.last_mut().unwrap();
g
}
};
push_rule(group, sel, decl);
} else {
plain.push(decl);
}
}
for (media, rules) in by_media {
if media.is_empty() {
for (sel, decls) in rules {
out.push_str(&format!("{} {{\n{}\n}}\n", sel, decls.join("\n")));
}
} else {
let inner = rules
.iter()
.map(|(sel, decls)| format!("{} {{\n{}\n}}", sel, decls.join("\n")))
.collect::<Vec<_>>()
.join("\n");
out.push_str(&format!("@media {} {{\n{}\n}}\n", media, inner));
}
}
for (anim, stops) in by_keyframes {
out.push_str(&format!("@keyframes {} {{\n", anim));
for (stop, decls) in stops {
out.push_str(&format!(" {} {{\n", stop));
out.push_str(&decls.join("\n"));
out.push('\n');
out.push_str(" }\n");
}
out.push_str("}\n");
}
if !plain.is_empty() {
out.push_str(&format!(".{} {{\n{}\n}}\n", class_name, plain.join("\n")));
}
}
/// Push `decl` under `sel` into a `(selector, declarations)` group list,
/// merging declarations when the selector already exists.
fn push_rule(groups: &mut Vec<(String, Vec<String>)>, sel: &str, decl: String) {
@@ -614,3 +699,47 @@ fn meta_text(v: &Value) -> String {
other => other.to_string(),
}
}
#[cfg(test)]
mod css_tests {
use super::*;
use serde_json::json;
#[test]
fn keyframes_stop_in_prop() {
let t = json!([
{"选择器": "@keyframes pulse", "属性": "0%", "值": "opacity: 0"},
{"选择器": "@keyframes pulse", "属性": "100%", "值": "opacity: 1"},
]);
let css = as_css_named("anim", &t);
assert!(css.contains("@keyframes pulse {"), "{css}");
assert!(css.contains("0% {"), "{css}");
assert!(css.contains("opacity: 0;"), "{css}");
assert!(css.contains("100% {"), "{css}");
assert!(!css.contains("0%: opacity"), "{css}");
}
#[test]
fn keyframes_stop_in_selector() {
let t = json!([
{"选择器": "@keyframes fade from", "属性": "opacity", "值": "0"},
{"选择器": "@keyframes fade to", "属性": "opacity", "值": "1"},
]);
let css = as_css_named("anim", &t);
assert!(css.contains("@keyframes fade {"), "{css}");
assert!(css.contains("from {"), "{css}");
assert!(css.contains("opacity: 0;"), "{css}");
assert!(css.contains("to {"), "{css}");
}
#[test]
fn media_still_works() {
let t = json!([
{"媒体": "(max-width: 800px)", "选择器": ".x", "属性": "color", "值": "red"},
]);
let css = as_css_named("x", &t);
assert!(css.contains("@media (max-width: 800px)"), "{css}");
assert!(css.contains(".x {"), "{css}");
assert!(css.contains("color: red;"), "{css}");
}
}
+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 complete** (middleware, CRUD+FTS, security, SEO/RSS, upload/gallery, RBAC, sitemap). Design: doc/design/ext-web.md · capabilities: doc/design/web-net-capabilities.md · example: examples/marqdo-blog/
ext/web — HTTP / SQLite·Postgres site helpers + native plugin. **W0–W7 + P3 + W8**. **Browser embed (routes D/E/F, v0.3.3)**: `web.client_embed` auto-mounts WASM — zero author JS; `lib/browser` + GFM tables; build with `marqdo wasm build`; examples: browser-hello · browser-app · browser-media · web-client-site. Design: doc/design/ext-web.md · WASM: doc/adr/0002-browser-marqdo-wasm.md · roadmaps D/E/F.
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 站点助手 + 原生插件。设计:doc/design/ext-web.md
ext/web(网页)— HTTP / SQLite 站点助手 + 原生插件。**W0–W7 + P3 + W8**。**浏览器挂载(路线 D/E/F,v0.3.3)**:`网页.客户端挂载` / `web.client_embed` 自动 mount(作者零业务 JS);`lib/浏览器` + GFM;先 `marqdo wasm build`;示例 examples/browser-hello/ · examples/browser-app/ · examples/browser-media/ · examples/web-client-site/。设计:doc/design/ext-web.md · WASM:doc/adr/0002-browser-marqdo-wasm.md · 路线 D/E/F:doc/roadmap/browser-wasm-*.md
ext/quantum(量子)— 电路、绘图、噪声、公式矩阵自定义门、Q7 密度/高级图、Q8 主题 SVG(`主题=dark|light|bw`)。设计:doc/design/ext-quantum.md · doc/design/ext-quantum-viz-style.md
+15 -4
View File
@@ -16,6 +16,10 @@ Marqdo = **Markdown markers as syntax**. A `.mq.md` file is both documentation a
Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.md`. Deeper tables: [reference.md](reference.md). Copy-paste patterns: [examples.md](examples.md).
**Authoring / library craft** (GFM-first, no json glue, how to develop Marqdo): use **[`.cursor/skills/marqdo-dev/SKILL.md`](../../.cursor/skills/marqdo-dev/SKILL.md)** whenever writing or refactoring `.mq.md`, `lib/*`, or `ext/*`.
**Product release** (tag, CHANGELOG, README, public docs, VSIX, GitHub assets): use [`.cursor/skills/marqdo-release/SKILL.md`](../../.cursor/skills/marqdo-release/SKILL.md) — detect latest version, **ask the user for the next SemVer**, then follow that playbook. Do not invent a version number.
## Hard rules (do not violate)
1. **File suffix** must be `.mq.md` (never plain `.md` for executable sources).
@@ -24,9 +28,12 @@ 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/E/F):** client logic is Marqdo on WASM; official bridge is host glue and **may** implement lists, routing, storage, WebSocket, canvas, file read, observers — authors **must not hand-write business JS**. Use `web.client_embed` / `data-mq-source-url` auto-mount. Client effects: prefer **GFM tables + `lib/browser`** ([`.cursor/skills/marqdo-dev/SKILL.md`](../../.cursor/skills/marqdo-dev/SKILL.md)).
11. **Code-as-documentation / no bag glue:** Prefer **GFM tables** for maps, lists, wire, commands. Prefer **`table.put` / named helpers** over `json.set` / `json.append` chains. `lib/json` is for parse/stringify/quote only — not a dict builder. Unreadable json pipelines are a style bug.
## Markup → meaning (v0.2)
@@ -172,11 +179,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_*` → `app` + `static` / `listen`. Client: `marqdo wasm build -o static` + `web.client_embed source="/static/client.mq.md"` — **no author JS**; bridge may implement rich host effects ([browser-wasm-e.md](../../doc/roadmap/browser-wasm-e.md) · [browser-app](../../examples/browser-app/)).
**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).
@@ -225,7 +232,9 @@ Design: [ext-quantum.md](../../doc/design/ext-quantum.md) · Q7: [ext-quantum-q7
| Forgetting `---` after nested `##` helper | Add `---` / `***` / `****` |
| Import `lib/text` then call bare `split` | `> text.split …` (qualified) |
| Import `lib/text` then call `拆分` | Match file language (`text.split`, not 文本) |
| `json.set` / `json.append` to build maps or lists | GFM tables; sparse `table.put`; named helpers (`browser.*`, `web.*`) |
| `json.set` to build page parts | GFM tables + `page.compose_*` / `web.page` methods |
| Import `json` for every browser handler | `import browser:lib/browser.mq.md` + tables ([`.cursor/skills/marqdo-dev/SKILL.md`](../../.cursor/skills/marqdo-dev/SKILL.md)) |
| Mix `web.page` and `网页.页面` in one file | One import language per `.mq.md` |
| Call `host_web_*` from `ext/web` | Use `# app` / `# db` methods; plugin ABI only |
| Call `host_*` from `ext/quantum` | Use `# circuit` / `# density` methods; plugin ABI only |
@@ -241,6 +250,8 @@ Design: [ext-quantum.md](../../doc/design/ext-quantum.md) · Q7: [ext-quantum-q7
- [ ] `# main` exists when the file is an entry program
- [ ] Nested functions ended with `---` / `***` / `****` when needed
- [ ] Imports and call names share the same language file
- [ ] Data shaped as **GFM tables** (or short helpers) — no `json.set` / `json.append` glue
- [ ] Web sites: tables + web classes only (no JSON glue); `data/` gitignored
- [ ] Browser client: `lib/browser` + tables when returning effects
- [ ] Quantum draw: quote `kind=` / `theme=`; rebuild plugin → `ext add quantum` before view
- [ ] `marqdo run` succeeds (or errors addressed)
+26
View File
@@ -78,6 +78,7 @@ Greeting via a nested function:
> print text=`果`
```
## 6b. Map table + footnote get
```markdown
@@ -109,6 +110,31 @@ Row-oriented records (SQL-like): first header `@` / `行` / `row` → list of ma
*名 = 订单[^1][^品名]*
```
## 6c. Browser effects — tables + lib/browser (not json.set)
```markdown
---
import browser:lib/browser.mq.md
---
# main
`wire` =
| @ | 选择器 | 事件 | 调用 |
|---|--------|------|------|
| 1 | "#bump" | click | bump |
**`wire`**
## bump
*`count` = count + 1*
*`label` = > str count*
**> browser.set_text sel="#count" text=label**
```
Do **not** build effect maps with `json.set` chains. See [marqdo-dev](../marqdo-dev/SKILL.md).
## 7. Import text stdlib
```markdown
+2 -1
View File
@@ -44,12 +44,13 @@ Import one file; use **that** file’s function names.
|-----------|-----------|-------------------------|
| `lib/text.mq.md` | `lib/文本.mq.md` | text helpers / 去空白·拆分·拼接… |
| `lib/table.mq.md` | `lib/表.mq.md` | `put`/`改` + list/map(见 `doc/design/stdlib-table.md`) |
| `lib/browser.mq.md` | `lib/浏览器.mq.md` | WASM client effect helpers(GFM + `set_text`/`canvas`/…;见 marqdo-dev) |
| `lib/fs.mq.md` | `lib/文件.mq.md` | filesystem |
| `lib/sys.mq.md` | `lib/系统.mq.md` | process / cwd / load_dotenv |
| `lib/plugin.mq.md` | `lib/插件.mq.md` | load native ABI plugins (`doc/design/ext-abi.md`) |
| `lib/time.mq.md` | `lib/时间.mq.md` | time/format |
| `lib/net.mq.md` | `lib/网络.mq.md` | HTTP(S) helpers (+ optional headers) |
| `lib/json.mq.md` | (see design) | JSON (+ `quote`) |
| `lib/json.mq.md` | (see design) | **parse / stringify / quote only** — not a dict builder |
| `lib/math.mq.md` | `lib/数学.mq.md` | num, trig, random, formula, plot |
| `lib/foreign.mq.md` | `lib/外联.mq.md` | run foreign fenced blocks |
| `ext/llm.mq.md` | `ext/大模型.mq.md` | `# llm` / `# 大模型` object + chat methods |
+152
View File
@@ -0,0 +1,152 @@
//! In-memory browser / WASM session: boot `# main`, then call handlers with shared entry env.
use anyhow::{bail, Result};
use crate::ast::Module;
use crate::host::json::{json_to_value, value_to_json};
use crate::host::{HostCaps, HostContext};
use crate::interp::Interpreter;
use crate::load::load_module_from_source;
use crate::value::Value;
use crate::Backend;
/// Persistent Marqdo program for the browser host bridge.
///
/// Session calls (`call`) use the **tree** interpreter so entry bindings persist
/// across handlers (C3). One-shot [`crate::run_source`] may still use bytecode.
pub struct BrowserSession {
module: Module,
interp: Interpreter,
}
impl BrowserSession {
/// Parse source, run `# main`, keep entry bindings for later [`Self::call`].
pub fn boot(source: &str) -> Result<(Self, Value)> {
Self::boot_with(source, Backend::Tree)
}
/// Like [`Self::boot`]. `Backend::Bytecode` is rejected for sessions (no shared entry env yet).
pub fn boot_with(source: &str, backend: Backend) -> Result<(Self, Value)> {
if source.trim().is_empty() {
bail!("source is empty");
}
if backend != Backend::Tree {
bail!("browser session requires tree backend (bytecode has no entry-env invoke yet)");
}
let module = load_module_from_source(source)?;
let caps = HostCaps {
fs_write: false,
exec: false,
net: false,
plugin: false,
};
let mut host = HostContext::for_capture(None, caps);
host.set_entry_source(None, source);
host.sleep_limit_ms = Some(0);
let mut interp = Interpreter::with_capture(None, false).with_host(host);
let value = interp.run_module(&module)?;
Ok((Self { module, interp }, value))
}
/// Invoke `name` with optional JSON object of named args; updates entry bindings.
pub fn call(&mut self, name: &str, args_json: &str) -> Result<Value> {
let args = parse_named_args(args_json)?;
self.interp.captured_stdout.clear();
self.interp.invoke_in_entry(&self.module, name, &args)
}
pub fn take_stdout(&mut self) -> String {
std::mem::take(&mut self.interp.captured_stdout)
}
}
fn parse_named_args(args_json: &str) -> Result<Vec<(String, Value)>> {
let t = args_json.trim();
if t.is_empty() || t == "{}" || t == "null" {
return Ok(Vec::new());
}
let v: serde_json::Value =
serde_json::from_str(t).map_err(|e| anyhow::anyhow!("call args json: {e}"))?;
match v {
serde_json::Value::Object(map) => {
let mut out = Vec::new();
for (k, j) in map {
out.push((k, json_to_value(&j).map_err(|e| anyhow::anyhow!(e))?));
}
Ok(out)
}
serde_json::Value::Null => Ok(Vec::new()),
_ => bail!("call args must be a JSON object"),
}
}
/// Serialize a runtime [`Value`] to JSON (for WASM bridge responses).
pub fn value_as_json(v: &Value) -> Result<serde_json::Value, String> {
value_to_json(v)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn boot_and_call_share_count() {
let src = r##"---
import json:lib/json.mq.md
---
# main
*`count` = 0*
`wire` =
| @ | 选择器 | 事件 | 调用 |
|---|--------|------|------|
| 1 | "#btn" | click | bump |
**`wire`**
## bump
*`count` = count + 1*
*`label` = > str count*
*`patch` = > json.set map=None key="#out" value=label*
**> json.set map=None key="set_text" value=patch**
"##;
let (mut sess, wire) = BrowserSession::boot(src).expect("boot");
assert!(matches!(wire, Value::List(_)), "wire={wire:?}");
let _v1 = sess.call("bump", "{}").expect("call1");
let v2 = sess.call("bump", "{}").expect("call2");
let j2 = value_as_json(&v2).unwrap();
assert_eq!(j2["set_text"]["#out"], "2");
}
#[test]
fn fetch_mq_load_returns_fetch_effect() {
let src = std::fs::read_to_string("examples/browser-hello/fetch.mq.md")
.expect("fetch.mq.md");
let (mut sess, wire) = BrowserSession::boot(&src).expect("boot");
assert!(matches!(wire, Value::List(_)));
let v = sess.call("load", "{}").expect("load");
let j = value_as_json(&v).unwrap();
assert_eq!(j["set_text"]["#status"], "loading…");
assert_eq!(j["fetch"]["then"], "on_uuid");
assert!(j["fetch"]["url"].as_str().unwrap().contains("httpbin"));
let done = sess
.call(
"on_uuid",
r#"{"ok":true,"status":200,"body":"{\"uuid\":\"x\"}"}"#,
)
.expect("on_uuid");
let jd = value_as_json(&done).unwrap();
assert!(jd["set_text"]["#status"].as_str().unwrap().contains("uuid"));
}
#[test]
fn session_rejects_bytecode_backend() {
let err = BrowserSession::boot_with("# main\n\n> print text=x\n", Backend::Bytecode)
.err()
.expect("err");
assert!(err.to_string().contains("tree backend"));
}
}
+54 -4
View File
@@ -194,6 +194,11 @@ fn find_native_plugin(short: &str) -> Result<PathBuf> {
let base = PathBuf::from(h);
candidates.push(base.join("native").join(&name));
candidates.push(base.join(&name));
// MARQDO_EXT_SOURCE often points at repo `ext/`; native libs live in sibling target/.
if let Some(repo) = base.parent() {
candidates.push(repo.join("target").join("debug").join(&name));
candidates.push(repo.join("target").join("release").join(&name));
}
}
// Honor CARGO_TARGET_DIR (sandbox / custom target roots) before cwd/target.
if let Ok(td) = env::var("CARGO_TARGET_DIR") {
@@ -205,6 +210,15 @@ fn find_native_plugin(short: &str) -> Result<PathBuf> {
candidates.push(cwd.join("target").join("debug").join(&name));
candidates.push(cwd.join("target").join("release").join(&name));
candidates.push(cwd.join("ext").join("native").join(&name));
// Walk up looking for a Cargo workspace target/ (run from a subdir).
let mut dir = cwd.clone();
for _ in 0..6 {
candidates.push(dir.join("target").join("debug").join(&name));
candidates.push(dir.join("target").join("release").join(&name));
if !dir.pop() {
break;
}
}
}
if let Ok(exe) = env::current_exe() {
if let Some(dir) = exe.parent() {
@@ -213,6 +227,7 @@ fn find_native_plugin(short: &str) -> Result<PathBuf> {
candidates.push(dir.join(&name));
// target/debug/deps → target/debug
candidates.push(dir.join("..").join(&name));
candidates.push(dir.join("..").join("release").join(&name));
}
}
for p in &candidates {
@@ -221,8 +236,35 @@ fn find_native_plugin(short: &str) -> Result<PathBuf> {
}
}
bail!(
"cannot find native plugin `{name}` (run `cargo build -p marqdo_plugin_{short}`, or `marqdo ext add {short}`, or set {env_key})"
"cannot find native plugin `{name}` (run `cargo build -p marqdo_plugin_{short}`, or set {env_key})"
)
}
/// Locate a built native plugin, or `cargo build -p …` once then look again.
fn ensure_native_plugin(crate_name: &str) -> Result<PathBuf> {
let short = native_short_name(crate_name);
if let Ok(p) = find_native_plugin(short) {
return Ok(p);
}
println!(
"native plugin for `{short}` not found; building `{crate_name}` (debug)…"
);
let status = std::process::Command::new("cargo")
.args(["build", "-p", crate_name])
.status()
.with_context(|| format!("spawn cargo build -p {crate_name}"))?;
if !status.success() {
bail!(
"cargo build -p {crate_name} failed (status {status}); build the plugin then re-run `marqdo ext add {short}`"
);
}
find_native_plugin(short).with_context(|| {
format!(
"built `{crate_name}` but still cannot find {}; set {} to the .so/.dll path",
native_lib_filename(short),
native_env_var(short)
)
})
}
pub fn add_ext(id: &str) -> Result<()> {
@@ -240,6 +282,14 @@ pub fn add_ext(id: &str) -> Result<()> {
fs::create_dir_all(&root)
.with_context(|| format!("create install root {}", root.display()))?;
// Preflight native binary *before* copying .mq.md so a missing .so does not
// leave a half-installed tree that fails at `plugin.native_path` / load time.
let native_src = if let Some(crate_name) = pkg.native_crate {
Some(ensure_native_plugin(crate_name)?)
} else {
None
};
for f in pkg.mq_files {
let src = find_source_file(f)?;
let dest = root.join(f);
@@ -252,10 +302,9 @@ pub fn add_ext(id: &str) -> Result<()> {
println!("installed {}", dest.display());
}
if let Some(crate_name) = pkg.native_crate {
if let (Some(crate_name), Some(src)) = (pkg.native_crate, native_src) {
let short = native_short_name(crate_name);
let lib_name = native_lib_filename(short);
let src = find_native_plugin(short)?;
let native_dir = root.join("native");
fs::create_dir_all(&native_dir)?;
let dest = native_dir.join(&lib_name);
@@ -270,7 +319,8 @@ pub fn add_ext(id: &str) -> Result<()> {
fs::write(&hint, abs.to_string_lossy().as_bytes())?;
println!("wrote {}", hint.display());
println!(
"hint: import works via install root; set {}={} if load_native needs it",
"hint: `plugin.native_path name={short}` resolves via {}; or set {}={}",
dest.display(),
native_env_var(short),
abs.display()
);
+223 -51
View File
@@ -2,7 +2,11 @@
use std::collections::HashMap;
use crate::host::{foreign, fs, json, math, net, plugin, subtask, sys, time, writeback, HostContext};
use crate::host::{fs, json, math, net, sys, time, writeback, HostContext};
#[cfg(feature = "exec-host")]
use crate::host::{foreign, subtask};
#[cfg(feature = "plugin-host")]
use crate::host::plugin;
use crate::value::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -648,22 +652,52 @@ pub fn call_host(
HostFn::JsonGet => json::get(require(bound, "value")?, require(bound, "key")?),
HostFn::JsonKeys => json::keys(require(bound, "value")?),
HostFn::JsonQuote => json::quote(require(bound, "text")?),
HostFn::HttpGet => net::http_get(ctx, require(bound, "url")?, bound.get("headers")),
HostFn::HttpPost => net::http_post(
ctx,
require(bound, "url")?,
require(bound, "body")?,
bound.get("content_type"),
bound.get("headers"),
),
HostFn::HttpPostSse => net::http_post_sse(
ctx,
require(bound, "url")?,
require(bound, "body")?,
bound.get("content_type"),
bound.get("headers"),
bound.get("echo"),
),
HostFn::HttpGet => {
#[cfg(feature = "net-host")]
{
net::http_get(ctx, require(bound, "url")?, bound.get("headers"))
}
#[cfg(not(feature = "net-host"))]
{
let _ = (ctx, bound);
Err("http_get unavailable in browser wasm".into())
}
}
HostFn::HttpPost => {
#[cfg(feature = "net-host")]
{
net::http_post(
ctx,
require(bound, "url")?,
require(bound, "body")?,
bound.get("content_type"),
bound.get("headers"),
)
}
#[cfg(not(feature = "net-host"))]
{
let _ = (ctx, bound);
Err("http_post unavailable in browser wasm".into())
}
}
HostFn::HttpPostSse => {
#[cfg(feature = "net-host")]
{
net::http_post_sse(
ctx,
require(bound, "url")?,
require(bound, "body")?,
bound.get("content_type"),
bound.get("headers"),
bound.get("echo"),
)
}
#[cfg(not(feature = "net-host"))]
{
let _ = (ctx, bound);
Err("http_post_sse unavailable in browser wasm".into())
}
}
HostFn::OpenAiSseParse => {
net::openai_sse_parse(require(bound, "text")?, bound.get("echo"))
}
@@ -671,14 +705,24 @@ pub fn call_host(
crate::host::event_bus::publish(require(bound, "event")?);
Ok(Value::Bool(true))
}
HostFn::HttpRequest => net::http_request(
ctx,
require(bound, "method")?,
require(bound, "url")?,
bound.get("body"),
bound.get("content_type"),
bound.get("headers"),
),
HostFn::HttpRequest => {
#[cfg(feature = "net-host")]
{
net::http_request(
ctx,
require(bound, "method")?,
require(bound, "url")?,
bound.get("body"),
bound.get("content_type"),
bound.get("headers"),
)
}
#[cfg(not(feature = "net-host"))]
{
let _ = (ctx, bound);
Err("http_request unavailable in browser wasm".into())
}
}
HostFn::UrlEncode => net::url_encode(require(bound, "text")?),
HostFn::Pi => math::pi(),
HostFn::EConst => math::e_const(),
@@ -756,33 +800,111 @@ pub fn call_host(
bound.get("path"),
bound.get("grid"),
),
HostFn::ForeignSetCmd => foreign::set_cmd(
ctx,
require(bound, "lang")?,
require(bound, "cmd")?,
bound.get("args"),
),
HostFn::ForeignRun => foreign::run(ctx, require(bound, "code")?, bound.get("stdin")),
HostFn::ForeignRunLang => foreign::run_lang(
ctx,
require(bound, "lang")?,
require(bound, "source")?,
bound.get("stdin"),
),
HostFn::ForeignLangs => foreign::langs(ctx),
HostFn::PluginLoad => plugin::load(ctx, require(bound, "path")?),
HostFn::PluginUnload => plugin::unload(ctx),
HostFn::PluginList => plugin::list(ctx),
HostFn::ForeignSetCmd => {
#[cfg(feature = "exec-host")]
{
foreign::set_cmd(
ctx,
require(bound, "lang")?,
require(bound, "cmd")?,
bound.get("args"),
)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignRun => {
#[cfg(feature = "exec-host")]
{
foreign::run(ctx, require(bound, "code")?, bound.get("stdin"))
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignRunLang => {
#[cfg(feature = "exec-host")]
{
foreign::run_lang(
ctx,
require(bound, "lang")?,
require(bound, "source")?,
bound.get("stdin"),
)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignLangs => {
#[cfg(feature = "exec-host")]
{
foreign::langs(ctx)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = ctx;
Ok(Value::List(Vec::new()))
}
}
HostFn::PluginLoad => {
#[cfg(feature = "plugin-host")]
{
plugin::load(ctx, require(bound, "path")?)
}
#[cfg(not(feature = "plugin-host"))]
{
let _ = (ctx, bound);
Err("plugin.load unavailable in browser wasm".into())
}
}
HostFn::PluginUnload => {
#[cfg(feature = "plugin-host")]
{
plugin::unload(ctx)
}
#[cfg(not(feature = "plugin-host"))]
{
let _ = ctx;
Err("plugin.unload unavailable in browser wasm".into())
}
}
HostFn::PluginList => {
#[cfg(feature = "plugin-host")]
{
plugin::list(ctx)
}
#[cfg(not(feature = "plugin-host"))]
{
let _ = ctx;
Ok(Value::List(Vec::new()))
}
}
HostFn::ExtNativePath => {
let name = require(bound, "name")?;
let s = match name {
Value::Text(t) => t.as_str(),
_ => return Err("name must be text".into()),
};
Ok(match crate::ext_cli::installed_native_path(s) {
Some(p) => Value::Text(p.to_string_lossy().into_owned()),
None => Value::None,
})
#[cfg(feature = "cli")]
{
Ok(match crate::ext_cli::installed_native_path(s) {
Some(p) => Value::Text(p.to_string_lossy().into_owned()),
None => Value::None,
})
}
#[cfg(not(feature = "cli"))]
{
let _ = s;
Ok(Value::None)
}
}
HostFn::MapSet => {
super::collection::map_set(require(bound, "map")?, require(bound, "key")?, require(bound, "value")?)
@@ -899,11 +1021,61 @@ pub fn call_host(
bound.get("line"),
)
}
HostFn::SubtaskSpawn => subtask::spawn(ctx, bound),
HostFn::SubtaskPoll => subtask::poll(ctx, require(bound, "id")?),
HostFn::SubtaskJoin => subtask::join(ctx, require(bound, "id")?),
HostFn::SubtaskKill => subtask::kill(ctx, require(bound, "id")?),
HostFn::SubtaskWaitAll => subtask::wait_all(ctx),
HostFn::SubtaskSpawn => {
#[cfg(feature = "exec-host")]
{
subtask::spawn(ctx, bound)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("subtask unavailable in browser wasm".into())
}
}
HostFn::SubtaskPoll => {
#[cfg(feature = "exec-host")]
{
subtask::poll(ctx, require(bound, "id")?)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("subtask unavailable in browser wasm".into())
}
}
HostFn::SubtaskJoin => {
#[cfg(feature = "exec-host")]
{
subtask::join(ctx, require(bound, "id")?)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("subtask unavailable in browser wasm".into())
}
}
HostFn::SubtaskKill => {
#[cfg(feature = "exec-host")]
{
subtask::kill(ctx, require(bound, "id")?)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("subtask unavailable in browser wasm".into())
}
}
HostFn::SubtaskWaitAll => {
#[cfg(feature = "exec-host")]
{
subtask::wait_all(ctx)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = ctx;
Err("subtask unavailable in browser wasm".into())
}
}
}
}
+10
View File
@@ -8,12 +8,21 @@ pub mod agent_rt;
pub mod collection;
mod dispatch;
pub mod event_bus;
#[cfg(feature = "exec-host")]
pub mod foreign;
mod fs;
pub(crate) mod json;
pub mod math;
mod net;
#[cfg(feature = "plugin-host")]
pub mod plugin;
#[cfg(not(feature = "plugin-host"))]
#[path = "plugin_stub.rs"]
pub mod plugin;
#[cfg(feature = "exec-host")]
pub mod subtask;
#[cfg(not(feature = "exec-host"))]
#[path = "subtask_stub.rs"]
pub mod subtask;
mod sys;
mod time;
@@ -80,6 +89,7 @@ pub struct HostContext {
/// Entry-file line of each active user call (for writeback anchoring).
pub call_site_lines: Vec<u32>,
/// Concurrent subtasks (`lib/subtask`): file / function / foreign.
#[cfg_attr(not(feature = "exec-host"), allow(dead_code))]
pub(crate) subtasks: HashMap<u64, subtask::Handle>,
pub subtask_seq: u64,
}
+14 -2
View File
@@ -1,10 +1,14 @@
//! HTTP host primitives (HTTP and HTTPS via ureq).
use std::io::{BufRead, BufReader, Write};
use std::io::Write;
#[cfg(feature = "net-host")]
use std::io::{BufRead, BufReader};
#[cfg(feature = "net-host")]
use std::time::Duration;
use crate::host::HostContext;
use crate::value::Value;
#[cfg(feature = "net-host")]
use crate::host::HostContext;
fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
match v {
@@ -13,6 +17,7 @@ fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
}
}
#[cfg(feature = "net-host")]
fn headers_from_value(headers: Option<&Value>) -> Result<Vec<(String, String)>, String> {
let Some(h) = headers else {
return Ok(Vec::new());
@@ -27,6 +32,7 @@ fn headers_from_value(headers: Option<&Value>) -> Result<Vec<(String, String)>,
}
}
#[cfg(feature = "net-host")]
fn http_exchange(
method: &str,
url: &str,
@@ -84,6 +90,7 @@ fn http_exchange(
}
}
#[cfg(feature = "net-host")]
fn response_map(status: u16, body: String) -> Value {
Value::Map(vec![
("status".into(), Value::Int(status as i64)),
@@ -91,6 +98,7 @@ fn response_map(status: u16, body: String) -> Value {
])
}
#[cfg(feature = "net-host")]
pub fn http_get(
ctx: &HostContext,
url: &Value,
@@ -105,6 +113,7 @@ pub fn http_get(
Ok(response_map(status, body))
}
#[cfg(feature = "net-host")]
pub fn http_post(
ctx: &HostContext,
url: &Value,
@@ -127,6 +136,7 @@ pub fn http_post(
}
/// Generic request: method + url + optional body / content_type / headers.
#[cfg(feature = "net-host")]
pub fn http_request(
ctx: &HostContext,
method: &Value,
@@ -630,6 +640,7 @@ pub fn openai_sse_parse(text: &Value, echo: Option<&Value>) -> Result<Value, Str
Ok(Value::List(openai_chat_sse_events(text, echo)?))
}
#[cfg(feature = "net-host")]
fn read_sse_body_to_events<R: BufRead>(
mut reader: R,
echo: bool,
@@ -755,6 +766,7 @@ fn read_sse_body_to_events<R: BufRead>(
}
/// POST and consume OpenAI-compatible SSE; return `{status, events}` list of stream maps.
#[cfg(feature = "net-host")]
pub fn http_post_sse(
ctx: &HostContext,
url: &Value,
+57
View File
@@ -0,0 +1,57 @@
//! Stub plugin surface when `plugin-host` is disabled (browser wasm).
use std::collections::HashMap;
use crate::host::HostContext;
use crate::value::Value;
pub const ABI_VERSION: u32 = 2;
pub const ABI_VERSION_MIN: u32 = 1;
/// Hook: resolve bare `lib.member` (unused without native plugins).
pub struct LibPathCall {
pub call: fn(*mut (), &str) -> Result<Value, String>,
pub data: *mut (),
}
pub fn with_lib_path_call<R>(_hook: LibPathCall, body: impl FnOnce() -> R) -> R {
body()
}
#[derive(Clone)]
pub struct RegisteredFn {
pub params: Vec<String>,
}
#[derive(Debug, Default, Clone)]
pub struct PluginState;
impl PluginState {
pub fn get(&self, _name: &str) -> Option<&RegisteredFn> {
None
}
pub fn list_names(&self) -> Vec<String> {
Vec::new()
}
}
pub fn load(_ctx: &mut HostContext, _path: &Value) -> Result<Value, String> {
Err("plugin.load unavailable in browser wasm".into())
}
pub fn unload(_ctx: &mut HostContext) -> Result<Value, String> {
Err("plugin.unload unavailable in browser wasm".into())
}
pub fn list(_ctx: &HostContext) -> Result<Value, String> {
Ok(Value::List(Vec::new()))
}
pub fn call_registered(
_ctx: &mut HostContext,
name: &str,
_bound: &HashMap<String, Value>,
) -> Result<Value, String> {
Err(format!("plugin `{name}` unavailable in browser wasm"))
}
+9
View File
@@ -0,0 +1,9 @@
//! Stub subtask surface when `exec-host` is disabled (browser wasm).
use crate::host::HostContext;
/// Placeholder handle type so `HostContext.subtasks` still type-checks.
#[derive(Debug)]
pub(crate) struct Handle;
pub fn kill_all(_ctx: &mut HostContext) {}
+17 -1
View File
@@ -1,5 +1,6 @@
//! System / process host primitives.
#[cfg(feature = "exec-host")]
use std::process::Command;
use crate::host::HostContext;
@@ -97,10 +98,24 @@ pub fn exit(ctx: &HostContext, code: &Value) -> Result<Value, String> {
if ctx.soft_side_effects {
return Err(format!("exit {c} (soft mode does not terminate process)"));
}
std::process::exit(c as i32);
#[cfg(target_arch = "wasm32")]
{
return Err(format!("exit {c} unavailable in browser wasm"));
}
#[cfg(not(target_arch = "wasm32"))]
{
std::process::exit(c as i32);
}
}
pub fn exec(ctx: &HostContext, cmd: &Value, args: Option<&Value>) -> Result<Value, String> {
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, cmd, args);
return Err("exec unavailable in browser wasm".into());
}
#[cfg(feature = "exec-host")]
{
if !ctx.allow_exec() {
return Err("exec denied by host policy".into());
}
@@ -123,6 +138,7 @@ pub fn exec(ctx: &HostContext, cmd: &Value, args: Option<&Value>) -> Result<Valu
.status()
.map_err(|e| format!("exec `{cmd}`: {e}"))?;
Ok(Value::Int(status.code().unwrap_or(1) as i64))
}
}
#[cfg(test)]
+37 -13
View File
@@ -1,7 +1,8 @@
//! Time host primitives.
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use std::time::Duration;
#[cfg(not(target_arch = "wasm32"))]
use std::time::{SystemTime, UNIX_EPOCH};
use chrono::{DateTime, NaiveDateTime, Utc};
@@ -9,19 +10,34 @@ use crate::host::HostContext;
use crate::value::Value;
pub fn now_unix() -> Result<Value, String> {
let secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| format!("now_unix: {e}"))?
.as_secs();
Ok(Value::Int(secs as i64))
#[cfg(target_arch = "wasm32")]
{
// No wall clock on wasm32-unknown-unknown without JS bridge (C4).
return Err("now_unix unavailable in browser wasm (no clock bridge yet)".into());
}
#[cfg(not(target_arch = "wasm32"))]
{
let secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| format!("now_unix: {e}"))?
.as_secs();
Ok(Value::Int(secs as i64))
}
}
pub fn now_ms() -> Result<Value, String> {
let ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| format!("now_ms: {e}"))?
.as_millis();
Ok(Value::Int(ms as i64))
#[cfg(target_arch = "wasm32")]
{
return Err("now_ms unavailable in browser wasm (no clock bridge yet)".into());
}
#[cfg(not(target_arch = "wasm32"))]
{
let ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| format!("now_ms: {e}"))?
.as_millis();
Ok(Value::Int(ms as i64))
}
}
fn as_i64(v: &Value, label: &str) -> Result<i64, String> {
@@ -65,7 +81,15 @@ pub fn sleep_ms(ctx: &HostContext, ms: &Value) -> Result<Value, String> {
}
}
if n > 0 {
thread::sleep(Duration::from_millis(n));
#[cfg(not(target_arch = "wasm32"))]
{
std::thread::sleep(Duration::from_millis(n));
}
#[cfg(target_arch = "wasm32")]
{
let _ = Duration::from_millis(n);
// Browser wasm has no blocking sleep; ignore (C0/C1).
}
}
Ok(Value::None)
}
+11 -8
View File
@@ -3,7 +3,9 @@
use std::collections::VecDeque;
use std::fs;
use std::io::{self, BufRead, Read, Write};
use std::io::{self, BufRead, Write};
#[cfg(all(unix, feature = "tty"))]
use std::io::Read;
use std::path::Path;
use anyhow::{Context, Result};
@@ -146,11 +148,11 @@ fn strip_block_indent(line: &str) -> String {
}
pub fn stdin_is_tty() -> bool {
#[cfg(unix)]
#[cfg(all(unix, feature = "tty"))]
{
unsafe { libc::isatty(libc::STDIN_FILENO) == 1 }
}
#[cfg(not(unix))]
#[cfg(not(all(unix, feature = "tty")))]
{
false
}
@@ -181,13 +183,13 @@ fn normalize_prompt(prompt: &str) -> String {
}
}
#[cfg(unix)]
#[cfg(all(unix, feature = "tty"))]
struct TermGuard {
fd: i32,
original: libc::termios,
}
#[cfg(unix)]
#[cfg(all(unix, feature = "tty"))]
impl TermGuard {
fn enter_cbreak() -> Result<Self> {
let fd = libc::STDIN_FILENO;
@@ -206,7 +208,7 @@ impl TermGuard {
}
}
#[cfg(unix)]
#[cfg(all(unix, feature = "tty"))]
impl Drop for TermGuard {
fn drop(&mut self) {
unsafe {
@@ -215,6 +217,7 @@ impl Drop for TermGuard {
}
}
#[cfg(all(unix, feature = "tty"))]
fn redraw_line(prompt: &str, buf: &str) -> Result<()> {
let mut out = io::stdout().lock();
// CR + clear whole line, then reprint (fixes CJK backspace display desync).
@@ -224,7 +227,7 @@ fn redraw_line(prompt: &str, buf: &str) -> Result<()> {
}
/// Interactive line editor: UTF-8 char backspace + full-line redraw.
#[cfg(unix)]
#[cfg(all(unix, feature = "tty"))]
fn read_stdin_line_interactive(prompt: &str) -> Result<String> {
let prompt = normalize_prompt(prompt);
let _guard = TermGuard::enter_cbreak()?;
@@ -290,7 +293,7 @@ fn read_stdin_line_interactive(prompt: &str) -> Result<String> {
}
}
#[cfg(not(unix))]
#[cfg(not(all(unix, feature = "tty")))]
fn read_stdin_line_interactive(prompt: &str) -> Result<String> {
let prompt = normalize_prompt(prompt);
print!("{prompt}");
+21
View File
@@ -151,6 +151,27 @@ impl Interpreter {
self.run_function(module, fun, Env::new(), args, false)
}
/// Call a function using (and updating) [`Self::entry_bindings`] from `# main`.
/// Used by browser WASM sessions so handlers share state with the entry object.
pub fn invoke_in_entry(
&mut self,
module: &Module,
name: &str,
args: &[(String, Value)],
) -> Result<Value> {
let fun = find_function_anywhere(module, name)
.ok_or_else(|| self.err(format!("unknown function `{name}`")))?;
let mut env = Env::new();
for (k, v) in &self.entry_bindings {
env.set(k.clone(), v.clone());
}
let prev = self.site_module;
self.site_module = Some(module as *const Module);
let result = self.run_function(module, fun, env, args, true);
self.site_module = prev;
result
}
pub fn run_module(&mut self, module: &Module) -> Result<Value> {
let prev = self.site_module;
self.site_module = Some(module as *const Module);
+86 -1
View File
@@ -5,13 +5,16 @@
pub mod aliases;
pub mod ast;
pub mod browser_session;
pub mod builtin;
pub mod bytecode;
pub mod capture;
#[cfg(feature = "cli")]
pub mod catalog;
pub mod debug;
pub mod diagnostics;
pub mod embedded_lib;
#[cfg(feature = "cli")]
pub mod ext_cli;
pub mod foreign;
pub mod formula;
@@ -23,8 +26,12 @@ pub mod lex;
pub mod load;
pub mod parse;
pub mod value;
#[cfg(feature = "net-host")]
pub mod version_check;
#[cfg(feature = "view")]
pub mod view;
#[cfg(feature = "cli")]
pub mod wasm_cli;
use std::path::Path;
@@ -36,7 +43,9 @@ use crate::bytecode::{compile_module, Vm};
use crate::capture::RunCapture;
use crate::interp::Interpreter;
use crate::lex::{classify_source, format_lines_dump};
use crate::load::load_module;
use crate::load::{load_module, load_module_from_source};
pub use browser_session::{value_as_json, BrowserSession};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Backend {
@@ -293,3 +302,79 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
}
}
}
/// Run source text in-memory (browser wasm / tests). Imports resolve via embedded `lib/` only.
pub fn run_source(source: &str, opts: &RunOptions) -> Result<RunCapture> {
if source.trim().is_empty() {
bail!("source is empty");
}
let stdin_lines = crate::input_feed::effective_stdin(source, &opts.stdin_lines);
let module = load_module_from_source(source)?;
match opts.backend {
Backend::Tree => {
let mut host = HostContext::for_capture(None, opts.host_caps());
host.set_entry_source(None, source);
host.argv = opts.argv.clone();
if let Some(root) = &opts.fs_root {
host.fs_root = Some(root.clone());
}
if let Some(lim) = opts.sleep_limit_ms {
host.sleep_limit_ms = Some(lim);
}
let mut interp = Interpreter::with_capture(None, false)
.with_stdin(stdin_lines)
.with_host(host);
let value = interp.run_module(&module)?;
let plots = interp.take_plots();
Ok(RunCapture {
stdout: interp.captured_stdout,
value,
plots,
bindings: interp.entry_bindings,
})
}
Backend::Bytecode => {
let program = compile_module(None, &module)?;
let mut host = HostContext::for_capture(None, opts.host_caps());
host.set_entry_source(None, source);
host.argv = opts.argv.clone();
if let Some(root) = &opts.fs_root {
host.fs_root = Some(root.clone());
}
if let Some(lim) = opts.sleep_limit_ms {
host.sleep_limit_ms = Some(lim);
}
let mut vm = Vm::with_capture(None)
.with_stdin(stdin_lines)
.with_host(host);
let value = vm.run(&program)?;
let plots = vm.take_plots();
Ok(RunCapture {
stdout: vm.captured_stdout,
value,
plots,
bindings: Default::default(),
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn run_source_hello() {
let cap = run_source("# main\n\n> print text=Hello World!\n", &RunOptions::default())
.expect("run_source");
assert_eq!(cap.stdout, "Hello World!\n");
}
#[test]
fn run_source_hello_bytecode() {
let mut opts = RunOptions::default();
opts.backend = Backend::Bytecode;
let cap = run_source("# main\n\n> print text=Hello World!\n", &opts).expect("bc");
assert_eq!(cap.stdout, "Hello World!\n");
}
}
+57 -8
View File
@@ -6,7 +6,7 @@ use std::path::{Path, PathBuf};
use anyhow::{bail, Context, Result};
use crate::ast::{Function, Module};
use crate::ast::Module;
use crate::diagnostics::Diagnostic;
use crate::embedded_lib;
use crate::parse::parse_source;
@@ -212,14 +212,63 @@ fn attach_path(path: &Path, err: anyhow::Error) -> anyhow::Error {
}
}
/// Kept for tests / tooling that expect a flat list (local tops only).
#[allow(dead_code)]
fn merge_top_level(into: &mut Vec<Function>, fun: Function) {
if let Some(existing) = into.iter_mut().find(|f| f.name == fun.name) {
*existing = fun;
} else {
into.push(fun);
/// Load a module from source text. Imports may only resolve to the embedded
/// `lib/…` stdlib (no filesystem / `ext/` for this MVP path).
pub fn load_module_from_source(source: &str) -> Result<Module> {
let mut visited = HashSet::new();
load_module_from_source_inner(source, "<memory>", &mut visited)
}
fn load_module_from_source_inner(
source: &str,
label: &str,
visited: &mut HashSet<PathBuf>,
) -> Result<Module> {
let key = PathBuf::from(label);
if !visited.insert(key.clone()) {
bail!("circular import involving {label}");
}
let result = (|| {
let mut module = parse_source(source).map_err(|e| anyhow::anyhow!("{label}: {e}"))?;
let imports = module.imports.clone();
let mut import_modules = HashMap::new();
for imp in imports {
let dep = load_embedded_import(&imp.path, visited)?;
if import_modules.contains_key(&imp.bind) {
bail!("duplicate import bind `{}` while loading {label}", imp.bind);
}
import_modules.insert(imp.bind, dep);
}
module.import_modules = import_modules;
crate::inherit::validate_inheritance(&module)
.map_err(|e| anyhow::anyhow!("{label}: {e}"))?;
Ok(module)
})();
visited.remove(&key);
result
}
fn load_embedded_import(rel: &str, visited: &mut HashSet<PathBuf>) -> Result<Module> {
let rel = rel.replace('\\', "/");
let rest = if let Some(r) = rel.strip_prefix("lib/") {
r.to_string()
} else if let Some(r) = rel.strip_prefix("std/") {
r.to_string()
} else if embedded_lib::read_file(&rel).is_some() {
rel.clone()
} else {
bail!(
"import `{rel}` is not an embedded lib/ path — \
run_source only resolves embedded stdlib (lib/…); filesystem and ext/ imports are unsupported"
);
};
let Some(dep_source) = embedded_lib::read_file(&rest) else {
bail!("embedded lib not found: lib/{rest}");
};
let label = format!("lib/{rest}");
load_module_from_source_inner(&dep_source, &label, visited)
}
#[cfg(test)]
+21
View File
@@ -124,6 +124,11 @@ enum Commands {
#[arg(long)]
check: bool,
},
/// Build browser WASM artifact (route C)
Wasm {
#[command(subcommand)]
action: WasmAction,
},
}
#[derive(Subcommand, Debug)]
@@ -142,6 +147,16 @@ enum ExtAction {
},
}
#[derive(Subcommand, Debug)]
enum WasmAction {
/// `cargo build -p marqdo-wasm --target wasm32-unknown-unknown --release` and copy `.wasm`
Build {
/// Destination directory (default: examples/browser-hello)
#[arg(short = 'o', long = "out", default_value = "examples/browser-hello")]
out: PathBuf,
},
}
#[derive(Subcommand, Debug)]
enum ViewAction {
/// Write static HTML documentation site
@@ -282,5 +297,11 @@ fn try_main() -> Result<i32> {
}
Ok(0)
}
Commands::Wasm { action } => match action {
WasmAction::Build { out } => {
marqdo::wasm_cli::build_wasm(&out)?;
Ok(0)
}
},
}
}
+157
View File
@@ -0,0 +1,157 @@
//! `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 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([
"build",
"-p",
"marqdo-wasm",
"--target",
"wasm32-unknown-unknown",
"--profile",
"release-wasm",
])
.status()
.context("failed to spawn cargo (is it on PATH?)")?;
if !status.success() {
bail!("cargo build -p marqdo-wasm --profile release-wasm failed with {status}");
}
let mut artifact = find_wasm_artifact()?;
std::fs::create_dir_all(out_dir)
.with_context(|| format!("create {}", out_dir.display()))?;
if let Some(optimized) = try_wasm_opt(&artifact)? {
artifact = optimized;
}
let dest_wasm = out_dir.join("marqdo_wasm.wasm");
std::fs::copy(&artifact, &dest_wasm).with_context(|| {
format!(
"copy {} → {}",
artifact.display(),
dest_wasm.display()
)
})?;
let bytes = std::fs::metadata(&dest_wasm)
.map(|m| m.len())
.unwrap_or(0);
println!(
"wrote {} ({:.1} KiB)",
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(())
}
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 {
return Ok(None);
};
if !out.status.success() {
return Ok(None);
}
let tmp = input.with_extension("opt.wasm");
let status = Command::new("wasm-opt")
.args(["-Oz", "--enable-bulk-memory"])
.arg(input)
.arg("-o")
.arg(&tmp)
.status()
.context("wasm-opt spawn failed")?;
if !status.success() {
let status2 = Command::new("wasm-opt")
.args(["-Oz"])
.arg(input)
.arg("-o")
.arg(&tmp)
.status()
.context("wasm-opt spawn failed")?;
if !status2.success() {
eprintln!("warning: wasm-opt failed; keeping cargo artifact");
return Ok(None);
}
}
println!("wasm-opt: {}", tmp.display());
Ok(Some(tmp))
}
fn find_wasm_artifact() -> Result<PathBuf> {
let mut candidates = Vec::new();
if let Ok(td) = std::env::var("CARGO_TARGET_DIR") {
candidates.push(
PathBuf::from(&td).join("wasm32-unknown-unknown/release-wasm/marqdo_wasm.wasm"),
);
candidates.push(
PathBuf::from(td).join("wasm32-unknown-unknown/release/marqdo_wasm.wasm"),
);
}
candidates.push(PathBuf::from(
"target/wasm32-unknown-unknown/release-wasm/marqdo_wasm.wasm",
));
candidates.push(PathBuf::from(
"target/wasm32-unknown-unknown/release/marqdo_wasm.wasm",
));
for c in &candidates {
if c.is_file() {
return Ok(c.clone());
}
}
bail!(
"built wasm not found; tried: {}",
candidates
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", ")
)
}
+3 -1
View File
@@ -182,7 +182,9 @@ fn structure_collection_cell_expr() {
gpt-4o-mini
https://api.openai.com/v1
/chat/completions
sk-live",
sk-live
1/5
16/9",
);
}
@@ -33,3 +33,13 @@ description: Data cells evaluate like call-arg values (`var`, paths, hyphen pros
| 1 | user | `secret` |
> print text=`rec`[^1][^content]
`ratios` =
| r |
|---|
| "1/5" |
| "16/9" |
> print text=`ratios`[^1]
> print text=`ratios`[^2]
+127
View File
@@ -0,0 +1,127 @@
#!/usr/bin/env node
/**
* 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, pathToFileURL } from "url";
import {
normalizeMountOptions,
eventArgsFromDom,
applyDomPatch,
renderListItems,
} from "../../crates/marqdo-wasm/js/marqdo-bridge.js";
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", { event: "click" });
const c2 = call("bump", { event: "click", value: "x" });
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);
}
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);
}
const html = renderListItems({
tag: "li",
items: ["a", { text: "b", attrs: { "data-id": "2" } }],
});
if (!html.includes("<li>a</li>") || !html.includes('data-id="2"')) {
console.error("renderListItems failed", html);
process.exit(1);
}
// DOM patch without document should no-op
applyDomPatch({
set_text: { "#x": "y" },
set_style: { "#x": { color: "red" } },
navigate: { url: "/x" },
});
console.log("wasm smoke ok");
console.log("bridge helpers ok");
void pathToFileURL;
+54
View File
@@ -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}");
}