Compare commits

...
28 Commits
Author SHA1 Message Date
cflmyandCursor 5745805a5d docs: blank line before v0.3.3 in CHANGELOG
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 14:20:31 +08:00
cflmyandCursor 590f7a58fa release: v0.3.4 — ext/web customization C0–C4
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 14:16:41 +08:00
cflmyandCursor 027b19c5db feat(web): C4 conditional nav with when and media columns
Filter nav/sidebar/footer by auth/guest/hide and emit responsive media CSS; stamp _logged_in from session on listen.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 13:54:53 +08:00
cflmyandCursor 7670673a39 feat(web): C3 style cell strict checks and head defer/version
Warn or reject numeric CSS values from bare `/` division; support script defer/async/version and page/app asset_version for cache busting.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 13:43:35 +08:00
cflmyandCursor 824b9bf607 docs(web): mark C1 auth-gates solution as landed
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 12:49:07 +08:00
cflmyandCursor 155183eb30 feat(web): C2 shell_css modes and page layout presets
Split injected shell CSS into vars/layout/widgets with full|minimal|off, add stacked/bare/rail layouts, and stop forcing has-sidebar when authors opt out.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 12:48:50 +08:00
cflmyandCursor b10a84466b feat(web): C1 segment-boundary gates with on_deny and exclude
Make auth/admin gates use path segment prefixes, configurable redirect vs 403, and login_path exclusion so /admin-publish and /desk/login are not mis-matched.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 12:38:44 +08:00
cflmyandCursor 0aa0f47a9d feat(web): C0 release /admin when disabled; configurable admin_prefix
Stop mounting reserved admin routes when admin=False, nest CRUD under a
configurable prefix, and honor login/logout redirects so custom desks need no JS bypass.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 11:50:11 +08:00
cflmyandCursor 5f91be7c21 docs(web): catalog customization limits and C0–C4 fix designs
Capture route/shell/auth/theme pain points from real sites and lock per-item solution docs before plugin work.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 11:38:20 +08:00
cflmyandCursor e3e2cfa9d1 fix(agent): writeback param shadow + Wave B1 dump/harness
step/plan writeback=True shadowed lib/writeback; persist via host_writeback_record. Align ZH context builder, add dump_step_context, lock offline harness.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 11:24:50 +08:00
cflmyandCursor d1b4e62d4d feat(agent): Wave B0 constitution demos + harness
Lock code-as-doc / call_site / OKF as first-class: reorder step
context, ship agent-pong and okf-flywheel examples, offline harness,
and skill/docs refresh. Dev LLM template via .env.example only.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 11:17:25 +08:00
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
119 changed files with 14977 additions and 584 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())
+30 -5
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)
@@ -134,13 +141,27 @@ import clock:lib/time.mq.md
- Instance methods stay `` > `obj`.method `` (backticks on the receiver only).
- `lib/…` resolves via `MARQDO_LIB`, cwd `lib/`, or `lib/` next to the `marqdo` binary.
- Design: [module-namespace.md](../../doc/design/module-namespace.md).
- Official optional extensions (`ext/`, not stdlib): install with `marqdo ext add llm|agent|web|quantum` (see `doc/design/ext-cli.md`). `ext/llm` — chat; `ext/agent` — document-driven agents: **step** (default writeback) / **plan** workbook ([ext-agent.md](../../doc/design/ext-agent.md), [ext-agent-plan.md](../../doc/design/ext-agent-plan.md)); **`ext/web`** — dynamic sites (W0–W7 + P3 complete; see below); **`ext/quantum`** — circuits + Q7 density/viz + Q8 themed SVG (see below).
- Official optional extensions (`ext/`, not stdlib): install with `marqdo ext add llm|agent|web|quantum` (see `doc/design/ext-cli.md`). `ext/llm` — chat; **`ext/agent`** — document-driven agents (see **ext/agent** below); **`ext/web`** — dynamic sites (see below); **`ext/quantum`** — circuits + Q7/Q8 (see below).
- Native plugins: `lib/plugin` — `## load` / `unload` / `list`. C ABI: `include/marqdo_abi.h`.
- Prefer `table.put` / `表.改` for list/map element updates; keep `json` for parse/stringify/quote (see `doc/design/stdlib-table.md`).
- Builtins (no import): `print`/`打印`, `input`/`输入`, `len`/`长度`, `str`/`文本`, `int`/`整数`; literals `True`/`真`, `False`/`假`, `None`/`空`; logic `and`/`且`, `or`/`或`, `not`/`非`.
Stdlib map: [reference.md](reference.md).
## Official extension: `ext/agent` (document-driven)
Install: `marqdo ext add agent` (ZH: `智能体`). Native: `cargo build --release -p marqdo_plugin_agent`.
**Constitution (do not dilute):**
1. **Code is documentation** — the runbook `.mq.md` is the model’s ground truth, not a hidden system prompt bag.
2. **Call site is first-class** — `build_step_context` injects path/function/line so the model knows where it is in the program.
3. **Document is the knowledge base (OKF)** — writeback → promote/solidify → reuse / `llm_free`; MCP/corpus are evidence only.
APIs: `# agent` / `# 智能体` → `## step` / `## plan`. Context: standing + task + **call site** + tools + budgeted source/skill + act protocol (`CALL:` / `READ:`). Inspect without LLM: `dump_step_context`. Inside `writeback=` / `写回=` branches use `host_writeback_record` (param name shadows the writeback import).
Examples: [agent-pong](../../examples/agent-pong/) · [agent-okf-flywheel](../../examples/agent-okf-flywheel/). Harness: `scripts/agent-harness.sh`. Design: [ext-agent.md](../../doc/design/ext-agent.md) · Wave B: [agent-framework-2026-09.md](../../doc/research/agent-framework-2026-09.md). Dev LLM: copy [.env.example](../../.env.example) → `.env` (gitignored).
## Official extension: `ext/web` (dynamic sites)
Install: `marqdo ext add web` (ZH id: `网页`). Build native plugin first: `cargo build --release -p marqdo_plugin_web`.
@@ -172,11 +193,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 +246,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 +264,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
+3 -2
View File
@@ -44,16 +44,17 @@ 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 |
| `ext/agent.mq.md` | `ext/智能体.mq.md` | agent **framework** (layout now; LLM orchestration roadmap in `ext-agent.md`) |
| `ext/agent.mq.md` | `ext/智能体.mq.md` | document-driven **step** / **plan** + OKF;示例 `examples/agent-pong` · `agent-okf-flywheel`;Wave B:[agent-framework-2026-09.md](../../doc/research/agent-framework-2026-09.md) |
| `ext/web/web.mq.md` | `ext/web/网页.mq.md` | dynamic sites — see **ext/web** section below |
| `ext/quantum/quantum.mq.md` | `ext/quantum/量子.mq.md` | circuits + Q7 density/viz + Q8 themes — see **ext/quantum** below |
+12
View File
@@ -0,0 +1,12 @@
# Local LLM for Marqdo agent / ext/ai/llm development.
# Copy to `.env` in the repo root (gitignored) and fill secrets.
# Never commit real keys.
OPENAI_API_KEY=
OPENAI_BASE_URL=https://llm.cflmy.cn/v1
OPENAI_MODEL=cflmy
# Aliases also accepted by ext/ai/llm:
# MARQDO_LLM_API_KEY=
# MARQDO_LLM_BASE_URL=
# MARQDO_LLM_MODEL=
+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.4
- **`ext/web` 定制 C0–C4**:admin 前缀可让出、段边界 gates、shell/layout、样式 strict、脚本 defer/version、条件导航 when/media
- **ext/web customization C0–C4**: configurable admin/gates/shell/layout/CSS strict/script lifecycle/conditional nav
- Agent Wave B0 demos + writeback shadow fix
- 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)
+8
View File
@@ -23,6 +23,7 @@
.DS_Store
.marqdo/
**/.marqdo/
.marqdo-ext/
.env
# Generated HTML beside tracked public/*.mq.md (sources stay in git)
@@ -39,6 +40,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/
+89
View File
@@ -2,6 +2,95 @@
## Unreleased
### Added
### Fixed
### Changed
## v0.3.4 — 2026-09-04
### Highlights
**`ext/web` 定制波次 C0–C4 收口**:可配置 admin 前缀与登录回跳、段边界 gates、shell/layout、样式单元格 strict、脚本 defer/version/`asset_version`、条件导航 when/media。附智能体 Wave B0 示例与写回遮蔽修复。
```bash
git checkout v0.3.4
cargo build --release
cargo build --release -p marqdo_plugin_web
marqdo ext add web
# golds: tests/ext/web-c0-admin-prefix … web-c4-nav-when
```
### Added
- **智能体 Wave B0**:宪法优先示例 [agent-pong](examples/agent-pong/)(call_site/源码注入)· [agent-okf-flywheel](examples/agent-okf-flywheel/)(OKF `cache=hit`);调研 [agent-framework-2026-09.md](doc/research/agent-framework-2026-09.md);离线 harness [`scripts/agent-harness.sh`](scripts/agent-harness.sh);金样 `agent-constitution-b0`。
- **`.env.example`**:开发期 OpenAI 兼容网关变量模板(密钥仅本地 `.env`)。
### Fixed
- **`agent.step` / `plan` 写回**:参数名 `writeback` 遮蔽 `lib/writeback` import,导致 `writeback=True` 时 `method receiver must be an object map`;改为 `host_writeback_record`。金样 `agent-writeback-shadow`。
- **`ext/web` C0**:`admin=False` 不再挂载/保留 `/admin*`;可配 `admin_prefix` / `login_redirect` / `logout_redirect`;金样 `web-c0-admin-prefix`。
- **`ext/web` C1**:门禁段边界匹配(不再误伤 `/admin-publish`);`gate` 支持 `match` / `on_deny` / `exclude`;`auth` 默认 `on_deny=redirect` + `login_path`;金样 `web-c1-gates`。
- **`ext/web` C2**:`shell_css=full|minimal|off`;`layout=sidebar|stacked|bare|rail`;full 壳含小屏单列 media;金样 `web-c2-shell-layout`。
- **`ext/web` C3**:样式装配对数字/布尔值单元格告警,`strict`/`strict_css_cells` 硬错误;`page.css` 作 raw CSS;head 表支持 `defer`/`async`/`version`,`asset_version` 统一 `?v=`;金样 `web-c3-style-head`。
- **`ext/web` C4**:导航表 `当`/`when`(`auth`/`guest`/`hide`)与 `媒体`/`media`(响应式显隐);listen 注入 `_logged_in`;金样 `web-c4-nav-when`。
### Changed
- `build_step_context`:call site 提前到 task 之后;开场白强调 code-as-documentation。
- 中文 `构建单步上下文` 委托英文版(含预算 / READ);新增 `dump_step_context`;live 用例改用仓库根 `.env`。
- 文档:[ext-web 定制限制](doc/research/ext-web-customization-limits.md) + [解决设计 C0–C4](doc/design/ext-web-customization/)。
## 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.4"
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"
+13 -8
View File
@@ -99,7 +99,7 @@ marqdo catalog public -o .marqdo
---
## 现状(v0.3.1)
## 现状(v0.3.4)
- 映射与解释器:Phase I 树遍历 + 字节码后端可用;金样例在 `tests/`
- **对象**:`#` = 类型/构造,`##`+ = 函数/方法;见 [objects.md](doc/design/objects.md)
@@ -107,9 +107,9 @@ 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)
- **`web`**:W0–W7 + P3 + **W8**;**定制 C0–C4**(admin 前缀/gates/`shell_css`/`layout`/样式 strict/脚本 defer·version/条件导航,见 [ext-web-customization](doc/design/ext-web-customization/));示例 [marqdo-blog](examples/marqdo-blog/);生产路径见 [web-asgi-servers-and-marqdo.md](doc/design/web-asgi-servers-and-marqdo.md)
- **`quantum`**:Q0–Q7 + Q8a/b 主题 SVG;示例 [quantum-entanglement](examples/quantum-entanglement/)
- **`agent`**:A1–A4(OKF 复用、过程事件、上下文预算、RAG/MCP fixture);下一波缺口 [agent-framework-gaps-after-a4.md](doc/research/agent-framework-gaps-after-a4.md)
- **`llm`**:OpenAI 兼容对话
@@ -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.4)
```bash
# 1) 源码安装(跟 tag 或 main)
git clone https://github.com/cflmy/marqdo.git && cd marqdo
git checkout v0.3.1 # 或留在 main
git checkout v0.3.4 # 或留在 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.4
```
开发期也可用 `cargo run -- …` 代替已安装的 `marqdo`:
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "marqdo-wasm"
version = "0.3.4"
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");
}
}
+10 -3
View File
@@ -40,6 +40,8 @@
| [design/ext-agent-plan.md](design/ext-agent-plan.md) | **`## 多步` / `## plan` 锁定设计**(工作簿文件、subtask 执行、修订循环、`step` 默认写回) |
| [design/ext-cli.md](design/ext-cli.md) | **`marqdo ext list/add/remove` 官方扩展安装器** |
| [design/ext-web.md](design/ext-web.md) | **官方扩展 `ext/web`(页面/库表/绑定/后台;ABI + CLI;设计锁定)** |
| [research/ext-web-customization-limits.md](research/ext-web-customization-limits.md) | **`ext/web` 定制限制踩坑盘点**(路由/壳 CSS/鉴权/样式/部署) |
| [design/ext-web-customization/](design/ext-web-customization/) | **对应解决设计**(C0–C4:前缀可让出、shell_css、gate、布局…) |
| [design/web-assets-and-images.md](design/web-assets-and-images.md) | **W8:favicon / Head 资源表 / 图片装配**(一次补齐) |
| [design/web-asgi-servers-and-marqdo.md](design/web-asgi-servers-and-marqdo.md) | **Daphne/Uvicorn 等 vs Marqdo**:不能直接托管;反代 + axum `listen` |
| [design/call-arguments.md](design/call-arguments.md) | **调用:具名 + 位置实参** |
@@ -59,12 +61,17 @@
| [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 优势 |
| [research/agent-framework-gaps-after-a4.md](research/agent-framework-gaps-after-a4.md) | **`ext/agent` A0–A4 之后缺口盘点**(产品化 / 评测 / MCP / resume) |
| [roadmap/ext-agent-optimize.md](roadmap/ext-agent-optimize.md) | **`ext/agent` 深入优化 A0–A4**(已完成) |
| [research/agent-framework-gaps-after-a4.md](research/agent-framework-gaps-after-a4.md) | **`ext/agent` A0–A4 之后缺口盘点** |
| [research/agent-framework-2026-09.md](research/agent-framework-2026-09.md) | **2026-09 刷新:宪法优先 Wave B** |
| [roadmap/ext-agent-optimize.md](roadmap/ext-agent-optimize.md) | **`ext/agent` A0–A4 done · Wave B Active** |
金样例与集成测试:[`tests/`](../tests/)。面向访客的可执行文档:[`public/`](../public/)。Spike 存档:[`spike/`](../spike/)。
+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
@@ -0,0 +1,74 @@
# 解决 1:路由与 `/admin` 前缀可让出
| | |
|---|---|
| 问题 | [研究 §1](../../research/ext-web-customization-limits.md#1-路由与路径被框架强占) |
| 优先级 | **P0** · 波次 **C0** |
| 触点 | `plugins/web/src/lib.rs`(`normalize_route_path`、`web_app_new`、redirect)· `plugins/web/src/http.rs`(admin 路由挂载、login redirect)· `ext/web/web.mq.md` / `网页.mq.md` |
---
## 1. 目标
1. 关闭内置后台后,**整段前缀可被站点路由占用**(含自研 `/admin`)。
2. 开启内置后台时,前缀**可配置**(默认仍 `/admin`),登录成功/登出落地页可配置。
3. `app.route` / `app.redirect` 只禁止**当前生效**的框架保留段,不再永久霸占 `/admin`。
---
## 2. 作者 API(草案)
```markdown
*应用 = > web.app page=`首页` db=`库` admin=False*
# 或:仍用内置 CRUD,但挂到旁路前缀 + 自定义回跳
*应用 = > web.app page=`首页` db=`库` admin=True*
*应用 = > `应用`.auth users=`用户表` admin_prefix="/desk" login_redirect="/desk" logout_redirect="/desk/login"*
```
| 参数 | 默认 | 含义 |
|------|------|------|
| `admin` / `后台` | `False` | `False`:**不注册**任何内置 admin HTTP 路由 |
| `admin_prefix` / `后台前缀` | `"/admin"` | 内置 CRUD + 登录页挂载根;仅 `admin=True` 时生效 |
| `login_redirect` / `登录回跳` | `{admin_prefix}` | 登录成功 303 目标 |
| `logout_redirect` / `登出回跳` | `{admin_prefix}/login` | 登出后目标 |
中文别名与英文一一对应,写进 `网页.mq.md`。
---
## 3. 插件改动点
| 改动 | 说明 |
|------|------|
| `normalize_route_path(app)` | reserved 列表改为:`/_form`、`/_part`、`/static` + **当前** `admin_prefix`(仅当 `admin=True`) |
| `listen` 路由表 | `admin=False` → **不** `.route("/admin…")`;为真则用 `admin_prefix` 拼路径 |
| `admin_login_post` / `admin_logout` | 使用配置的 redirect,禁止写死 `"/admin"` |
| `web_app_redirect` | 校验目标时用同一套动态 reserved,允许指向已让出的 `/admin` |
| disabled 文案路径 | 删除「挂路由但只显示 Admin is disabled」;无路由则 404 或落入站点自定义页 |
---
## 4. 兼容策略
- 缺省参数下:现有 `examples/web-site`、`web-net-site`、`marqdo-blog` 行为不变(仍 `/admin` + 跳 `/admin`)。
- 文档明确:`admin=False` 后若仍要登录能力,用 §3 的通用 `auth`/`gate`,不必再依赖内置 admin 壳。
---
## 5. 验收
| 金样 / 手工 | 期望 |
|-------------|------|
| `admin=False` + `route path="/admin/news"` | 注册成功;GET 渲染站点页,**不是** Admin is disabled |
| `admin_prefix="/desk"` | 内置登录在 `/desk/login`;成功跳 `login_redirect` |
| 默认 `admin=True` 无新参数 | 与现网一致 |
| `redirect` 到已让出的 `/admin` | 允许 |
---
## 6. 过渡期 → 已落地
~~继续用 `/desk` 旁路 + JS 调 `/admin/login`。~~
**C0 已落地(2026-09):** `admin=False` 可直接 `route path="/admin/…"`;或 `admin=True` + `admin_prefix="/desk"` + `login_redirect` / `logout_redirect`。见金样 `tests/ext/web-c0-admin-prefix.mq.md`。
@@ -0,0 +1,72 @@
# 解决 2:`SHELL_CSS` 可关 / 可分层
| | |
|---|---|
| 问题 | [研究 §2](../../research/ext-web-customization-limits.md#2-内置-shell_css-难以彻底覆盖) |
| 优先级 | **P1** · 波次 **C2** |
| 触点 | `plugins/web/src/render.rs`(`SHELL_CSS`、`<style>` 拼接)· page/app 元数据 · `ext/web` 样式装配 |
---
## 1. 目标
1. 站点主题可选择:**不要**框架栅格/卡片默认,或只要 reset 级变量。
2. 壳 CSS 与主题 CSS 的级联顺序**可声明、可文档化**。
3. 默认仍注入完整壳(兼容旧站);新主题显式 `shell_css=off` 即可干净起步。
---
## 2. 作者 API(草案)
```markdown
*应用 = > web.app page=`首页` … shell_css="minimal"*
# 或页面级覆盖
*页 = > `页`.meta …* # 或 page 选项 shell_css=
```
| 值 | 行为 |
|----|------|
| `full`(默认) | 现网 `SHELL_CSS` 全文 |
| `minimal` | 仅 `:root` 变量 + `body` margin/字体;**不含** `has-sidebar` 双列栅格与卡片表单皮肤 |
| `off` / `none` | 不注入框架壳样式;只输出站点 `style` / 外链 CSS |
级联顺序锁定为文档约定:
1. (可选)框架 `SHELL_CSS`
2. 站点全局 style 表 / `site.css`
3. 页面级 style
禁止再出现「主题写在 extra,却被同特异性壳规则在小屏打穿且无媒体查询」而无开关可关的情况。
---
## 3. 插件改动点
| 改动 | 说明 |
|------|------|
| 拆分 `SHELL_CSS` | `SHELL_VARS` / `SHELL_LAYOUT` / `SHELL_WIDGETS` 三段;`full`=`all`,`minimal`=vars(+极简 layout) |
| `render` 读 `app.shell_css` / `page.shell_css` | 页面覆盖应用 |
| 为 `has-sidebar` 布局加基础媒体查询 | 即使 `full`,小屏改为单列(减轻幽灵双列);`minimal`/`off` 不负责响应式 |
---
## 4. 兼容策略
- 默认 `full`:视觉与现网一致。
- Tutorial 增加一节「品牌主题请用 `shell_css=minimal|off`」。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| `shell_css=off` + 站点只写单列 grid | 响应里**无** `grid-template-columns:14rem` |
| `minimal` | 有 CSS 变量;无 `.content.cards article` 边框默认(或等价皮肤段) |
| 默认示例站 | HTML 仍含完整壳 CSS |
---
## 6. 过渡期 → 已落地
**C2 已落地(2026-09):** `shell_css=full|minimal|off`;页面/应用可设;`full` 含 `@media (max-width:720px)` 单列。金样 `tests/ext/web-c2-shell-layout.mq.md`。
@@ -0,0 +1,72 @@
# 解决 3:鉴权 / 门禁可配置且行为一致
| | |
|---|---|
| 问题 | [研究 §3](../../research/ext-web-customization-limits.md#3-鉴权--门禁模型偏固定) |
| 优先级 | **P0** · 波次 **C1**(依赖 [01](01-routes-and-admin-prefix.md) 的 prefix) |
| 触点 | `plugins/web/src/http.rs`(`rbac_middleware`、`path_matches`、login 表单)· `lib.rs`(`web_app_auth` / `web_app_gate`)· `ext/web` |
---
## 1. 目标
1. **未登录策略一致**:可配置 `redirect`(303 登录)或 `forbid`(403),对任意 gate 路径生效,不再「仅 `/admin*` 会跳登录」。
2. **匹配语义清晰**:支持精确路径、前缀、以及排除列表;`/desk` 默认**不**误伤 `/desk/login`。
3. 默认 admin gate 使用 **路径段边界**(`/admin` 与 `/admin/…`),不匹配 `/admin-publish`。
4. 登录 URL、表单 `action`、成功/失败回跳均可配置(与 C0 对齐)。
---
## 2. 作者 API(草案)
```markdown
*应用 = > `应用`.auth users=`用户表` login_path="/desk/login" login_redirect="/desk"*
*应用 = > `应用`.gate path="/desk" roles="admin" match="prefix" on_deny="redirect" exclude="/desk/login"*
```
| 字段 | 说明 |
|------|------|
| `login_path` | 登录页 URL(GET 表单 + POST 处理);默认 `{admin_prefix}/login` |
| `match` | `exact` \| `prefix`(默认对自定义 gate 建议 `prefix` + `exclude`) |
| `on_deny` | `redirect` \| `forbid`;`redirect` 时跳 `login_path`(可带 `?next=`) |
| `exclude` | 逗号分隔或表列:匹配前缀时放行的路径 |
`auth` 注册默认 gate 时:
- 使用 `{admin_prefix}` + 段边界,**不要** `starts_with("/admin")` 裸前缀。
- 自动把 `login_path` 加入放行列表。
---
## 3. 插件改动点
| 改动 | 说明 |
|------|------|
| `path_matches` | 增加 `exact`;`prefix` 要求下一字符为 `/` 或结尾;可选 exclude |
| `rbac_middleware` | 按 gate 的 `on_deny` 分支;通用放行 `login_path`,不写死 `/admin/login` |
| 登录 HTML | `action={login_path}`;hidden `next` 可选 |
| Session/CSRF | 短期仍用框架实现;文档标明字段名;中期再开放 `login_form` 自定义字段映射(非本波次必做) |
---
## 4. 兼容策略
- 未传新字段:行为对齐现网(`/admin*` → redirect 登录;其它自定义 gate → 403)。
- 新增金样:`/desk` gate + `/desk/login` 可匿名打开。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| visitor 访问 `/desk`(`on_deny=redirect`) | 303 → `/desk/login`,不是 403 |
| visitor 访问 `/desk/login`(exclude) | 200 登录页 |
| `/admin-publish` 无显式 gate | **不**被默认 admin gate 拦住 |
| 旧站仅 `app.auth` | 仍保护 `/admin*` |
---
## 6. 过渡期 → 已落地
**C1 已落地(2026-09):** `auth` 默认段边界 prefix + `on_deny=redirect` + 排除 `login_path`;自定义 `gate` 可设 `match` / `on_deny` / `exclude`。金样 `tests/ext/web-c1-gates.mq.md`;单元测试 `http::gate_tests`。
@@ -0,0 +1,69 @@
# 解决 4:样式表作者体验
| | |
|---|---|
| 问题 | [研究 §4](../../research/ext-web-customization-limits.md#4-样式作者体验受限) |
| 优先级 | **P2** · 波次 **C3** |
| 触点 | 表单元格表达式(T5)· `ext/web` style 装配 · 教程 / Skill · 可选校验 |
---
## 1. 目标
1. 含 `/`、`,`、括号的 CSS 值**不易被静默算坏**。
2. 复杂选择器 / `@keyframes` / 多层 media 有**官方推荐写法**(表内 vs 外链 vs raw 块)。
3. 与壳 CSS 的层叠关系在文档中一句话写清(并链到 [02](02-shell-css.md))。
---
## 2. 作者 API / 约定(草案)
### 2.1 立即固化的文档约定(可不改代码)
| 规则 | 说明 |
|------|------|
| 含 `/` 的值必须引号 | `"1 / 5"`、`"image/png"`(已有;Skill/教程加醒目反例) |
| 复杂皮肤优先外链 | `static/theme.css` + `page.head` / `app.icons` 同类资源表 |
| `@keyframes` / 长 media | 放外链 CSS,不塞进 GFM 单元格 |
| 调试 | `shell_css=off` 后只看主题文件,避免同页双源 |
### 2.2 产品增强(C3)
| 能力 | 说明 |
|------|------|
| `style` 装配时对可疑单元格告警 | 未加引号且含 `/` → listen/assemble 警告或硬错误(可开关) |
| 可选 `##` raw CSS 块绑定 | 例如页面附属 ````css` 具名块,**不经**表表达式求值 |
| 文档示例 | `min-width` + `max-width` 外链表;引用 [table-cell-expressions.md](../table-cell-expressions.md) |
---
## 3. 插件 / 核心改动点
| 改动 | 说明 |
|------|------|
| web style 编译 | 可选 `strict_css_cells=True`:裸 `/` 报错 |
| (可选)`web_page_css_raw` | 把文本 CSS 追加到页面,跳过 T5 |
| Skill `marqdo` / tutorial 14 | 增加「样式踩坑」小节 |
---
## 4. 兼容策略
- 默认不硬错误(避免打碎旧表);新 scaffold 默认 `strict_css_cells` 或文档强制引号。
- 不把完整 CSS 语法塞进表格方言——复杂内容走文件。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| 文档反例 `grid-column` 裸 `1 / 5` | 在 strict 模式下失败或警告 |
| 外链 `theme.css` + `shell_css=off` | 无壳栅格串扰 |
| 现有 web 示例 | 默认模式仍绿 |
---
## 6. 过渡期 workaround
全部敏感值加引号;响应式与 keyframes 只写在 `static/*.css`;小屏问题优先关壳([02](02-shell-css.md))再调主题。
@@ -0,0 +1,85 @@
# 解决 5:页面壳与插槽松绑
| | |
|---|---|
| 问题 | [研究 §5](../../research/ext-web-customization-limits.md#5-页面壳与插槽约定僵硬) |
| 优先级 | **P1** · 波次 **C2/C4** |
| 触点 | `plugins/web/src/render.rs`(body class、四区 HTML)· page 槽位装配 · nav 组件表 |
---
## 1. 目标
1. 作者可选**非侧栏栅格**布局,而不必用 CSS 硬怼掉 `has-sidebar`。
2. 侧栏存在 ≠ 强制桌面双列;提供 stacked / bare 等预设。
3. 为「条件导航」留扩展点(先文档 + 简单 hook,完整运行时条件可后置)。
---
## 2. 作者 API(草案)
```markdown
*首页 = > web.page … layout="stacked"*
*应用 = > web.app page=`首页` … layout="bare"*
```
| `layout` | DOM / class | 说明 |
|----------|-------------|------|
| `sidebar`(默认,有 side 槽时) | `body.has-sidebar` | 现网行为 |
| `stacked` | `body.layout-stacked`;side 在 main 上或折叠区 | 单列流式,适合杂志/营销 |
| `bare` | 无 top/side/foot 强制栅格;只渲染 `main`(+ 显式槽) | 登录页、落地页 |
| `rail`(可选) | 保留站点已有 `has-rail` 约定并文档化 | 避免「只有首页有 class」 |
规则:**有 side 组件但 `layout=stacked|bare` 时,不自动加 `has-sidebar`。**
---
## 3. 插件改动点
| 改动 | 说明 |
|------|------|
| `render` 读 `page.layout` / `app.layout` | 决定 body class 与 HTML 骨架 |
| `SHELL_LAYOUT`(见 [02](02-shell-css.md)) | 为 `layout-stacked` / `layout-bare` 提供最小样式;`shell_css=off` 时不注入 |
| Nav 表 | 短期保持声明式;文档说明「条件项用两套 nav 组件 + 媒体查询隐藏」 |
| 中期 hook(非阻断) | `navigate` 已有字段可扩展 `when`/`media` 列(单独 RFC) |
---
## 4. 兼容策略
- 未设 `layout`:有 side → 与现网 `has-sidebar` 相同。
- 金样增加 `layout=bare` 登录页(可与 C0 自研 `/desk/login` 共用)。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| 有 side + `layout=stacked` | body **无** `has-sidebar`;无 `14rem` 双列(在 full 壳下用 stacked 规则) |
| `layout=bare` | 输出不含 `<aside class="side">`(或 empty 不占栅格) |
| 默认站 | 不变 |
---
## 6. 过渡期 → 已落地
**C2 已落地(2026-09):** `layout=sidebar|stacked|bare|rail`;有 side 时 `stacked`/`bare` 不再强制 `has-sidebar`。金样 `web-c2-shell-layout`。
**C4 已落地(2026-09):** 导航 / 侧栏 / 页脚绑定表可选列:
| 列 | 说明 |
|----|------|
| `媒体` / `media` | CSS media;不匹配时 `display:none`(生成 `nav-mq-*` + `@media not …`) |
| `当` / `when` | `hide` 省略;`auth` / `guest` 按登录态过滤;空 = 总是显示 |
```markdown
| 属性 | 值 | 样式 | 媒体 | 当 |
|------|-----|------|------|-----|
| Home | / | | | |
| Menu | /m | | (max-width: 720px) | |
| Admin | /admin | | | auth |
| Login | /login | | | guest |
```
Listen 渲染时写入 `_logged_in` / `_nav_user`(来自 session)。离线 `page.render` 可自行 `table.put` `_logged_in`。金样 `web-c4-nav-when`。
@@ -0,0 +1,67 @@
# 解决 6:后台 CRUD 与表单能力边界
| | |
|---|---|
| 问题 | [研究 §6](../../research/ext-web-customization-limits.md#6-后台-crud-与表单能力边界) |
| 优先级 | **P3** · 随 C0 文档化;增强可选 |
| 触点 | `plugins/web/src/http.rs` / `form.rs`(内置 admin)· 站点自研页 + `db.*` · `/_form` |
---
## 1. 目标
1. **产品叙事澄清**:内置 `/admin`(或可配置前缀)= 通用表浏览器,**不是** CMS;关则彻底让路(见 [01](01-routes-and-admin-prefix.md))。
2. 自研后台的推荐路径写清楚:`page` + `form` + `db` + gate,而不是改插件壳。
3. 对「链接前缀 / new / edit」给出约定或薄辅助,减少前端状态机拼装。
---
## 2. 作者 API / 文档(草案)
### 2.1 推荐架构(文档为主)
| 需求 | 做法 |
|------|------|
| 产品级编辑器、专栏联动 | 自研 `# page` + 组件;写库用 `db.insert`/`update`;鉴权用 `gate` |
| 简单表维护 | 开 `admin=True`(可换前缀) |
| 关内置仍要 CRUD | 自研列表/编辑页;**不要**依赖 disabled 壳 |
### 2.2 可选薄增强(非 CMS)
| 能力 | 说明 |
|------|------|
| `form` 支持 `mode=new\|edit` 查询参数约定 | 文档 + 示例;必要时 `web.form` 读 `id`/`new` |
| `list` 组件 `link_prefix` | 已有则补示例;缺失则加一列「详情路径模板」 |
| Markdown 字段 | 继续「存库 + 前台渲染」;分栏编辑器保持外挂 JS(明确不做进 ABI) |
---
## 3. 插件改动点
| 改动 | 优先级 |
|------|--------|
| C0:disabled 不占路径 | 必需(属 [01](01-routes-and-admin-prefix.md)) |
| 示例 `examples/web-custom-desk/` | 展示自研列表/编辑,零内置 admin |
| form 查询参数助手 | 可选 |
---
## 4. 兼容策略
- 不扩展内置 admin 成 CMS(避免范围爆炸)。
- Tutorial 增加「何时用内置 admin / 何时自研」。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| 文档 + 示例 desk | 无 `/admin` 也能完成一文增删改 |
| 内置 admin 金样 | 仍绿 |
---
## 6. 过渡期 workaround
自研 `/desk` + 调用 `/_form` 或直接 DB API;复杂编辑器继续外挂 JS。
@@ -0,0 +1,71 @@
# 解决 7:静态资源与脚本生命周期
| | |
|---|---|
| 问题 | [研究 §7](../../research/ext-web-customization-limits.md#7-静态资源与脚本生命周期) |
| 优先级 | **P2** · 波次 **C3** |
| 触点 | `web_page_head` / `web_head` · `render.rs` head 输出 · static 挂载 · [web-assets-and-images.md](../web-assets-and-images.md) |
---
## 1. 目标
1. 默认脚本加载方式**不假设**作者手写 IIFE 抢在 DOM 前执行成功;提供 `defer` / `module` 一等约定。
2. 静态资源变更可发现:文档化 `?v=`,并提供可选自动指纹或 listen 时 mtime 查询参数。
---
## 2. 作者 API(草案)
Head 资源表扩展列(向后兼容):
| 列 | 说明 |
|----|------|
| `rel` / `关系` | 已有;`script` / `module` |
| `defer` / `推迟` | `真` → `<script defer>`(**建议默认对 script 为真**) |
| `async` / `异步` | 可选 |
| `version` / `版本` | 非空则自动追加 `?v=` |
```markdown
`头` =
| 关系 | 地址 | 推迟 | 版本 |
|------|------|------|------|
| script | /static/theme.js | 真 | 2026-09-04 |
| module | /static/desk.js | 真 | 3 |
```
全局:`app.asset_version="2026-09-04"` 为所有 static 链接统一 bump(可选)。
---
## 3. 插件改动点
| 改动 | 说明 |
|------|------|
| head 渲染 | 尊重 defer/async;`module` → `type="module"`(已有则核对) |
| 默认 | 新建 scaffold 的 script 行带 `defer` |
| (可选)`asset_version` | listen 时重写 head / 页面内 static URL |
| 文档 | 「禁止在同步 head 脚本里直接 `getElementById` 主节点;用 defer 或 `DOMContentLoaded`」 |
---
## 4. 兼容策略
- 旧表无 `defer` 列:保持现网同步行为(或仅对 scaffold/新文档默认 defer,避免静默改变旧站时序)。
- 更安全:缺省仍同步;**Skill 与 scaffold 默认写 defer=真**。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| defer 脚本读 DOM | 登录跳转逻辑在 DOM 就绪后执行 |
| `version` 列 | HTML 中出现 `theme.js?v=…` |
| 旧示例无新列 | 仍通过 |
---
## 6. 过渡期 workaround
脚本改 `type=module` 或放 body 末;手动 `?v=` bump;登录逻辑用 `DOMContentLoaded`。
@@ -0,0 +1,60 @@
# 解决 8:扩展与部署耦合
| | |
|---|---|
| 问题 | [研究 §8](../../research/ext-web-customization-limits.md#8-扩展与部署耦合) |
| 优先级 | **P3** · 文档 + 发布流程 |
| 触点 | `marqdo ext add web` · ABI 版本 · Docker/发布说明 · [ext-cli.md](../ext-cli.md) · [marqdo-release](../../../.cursor/skills/marqdo-release/SKILL.md) |
---
## 1. 目标
1. 站点作者**不必 fork 插件**才能完成 P0/P1 定制(把能力收进官方参数,见 01–05)。
2. 版本耦合可预期:changelog / 扩展清单标明「web 插件需 ≥ x.y.z」。
3. 升级路径文档化:二进制、`.marqdo-ext`、Docker 镜像三者对齐检查。
---
## 2. 作者 / 运维约定(草案)
| 约定 | 说明 |
|------|------|
| 定制优先走 `.mq.md` 开关 | `admin_prefix`、`shell_css`、`layout`、`gate`… 进官方 API 后,禁止文档再教「改 plugins/web」 |
| 兼容性矩阵 | 在 [web-net-capabilities.md](../web-net-capabilities.md) 或本目录维护「Marqdo ↔ libweb 最低版本」表 |
| `marqdo ext add web` | 安装后打印当前插件路径与版本;与 CLI 版本不符时警告 |
| Docker | 示例 Dockerfile 注释:升级需同时换 `marqdo` 与 `ext add` 产物 |
| 样式引号等行为变更 | 写入 CHANGELOG **Breaking / migration** 小节(如 0.3.2 T5) |
---
## 3. 工程改动点
| 改动 | 说明 |
|------|------|
| 插件/Crate 版本可见 | `web_listen` 或 `ext list` 显示 web ABI/包版本 |
| CI | 金样使用仓库内 `plugins/web`;发布技能检查 VSIX/CLI/插件三件套 |
| 研究→设计→路线图 | C0–C4 进 [ext-web roadmap](../../roadmap/ext-web.md),避免只活在私有 fork |
---
## 4. 兼容策略
- 不承诺插件源码级稳定 API;承诺 **`.mq.md` 作者 API** 在小版本尽量兼容,破坏性变更进 CHANGELOG。
- Fork 插件仅作为「官方尚未交付」的临时手段,并在 issue/路线图留归还项。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| 升级说明文档 | 运维按清单升级后 web 金样通过 |
| C0–C2 落地 | 自研后台场景**无需**改 `plugins/web` 源码 |
| `ext list` / 文档 | 能核对版本 |
---
## 6. 过渡期 workaround
锁定 Marqdo 与插件同版本镜像;本地 `MARQDO_EXT` 指向仓库构建产物;定制需求提 issue 对照本目录解决文,避免沉默 fork 漂移。
@@ -0,0 +1,50 @@
# `ext/web` 定制修复:解决文档索引
| | |
|---|---|
| 状态 | **C0–C4 done** |
| 日期 | 2026-09-04 |
| 问题盘点 | [../../research/ext-web-customization-limits.md](../../research/ext-web-customization-limits.md) |
| 相关 | [../ext-web.md](../ext-web.md) · [../ext-web-net.md](../ext-web-net.md) · [../../roadmap/ext-web.md](../../roadmap/ext-web.md) |
对应研究文 §1–§8,每项一份解决文档:**目标 → 作者 API → 插件改动点 → 兼容策略 → 验收**。
实现时优先 **不破坏现有金样**(`tests/ext/web-*`、`examples/web-*`);新能力用显式 opt-in 参数打开。
---
## 文档一览
| # | 主题 | 文档 | 建议优先级 |
|---|------|------|------------|
| 1 | 路由与 `/admin` 前缀可让出 | [01-routes-and-admin-prefix.md](01-routes-and-admin-prefix.md) | P0 |
| 2 | `SHELL_CSS` 可关 / 可层 | [02-shell-css.md](02-shell-css.md) | P1 |
| 3 | 鉴权门禁可配置且行为一致 | [03-auth-gates.md](03-auth-gates.md) | P0 |
| 4 | 样式表作者体验 | [04-stylesheet-authoring.md](04-stylesheet-authoring.md) | P2 |
| 5 | 页面壳与插槽松绑 | [05-page-shell-slots.md](05-page-shell-slots.md) | P1 |
| 6 | 后台 CRUD / 表单边界 | [06-admin-crud-forms.md](06-admin-crud-forms.md) | P3 |
| 7 | 静态资源与脚本生命周期 | [07-assets-script-lifecycle.md](07-assets-script-lifecycle.md) | P2 |
| 8 | 扩展与部署耦合 | [08-ext-deploy-coupling.md](08-ext-deploy-coupling.md) | P3 |
---
## 波次建议(实现用)
| 波次 | 内容 | 依赖 |
|------|------|------|
| **C0** | 可配置 `admin_prefix`;`admin=False` 时不挂内置路由;`login_redirect` / `logout_redirect` | — |
| **C1** | gate:统一未登录策略;精确/前缀匹配;登录页自动放行;默认 gate 不再误伤 `/admin-*` | C0 |
| **C2** | `shell_css=off\|minimal\|full`;主题在壳前或隔离层;可选 `layout=bare` | — |
| **C3** | 样式:校验警告 / `strict`;`page.css` raw;脚本 `defer`/`async`/`version` + `asset_version` | **done** |
| **C4** | 壳:`layout` 预设(C2);条件导航 `when` / `media` | **done** |
路线图入口可在 [ext-web.md](../../roadmap/ext-web.md) 增补「定制波次 C0–C4」行,落地后再改状态。
---
## 产品原则(解法共同约束)
1. **`.mq.md` 仍是真相源** — 能声明的不进隐藏默认;新开关写在 `app` / `page` / `listen` 参数表。
2. **内置 admin 是可选产品**,不是不可替换的内核路由命名空间。
3. **默认行为保持兼容** — 现有 tutorial / 示例零改动仍能跑;新站显式打开定制。
4. **禁止**为单站需求永久硬编码第二套旁路(如永远推荐 `/desk` + JS fetch 登录)。
+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」强绑某一云厂商。
+5 -2
View File
@@ -121,13 +121,16 @@ url = /favicon.ico
| `媒体` | `media` | CSS media |
| `作为` | `as` | preload `as` |
| `跨域` | `crossorigin` | 空 / `anonymous` / `use-credentials` |
| `推迟` | `defer` | 经典 `script` 为真时输出 `defer`(缺省同步,兼容旧站) |
| `异步` | `async` | 为真时输出 `async` |
| `版本` | `version` / `v` | 非空则自动追加 `?v=`;否则用页面/应用 `asset_version` |
**渲染规则**
| `rel` | 输出 |
|-------|------|
| `script` | `<script src="…"></script>`(`type` 非空则写出) |
| `module` | `<script type="module" src="…"></script>` |
| `script` | `<script … src="…"></script>`(可选 `defer`/`async`;`type` 非空则写出) |
| `module` | `<script type="module" src="…"></script>`(浏览器默认 defer 语义) |
| 其他 | `<link rel="…" href="…" …>`(按列附加 `type`/`sizes`/`media`/`as`/`crossorigin`) |
空 `地址` 的行跳过。
+54
View File
@@ -0,0 +1,54 @@
# 调研刷新:2026-09 智能体框架与 Marqdo「代码即文档」
| | |
|---|---|
| 状态 | **Wave B1 Active**(B0/B0.5 已完成;宪法优先) |
| 日期 | 2026-09-04 |
| 前置 | [agent-frameworks-and-marqdo.md](agent-frameworks-and-marqdo.md) · [agent-framework-gaps-after-a4.md](agent-framework-gaps-after-a4.md) |
| 路线 | [ext-agent-optimize.md](../roadmap/ext-agent-optimize.md) |
## 0. 结论
业界框架(LangGraph / Microsoft Agent Framework / CrewAI / OpenAI Agents SDK)在编排、工具、检查点、MCP、评测上继续收敛;**权威真相仍默认在对象图 + transcript + 外置 Store**。
Marqdo 的差异化不是「再做一个 loop」,而是:
1. **代码即文档** — 编排 `.mq.md` = 提示词工作面
2. **调用位置可见** — `agent_call_site`(路径 / 函数 / 行)是一等上下文
3. **文档即知识库(OKF)** — 写回 → promote / solidify → 二次命中 / `llm_free`
Wave B 的目标函数:**证明并硬化上述三点**;产品化示例与评测必须服务差异化,禁止做成无源码上下文的 chatbot demo。
## 1. 业界快照(2026)
| 模式 | 代表 | 状态记忆 | 对 Marqdo |
|------|------|----------|-----------|
| 图 + checkpointer | LangGraph | typed state 持久化 | 续跑应对齐**文件化工作簿**,不造 Python 图 DSL |
| Agent vs Workflow | Microsoft AF | 自主 + 确定性流 | 已有 step / plan,强化即可 |
| 角色班组 | CrewAI | Task 管道 | 多 Agent 低优先;父 CALL + 多工作簿 |
| Handoff + Guardrails | OpenAI Agents SDK | 显式交接 | 可借鉴语义;权威仍在 `.mq.md` |
## 2. 深远影响(开发硬约束)
| 约束 | 含义 |
|------|------|
| 提示不黑盒 | standing / 工具 / 任务写在文件;拼装可审查 |
| 位置感知 | 每次推理注入 call_site;示例与评测可断言 |
| 源码工作面 | `source_brief` + `READ:source\|skill`;禁止藏整份 Skill 进不可见提示 |
| 写回即记忆 | ok/error 槽 + view;非默认向量库 |
| OKF 飞轮 | promote / solidify / hit / llm_free |
| 外置工具 | corpus / MCP 仅证据,`authority=workbook` |
## 3. Wave B 范围
| 波次 | 主题 |
|------|------|
| **B0** | 宪法可见示例 + 上下文管道可读性 + Skill/文档 |
| **B0.5** | 本机 live(`.env` → cflmy)验证「模型用上了文档」 |
| **B1** | 评测锁住 call_site / OKF / 写回 / 预算 |
暂缓:真 MCP、resume/HITL view、kb stats、并行、A2A。
## 4. 开发期 LLM
仓库根目录 `.env`(gitignore):`OPENAI_*` 或 `MARQDO_LLM_*`。模板见 `.env.example`。
@@ -0,0 +1,154 @@
# `ext/web` 定制限制:开发者不易定制的问题盘点
| | |
|---|---|
| 状态 | **调研锁定(踩坑整理)** |
| 日期 | 2026-09-04 |
| 相关 | [ext-web.md](../design/ext-web.md) · [ext-web-net.md](../design/ext-web-net.md) · [web-net-capabilities.md](../design/web-net-capabilities.md) |
| 解决索引 | [../design/ext-web-customization/](../design/ext-web-customization/) |
结合自研后台、样式迁移与响应式改造中的实际踩坑,整理当前 `plugins/web` + `ext/web` 对站点作者的**强占与难定制点**。本文只陈述问题与证据;逐项解法见解决索引。
---
## 0. 一句话
内置 `/admin` 壳、固定鉴权路径、注入式 `SHELL_CSS` 与四区栅格,让「只写 `.mq.md`」的产品路径在**自研后台 / 品牌主题 / 移动端**上反复撞墙;作者被迫旁路前缀 + `!important` + 前端 JS 兜底。
---
## 1. 路由与路径被框架强占
**现象**
- `/admin` 及 `/admin/*` 整段保留,无法 `app.route` 注册自定义页(错误:`route path … is reserved`)。
- `app.重定向` / `redirect` 目标若落在 reserved 前缀,同样被校验拒绝。
- `后台=False`(`admin=False`)后,访问 `/admin/news` 等仍进内置壳,只显示 *Admin is disabled*,**不能**换成自研页。
- 登录/登出硬绑 `/admin/login`、`/admin/logout`;登录成功硬编码 `Redirect::to("/admin")`,无法配置回跳到 `/desk`。
**代码证据**
| 位置 | 行为 |
|------|------|
| `plugins/web/src/lib.rs` → `normalize_route_path` | `/admin`、`/_form`、`/_part`、`/static` 一律 reserved |
| `plugins/web/src/http.rs` | 始终挂 `/admin…` 路由;disabled 时仍 `admin_shell` + 文案 |
| 同文件 `admin_login_post` | 成功跳转写死 `/admin` |
**结果**
自研后台只能用 `/desk` 等旁路前缀;入口与鉴权路径分裂,还要靠前端 JS(`fetch('/admin/login')` 再 `replace('/desk')`)做跳转兜底。
→ 解决:[01-routes-and-admin-prefix.md](../design/ext-web-customization/01-routes-and-admin-prefix.md)
---
## 2. 内置 `SHELL_CSS` 难以彻底覆盖
**现象**
- 每个页面都会注入框架壳样式,例如 `body.has-sidebar { grid-template-columns:14rem 1fr; … }`、默认卡片/表单/侧栏色。
- 规则**无媒体查询**、选择器优先级不低;站点主题选择器不够强时,小屏双列、侧栏占位等「幽灵布局」反复出现。
- 首页有额外 class(如 `has-rail`)时碰巧盖住,其他页没有同类 class 就暴露——表现为「只修了首页」。
- 实务上经常要 `!important` + 更高选择器,与「干净主题层」冲突。
**代码证据**
| 位置 | 行为 |
|------|------|
| `plugins/web/src/render.rs` → `SHELL_CSS` | 常量内联进每个 HTML |
| 同文件壳渲染 | `<style>{SHELL_CSS}{extra}</style>`,主题只能接在后面 |
→ 解决:[02-shell-css.md](../design/ext-web-customization/02-shell-css.md)
---
## 3. 鉴权 / 门禁模型偏固定
**现象**
- 未登录访问受保护路径:对 `/admin*` 会 **303 → 登录页**;对 `/desk` 等自定义路径往往是 **403 HTML**,行为不一致。
- 门禁匹配偏宽:`path.starts_with` / `path_matches` 使 `/desk` 匹配 `/desk/login`,公开登录页易被误伤。
- 默认鉴权挂上 `/admin*` → `admin`;`/admin-publish` 这类名字也会被当成 admin 域(`starts_with("/admin")`)。
- 会话 cookie、CSRF、登录表单字段均固定在框架实现;难换登录 UI 或改成功落地页。
**代码证据**
| 位置 | 行为 |
|------|------|
| `http.rs` → `rbac_middleware` | visitor + `/admin*` → redirect;其它 gate → 403 |
| `http.rs` → `path_matches` | 前缀匹配,无「精确路径 + 子路径排除」DSL |
| `lib.rs` → `web_app_auth` | 默认塞入 `/admin*` gate |
→ 解决:[03-auth-gates.md](../design/ext-web-customization/03-auth-gates.md)
---
## 4. 样式作者体验受限
**现象**
- 样式表是 GFM 表格;含 `/` 的值必须加引号(如 `"1 / 5"`),否则单元格表达式把 `/` 当除法(曾出现 `grid-column` 变成 `0`)。
- `@keyframes`、复杂选择器、多层媒体查询(`min-width` and `max-width`)表达能力有限,装配顺序要小心。
- 主题 CSS 与 `SHELL_CSS` 同页串联,级联顺序不透明,调试成本高。
- 响应式不能指望框架;壳层几乎不提供移动端抽屉/折叠。
→ 解决:[04-stylesheet-authoring.md](../design/ext-web-customization/04-stylesheet-authoring.md)
---
## 5. 页面壳与插槽约定僵硬
**现象**
- 壳结构固定为 `topnav` / `side` / `main` / `foot` 栅格命名区。
- 侧栏一旦装配,`body` 即 `has-sidebar`,套上框架双列;杂志风单列、抽屉必须自己拆布局。
- 组件表驱动导航,难做运行时条件导航(小屏合并顶栏+侧栏),通常再补 `theme.js`。
→ 解决:[05-page-shell-slots.md](../design/ext-web-customization/05-page-shell-slots.md)
---
## 6. 后台 CRUD 与表单能力边界
**现象**
- 内置 admin 是通用表管理,不是产品级 CMS;**关了又占着 `/admin` 路径**(与 §1 叠加)。
- 表单以声明式字段表为主;Markdown 分栏、专栏元数据联动等只能外挂 JS。
- 列表「链接前缀」等约定简单;编辑/新建状态机常靠前端拼(`?id=`、`?new=1`)。
→ 解决:[06-admin-crud-forms.md](../design/ext-web-customization/06-admin-crud-forms.md)
---
## 7. 静态资源与脚本生命周期
**现象**
- 头资源脚本常在 `<head>` **同步**加载;若脚本假设 DOM 已就绪会直接失败(登录页曾因此不跳转)。
- 缓存靠 `?v=` 手动 bump;无构建管线时易出现「改了 JS 浏览器仍用旧文件」。
→ 解决:[07-assets-script-lifecycle.md](../design/ext-web-customization/07-assets-script-lifecycle.md)
---
## 8. 扩展与部署耦合
**现象**
- 能力依赖 web 插件 ABI / Marqdo 版本(如 0.3.2 起的样式引号约定);升级要同步 Docker / 本机二进制。
- 定制若依赖改插件源码(放宽 `/admin` reserved、可配置 login redirect),就脱离「只写 `.mq.md`」的产品路径,维护成本陡增。
→ 解决:[08-ext-deploy-coupling.md](../design/ext-web-customization/08-ext-deploy-coupling.md)
---
## 9. 优先级建议(给实现排期)
| 优先级 | 项 | 理由 |
|--------|-----|------|
| P0 | §1 路由/前缀 + §3 鉴权一致 | 阻塞自研后台产品路径 |
| P1 | §2 SHELL_CSS + §5 壳布局 | 阻塞品牌主题与响应式 |
| P2 | §4 样式作者体验 + §7 脚本生命周期 | 降低日常踩坑,不改架构也能缓解 |
| P3 | §6 CRUD 边界 + §8 部署耦合 | 文档/约定/可选增强为主 |
详细验收与实现切片见解决索引 README。
+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 |
+23 -12
View File
@@ -2,9 +2,9 @@
| | |
|---|---|
| 状态 | **A0–A4 完成**(调研驱动优化闭环;A4:corpus/MCP 证据工具,权威仍是 `.mq.md`) |
| 日期 | 2026-08-28 |
| 调研 | [agent-frameworks-and-marqdo.md](../research/agent-frameworks-and-marqdo.md) · **缺口盘点** [agent-framework-gaps-after-a4.md](../research/agent-framework-gaps-after-a4.md) |
| 状态 | **A0–A4 完成**;**Wave B Active**(宪法优先:代码即文档 / call_site / OKF) |
| 日期 | 2026-09-04 |
| 调研 | [agent-frameworks-and-marqdo.md](../research/agent-frameworks-and-marqdo.md) · [agent-framework-gaps-after-a4.md](../research/agent-framework-gaps-after-a4.md) · **[agent-framework-2026-09.md](../research/agent-framework-2026-09.md)** |
| 设计 | [ext-agent.md](../design/ext-agent.md) · [ext-agent-plan.md](../design/ext-agent-plan.md) · [ext-agent-parent.md](../design/ext-agent-parent.md) · [okf.md](../design/okf.md) |
| 邻近 | [agent-streaming.md](agent-streaming.md) · [okf-near-match.md](okf-near-match.md) |
@@ -13,21 +13,32 @@
## 1. 优化原则(来自调研)
1. **强化差异化,不向 LangChain 薄循环回退**(禁止隐藏 TOOL: 主路径、禁止整文件 LLM 重写工作簿)。
2. 把资源砸在:**工作簿质量、写回、固化、OKF 命中、过程可视**。
2. 把资源砸在:**工作簿质量、写回、固化、OKF 命中、过程可视、源码/调用位置注入**。
3. 外部 RAG/MCP 只作**工具**,不升为权威真相源。
自评四问见调研 §9。A0–A4 之后的缺口与建议分期 **B0–B5** 见 [agent-framework-gaps-after-a4.md](../research/agent-framework-gaps-after-a4.md)。
自评四问见调研 §9。A0–A4 之后的缺口见 [agent-framework-gaps-after-a4.md](../research/agent-framework-gaps-after-a4.md)。**2026-09 Wave B** 锁定见 [agent-framework-2026-09.md](../research/agent-framework-2026-09.md)。
---
## 2. 建议分期(摘要)
## 2. A0–A4(已完成)
| 波次 | 主题 | 验收线索 |
|------|------|----------|
| **A0** | 工作簿补丁 / 固化可靠性 | **done** — 整文件 FIND 护栏;`soft` 仅 miss;decompose `n` 检查;`workbook_solidify` 单测;金样 `agent-workbook-patch-a0`(双 CONTINUE + solidify) |
| **A1** | OKF 复用飞轮(lookup / near / soft_match UX) | **done** — `list_tasks` 含 description/aliases/status/llm_free/hits;`plan` 命中路径暴露 `match`/`score`;soft_match 策展行含 meta;view plan 卡显示 match;金样 `agent-kb-plan-hit`(exact hit + near soft-hit) |
| **A2** | 过程可见(stream + view 过程卡) | **done** — `plan_append_*` / `plan_finish_stream` 始终写入 `events`(SSE 仍仅 `stream=True`);OKF REUSE 记 `decision`;view `plan-card` 渲染过程时间线(跳过 delta);金样断言 `events-ok`;对齐 [agent-streaming.md](agent-streaming.md) |
| **A3** | 上下文预算(源码/Skill 渐进披露) | **done** — `source_brief` / 加深 `skill_brief`;`build_step_context` 默认预算 + `READ:source|skill`;`step max_reads`;父 `READ:skill`;金样 `agent-context-budget-a3` |
| **A4** | 可选:RAG/MCP 工具适配器 | **done** — `corpus_search`(本地语料关键词);`mcp_list_tools` / `mcp_call`(JSON fixture);`authority=workbook`;金样 `agent-tools-rag-a4` |
| **A0** | 工作簿补丁 / 固化可靠性 | **done** — 金样 `agent-workbook-patch-a0` |
| **A1** | OKF 复用飞轮 | **done** — 金样 `agent-kb-plan-hit` |
| **A2** | 过程可见 | **done** — events + view plan 卡 |
| **A3** | 上下文预算 | **done** — `source_brief` / `READ:`;金样 `agent-context-budget-a3` |
| **A4** | RAG/MCP 证据工具 | **done** — 金样 `agent-tools-rag-a4` |
细节与行业对照以调研正文为准;本文件只跟踪 **A0–A4** 实现分期。后续产品化 / 评测 / live MCP 等见 [agent-framework-gaps-after-a4.md](../research/agent-framework-gaps-after-a4.md) §5(草案 B0–B5)。
---
## 3. Wave B(Active — 宪法优先)
| 波次 | 主题 | 状态 |
|------|------|------|
| **B0** | 官方示例演示 call_site/源码/OKF;Skill/文档;上下文管道可读 | **done** |
| **B0.5** | 本机 live(`.env` → 开发模型)验证「模型用上了文档」 | **done**(`AGENT_LIVE` / `AGENT_HARNESS_LIVE`) |
| **B1** | 评测 harness 锁差异化指标(constitution / dump / writeback 遮蔽) | **Active** |
| **B2–B5** | 真 MCP / resume+HITL / stats / 并行 | 暂缓 |
示例:`examples/agent-pong/` · `examples/agent-okf-flywheel/`。
+12
View File
@@ -35,6 +35,18 @@
| **W7** | Cache-Control / 404·500 / 重定向 / sitemap·robots / init 唯一·索引 / HTTPS 反代说明 | **done** |
| **P3** | 审计时间戳 / 外键 / RBAC / 相册 / ETag | **done** |
### 定制波次(规划中)
自研后台 / 主题 / 响应式踩坑见 [ext-web-customization-limits.md](../research/ext-web-customization-limits.md);解法索引 [ext-web-customization/](../design/ext-web-customization/)。
| 波次 | 内容 | 状态 |
|------|------|------|
| **C0** | `admin` 关则不占路径;`admin_prefix` / 登录回跳可配 | **done** |
| **C1** | gate 匹配与未登录策略一致;段边界默认 admin gate | **done** |
| **C2** | `shell_css` + `layout` 松绑 | **done** |
| **C3** | 样式 strict / 脚本 defer·version | **done** |
| **C4** | 条件导航 when/media(layout 见 C2) | **done** |
验收金样:`tests/ext/web-smoke.mq.md`、`tests/ext/web-security-smoke.mq.md`、`tests/ext/web-drivers-smoke.mq.md`、`tests/ext/web-upload-smoke.mq.md`、`tests/ext/web-db-w6-smoke.mq.md`、`tests/ext/web-w7-finish-smoke.mq.md`、`tests/ext/web-p3-smoke.mq.md`、`ext_cli_add_web`。
---
+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)。
- 字节码调试可晚于树遍历一个迭代。
---
+13
View File
@@ -0,0 +1,13 @@
# agent-okf-flywheel(Wave B0)
演示 **文档即知识库(OKF)**:固化工作簿 promote 后,相同 goal 的 `plan` 走 `cache=hit`(`llm_free` 路径),无需再问模型。
```bash
cargo build --release -p marqdo -p marqdo_plugin_agent
export MARQDO_EXT="$PWD/.marqdo-ext"
./target/release/marqdo run examples/agent-okf-flywheel/index.mq.md
```
期望:`promoted` · `hit` · `flywheel-ok`。
见 [okf.md](../../doc/design/okf.md) · [agent-framework-2026-09.md](../../doc/research/agent-framework-2026-09.md)。
+60
View File
@@ -0,0 +1,60 @@
---
title: agent-okf-flywheel (Wave B0)
description: Promote solidified workbook; second plan is cache=hit — document as knowledge base (OKF).
import llm:ext/ai/llm.mq.md
import agent:ext/ai/agent.mq.md
import fs:lib/fs.mq.md
import json:lib/json.mq.md
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
---
# main
OKF flywheel offline: promote → plan same goal → `cache=hit` (no live LLM required for the hit path).
*p = > plugin.native_path name="agent"*
1. `p`
> plugin.load path=`p`
2. *
> print text=no-agent-plugin
> sys.exit code=1
> sys.env_set name="OPENAI_API_KEY" value="offline-okf-dummy"
*model = > llm.llm*
*tools = > json.parse text=[]*
*助手 = > agent.agent model=`model` tools=`tools` standing="offline okf flywheel"*
*kb = ".marqdo/agent-kb-example-flywheel"*
*wb = ".marqdo/agent-runs/example-pong-solid.mq.md"*
*goal = "Reply with exactly the word pong and nothing else."*
*body = "---\ntitle: okf pong\n---\n\n# main\n\n*msg = \"pong\"*\n\n**msg**\n"*
1. > fs.exists path=`kb`
> fs.remove path=`kb`
2. *
---
> fs.write_text path=`wb` text=`body`
*prom = > agent_kb_promote kb_dir=`kb` goal=`goal` workbook=`wb`*
*okp = > json.get value=`prom` key="promoted"*
1. `okp`
> print text=promoted
2. *
> print text=promote-fail
> sys.exit code=1
*out = > `助手`.plan goal=`goal` max_rounds=2 writeback=False kb_dir=`kb` explore_n=0 promote=False*
*cache = > json.get value=`out` key="cache"*
> print text=`cache`
*match = > json.get value=`out` key="match"*
> print text=`match`
*val = > json.get value=`out` key="result"*
> print text=`val`
1. `cache` == "hit"
> print text=flywheel-ok
2. *
> print text=flywheel-miss
> sys.exit code=1
+16
View File
@@ -0,0 +1,16 @@
# agent-pong(Wave B0)
演示 Marqdo 智能体宪法:**代码即文档** — 模型上下文含 **call site** 与本文件 **source**;工具是同文件里的 `## 获取时间`。
```bash
# 仓库根目录
cargo build --release -p marqdo -p marqdo_plugin_agent
export MARQDO_EXT="$PWD/.marqdo-ext" # 或: marqdo ext add agent
# 可选 live:仓库根 `.env` + `AGENT_LIVE=1 marqdo run examples/agent-pong/index.mq.md`
./target/release/marqdo run examples/agent-pong/index.mq.md
```
期望离线输出含:`call-site-ok` · `source-ok` · `tool-in-source-ok`。
配置真实 `.env` 时还会跑一次 `step`(CALL 工具)。
见 [agent-framework-2026-09.md](../../doc/research/agent-framework-2026-09.md)。
+89
View File
@@ -0,0 +1,89 @@
---
title: agent-pong (Wave B0)
description: >-
Constitution demo — call_site + source in step context; optional live CALL via .env.
Code is documentation; tools are ## in this same file.
import llm:ext/ai/llm.mq.md
import agent:ext/ai/agent.mq.md
import json:lib/json.mq.md
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
import time:lib/time.mq.md
---
## 获取时间
Return today's date string (tool visible in source to the model).
*u = > time.now_unix*
**> time.format unix=`u` pattern="%Y-%m-%d"**
# main
*p = > plugin.native_path name="agent"*
1. `p`
> plugin.load path=`p`
2. *
> print text=no-agent-plugin
> sys.exit code=1
> llm.load_env path="../../.env"
`工具表` =
| 工具 |
|------|
| 获取时间 |
*model = > llm.llm*
*助手 = > agent.agent model=`model` tools=`工具表` standing="You are a Marqdo agent. Prefer CALL:获取时间 when the task needs today's date."*
Assert constitution markers in the assembled prompt (call site before how-to-act):
*ctx = > agent.build_step_context agent=`助手` task="What is today's date? Use the tool in this runbook."*
*parts = > split value=`ctx` sep="--- call site ---"*
*n = > len value=`parts`*
1. `n` > 1
> print text=call-site-ok
2. *
> print text=call-site-missing
> sys.exit code=1
*parts2 = > split value=`ctx` sep="--- source (.mq.md) ---"*
*n2 = > len value=`parts2`*
1. `n2` > 1
> print text=source-ok
2. *
> print text=source-missing
> sys.exit code=1
*parts3 = > split value=`ctx` sep="获取时间"*
*n3 = > len value=`parts3`*
1. `n3` > 1
> print text=tool-in-source-ok
2. *
> print text=tool-in-source-missing
> sys.exit code=1
*site = > agent_call_site*
*fn = > json.get value=`site` key="function"*
> print text=`fn`
Optional live step — set env AGENT_LIVE=1 and put keys in repo-root `.env`:
*live = > sys.env_get name="AGENT_LIVE"*
*key = > sys.env_get name="OPENAI_API_KEY"*
1. `live` == "1"
1. `key`
*out = > `助手`.step task="请调用获取时间工具,然后只回复日期字符串。" writeback=False*
*status = > json.get value=`out` key="status"*
> print text=`status`
*tool = > json.get value=`out` key="tool"*
> print text=`tool`
*result = > json.get value=`out` key="result"*
> print text=`result`
2. *
> print text=live-skipped-no-key
2. *
> print text=live-skipped
+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
+45 -18
View File
@@ -17,8 +17,8 @@ import plugin:lib/plugin.mq.md
+ `source_depth`=default
+ `skill_depth`=default
Assemble a readable prompt: standing, task, tools, call site, **budgeted** source + skill, and the act protocol.
Default budgets keep long runbooks from exploding the window; emit `READ:source` / `READ:skill` (Chinese `读取:`) to deepen, then answer or `CALL:`.
Assemble a readable prompt: standing, task, **call site**, tools, **budgeted** source + skill, and the act protocol.
The runbook `.mq.md` is ground truth (code as documentation). Default budgets keep long files from exploding the window; emit `READ:source` / `READ:skill` (Chinese `读取:`) to deepen, then answer or `CALL:`.
*standing = > json.get value=`agent` key="standing"*
1. `standing`
@@ -43,12 +43,39 @@ Default budgets keep long runbooks from exploding the window; emit `READ:source`
*f = > json.get value=`esc` key="f"*
*g = > json.get value=`esc` key="g"*
*p = "You are a Marqdo agent. The runbook source is your ground truth — code is documentation."*
*p = p + a + up + b + task_s + c + tools_s + g + d + site_s + e + src + f + skill*
*p = "You are a Marqdo agent. Code is documentation: this runbook source and call site are your ground truth — not a hidden system prompt."*
*p = p + a + up + b + task_s + d + site_s + c + tools_s + e + src + f + skill + g*
**p**
---
## dump_step_context
+ `agent`
+ `task`=""
+ `source_depth`=default
+ `skill_depth`=default
Inspect what `build_step_context` would send — no LLM. Returns a map: `prompt`, `call_site`, `prompt_chars`, `truncated` (true when budget markers appear). Use for harness / debugging the code-as-doc pipeline.
*prompt = > build_step_context agent=`agent` task=`task` source_depth=`source_depth` skill_depth=`skill_depth`*
*site = > agent_call_site*
*chars = > len value=`prompt`*
*parts = > split value=`prompt` sep="[truncated"*
*n = > len value=`parts`*
*truncated = False*
1. `n` > 1
*truncated = True*
2. *
*_ = 1*
*out = > json.parse text={}*
*out = > json.set map=`out` key="prompt" value=`prompt`*
*out = > json.set map=`out` key="call_site" value=`site`*
*out = > json.set map=`out` key="prompt_chars" value=`chars`*
*out = > json.set map=`out` key="truncated" value=`truncated`*
**out**
---
## extract_tool_name
+ `reply`
@@ -168,9 +195,9 @@ Structured observation for the parent developer-agent: source, named writeback s
- [`slot`](`slots`)
*k = > json.get value=`slot` key="key"*
*body = > json.get value=`slot` key="body"*
1. `k` == ok
1. `k` == "ok"
*last_ok = body*
2. `k` == error
2. `k` == "error"
*last_error = body*
3. *
*_ = 1*
@@ -1436,7 +1463,7 @@ Always append `done` and attach `events` on the result map (process audit even w
1. `trace`
*body = > json.stringify value=`events`*
> writeback.record value=`body` key=trace
> host_writeback_record value=`body` key="trace"
2. *
*_ = 1*
@@ -1578,10 +1605,10 @@ With `stream=True`, the model call uses SSE; `echo=True` prints delta text to st
1. `writeback`
*body = > json.stringify value=`out`*
*st = > json.get value=`out` key="status"*
1. `st` == ok
> writeback.record value=`body` key=ok
1. `st` == "ok"
> host_writeback_record value=`body` key="ok"
2. *
> writeback.record value=`body` key=error
> host_writeback_record value=`body` key="error"
2. *
*_ = 1*
@@ -1684,7 +1711,7 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near`
*events = > plan_append_round events=`events` round=1 workbook=`path` exit_code=`code` result=`child_val` stream=`stream` echo=`echo`*
1. `writeback`
*body = > json.stringify value=`out`*
> writeback.record value=`body` key=ok
> host_writeback_record value=`body` key="ok"
2. *
*_ = 1*
*out = > plan_finish_stream out=`out` events=`events` stream=`stream` trace=`trace` result=`child_val`*
@@ -1741,7 +1768,7 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near`
*events = > plan_append_round events=`events` round=1 workbook=`path` exit_code=`code` result=`child_val` stream=`stream` echo=`echo`*
1. `writeback`
*body = > json.stringify value=`out`*
> writeback.record value=`body` key=ok
> host_writeback_record value=`body` key="ok"
2. *
*_ = 1*
*out = > plan_finish_stream out=`out` events=`events` stream=`stream` trace=`trace` result=`child_val`*
@@ -1805,7 +1832,7 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near`
*events = > plan_append_round events=`events` round=1 workbook=`path` exit_code=`code` result=`child_val` stream=`stream` echo=`echo`*
1. `writeback`
*body = > json.stringify value=`out`*
> writeback.record value=`body` key=ok
> host_writeback_record value=`body` key="ok"
2. *
*_ = 1*
*out = > plan_finish_stream out=`out` events=`events` stream=`stream` trace=`trace` result=`child_val`*
@@ -1883,7 +1910,7 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near`
*out = > json.set map=`out` key="cache" value="bypass"*
1. `writeback`
*body = > json.stringify value=`out`*
> writeback.record value=`body` key=ok
> host_writeback_record value=`body` key="ok"
2. *
*_ = 1*
*out = > plan_finish_stream out=`out` events=`events` stream=`stream` trace=`trace`*
@@ -2022,7 +2049,7 @@ Deterministic success stop (loop engineering): when the child already returned a
*summary = last_reply*
*left = 0*
1. `status` == ok
1. `status` == "ok"
1. `promote`
*prom = > agent_kb_promote kb_dir=`kb_dir` goal=`goal` workbook=`path` tools=`tools`*
*cache = "refreshed"*
@@ -2063,10 +2090,10 @@ Deterministic success stop (loop engineering): when the child already returned a
1. `writeback`
*body = > json.stringify value=`out`*
1. `status` == ok
> writeback.record value=`body` key=ok
1. `status` == "ok"
> host_writeback_record value=`body` key="ok"
2. *
> writeback.record value=`body` key=error
> host_writeback_record value=`body` key="error"
2. *
*_ = 1*
+9 -30
View File
@@ -13,35 +13,14 @@ import json:lib/json.mq.md
## 构建单步上下文
+ `智能体`
+ `任务`
+ `源码深度`=default
+ `技能深度`=default
组装可读提示:站立提示、任务、工具、调用位置、源码、Skill,以及人可见的行动约定。
组装可读提示:站立提示、任务、**调用位置**、工具、**预算**源码 + Skill,以及人可见的行动约定。
编排 `.mq.md` 即真相源(代码即文档)。默认预算防爆窗;可先 `读取:source|skill` 加深再答或 `调用:`。
实现委托 `agent.build_step_context`(与英文版同源)。
*standing = > json.get value=`智能体` key="standing"*
1. `standing`
*up = standing*
2. *
*up = 空*
*tools = > json.get value=`智能体` key="tools"*
*tools_s = > agent_format_tools tools=`tools`*
*src = > agent_module_source*
*site = > agent_call_site*
*site_s = > json.stringify value=`site`*
*skill = > agent_marqdo_skill*
*task_s = > json.stringify value=`任务`*
*esc = > json.parse text={"a":"\n\n--- standing ---\n","b":"\n\n--- task ---\n","c":"\n\n--- tools ---\n","d":"\n\n--- call site ---\n","e":"\n\n--- source (.mq.md) ---\n","f":"\n\n--- marqdo skill ---\n","g":"\n\n--- how to act ---\nTools are ## functions in the source above. To call one, reply with exactly one line: CALL:<name>\n(Chinese ok: 调用:<name>)\nOtherwise reply with the final answer only.\nTools run via Marqdo subtask (spawn fn / wait).\n"}*
*a = > json.get value=`esc` key="a"*
*b = > json.get value=`esc` key="b"*
*c = > json.get value=`esc` key="c"*
*d = > json.get value=`esc` key="d"*
*e = > json.get value=`esc` key="e"*
*f = > json.get value=`esc` key="f"*
*g = > json.get value=`esc` key="g"*
*p = "You are a Marqdo agent. The runbook source is your ground truth — code is documentation."*
*p = p + a + up + b + task_s + c + tools_s + g + d + site_s + e + src + f + skill*
**p**
**> agent.build_step_context agent=`智能体` task=`任务` source_depth=`源码深度` skill_depth=`技能深度`**
---
@@ -195,10 +174,10 @@ import json:lib/json.mq.md
1. `写回`
*body = > json.stringify value=`out`*
*st = > json.get value=`out` key="status"*
1. `st` == ok
> 自写回.写回 值=`body` 键=ok
1. `st` == "ok"
> host_writeback_record value=`body` key="ok"
2. *
> 自写回.写回 值=`body` 键=error
> host_writeback_record value=`body` key="error"
2. *
*_ = 1*
+187 -12
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
@@ -20,15 +21,22 @@ Load the ABI v2 `web` plugin once.
## make_style
+ `name`=""
+ `table`
+ `strict`=False
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 and becomes a numeric cell — default mode warns, `strict=True` errors.
For complex themes prefer `page.css` (raw string, no table eval) or an external
`static/*.css` via `page.head`. Styles stay as data tables, `make_style` turns
them into CSS — 样式即数据、装配即函数.
> ensure_plugin
**> web_style name=`name` table=`table`**
**> web_style name=`name` table=`table` strict=`strict`**
## make_images
+ `table`
@@ -50,17 +58,168 @@ 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`=""
+ `shell_css`=None
+ `layout`=None
+ `asset_version`=None
> ensure_plugin
**> web_page_new title=`title` intro=`intro`**
**> web_page_new title=`title` intro=`intro` shell_css=`shell_css` layout=`layout` asset_version=`asset_version`**
## shell_css
+ `mode`=full
Framework shell CSS mode for this page: `full` (default), `minimal` (vars only), or `off`/`none`.
*`out` = > table.put in=`self` at="shell_css" value=mode*
**out**
## layout
+ `layout`=sidebar
Page chrome layout: `sidebar` (default when a side slot exists), `stacked` (single column; no `has-sidebar` grid), `bare` (main only), or `rail`.
*`out` = > table.put in=`self` at="layout" value=layout*
**out**
## asset_version
+ `version`=""
Default `?v=` bump for head scripts/styles that omit a per-row `version` column.
*`out` = > table.put in=`self` at="asset_version" value=version*
**out**
## compose_components
+ `components`
Assemble nav / sidebar / footer from a page table (`|组件|样式|` or `|src|style|`).
Nav bind tables may include optional `媒体`/`media` (responsive show) and `当`/`when`
(`auth` / `guest` / `hide`) columns — see C4 conditional nav.
**> web_compose_components page=`self` components=`components`**
@@ -97,8 +256,9 @@ an `href`/`链接` field become `<a href="{prefix}{href}">`.
## css
+ `css`
Append a raw CSS string to the page's stylesheet (`styles_css`). Use it to ship
a hand-written theme alongside the assembled shell.
Append a **raw** CSS string to the page's stylesheet (`styles_css`). Skips table-cell
expression evaluation — use for themes with `/`, `@keyframes`, or long media queries.
Hand-written theme alongside the assembled shell; or link `static/theme.css` via `head`.
**> web_page_css page=`self` css=`css`**
@@ -120,7 +280,7 @@ SEO / OpenGraph metadata as a data table (`|key|value|`). Keys such as `title`,
## head
+ `table`
Assemble `<head>` resources from a GFM table (`|rel|href|type|sizes|media|as|crossorigin|` or ZH `|关系|地址|类型|…|`). `rel=script` / `module` become `<script>`; other rows become `<link>`. Merges with any existing `head` on the page.
Assemble `<head>` resources from a GFM table (`|rel|href|type|sizes|media|as|crossorigin|defer|async|version|` or ZH `|关系|地址|…|推迟|异步|版本|`). `rel=script` / `module` become `<script>`; other rows become `<link>`. Classic scripts emit `defer` / `async` only when those columns are true (compat: missing `defer` stays synchronous). Non-empty `version` appends `?v=`; else page/app `asset_version` is used. Merges with any existing `head` on the page.
**> web_page_head page=`self` table=`table`**
@@ -439,9 +599,17 @@ Field table + rules table; submit writes through `# db`.
+ `admin`=False
+ `host`=127.0.0.1
+ `port`=18081
+ `admin_prefix`=/admin
+ `login_redirect`=None
+ `logout_redirect`=None
+ `shell_css`=None
+ `layout`=None
+ `asset_version`=None
Construct an app. `admin=True` mounts the built-in CRUD UI under `admin_prefix` (default `/admin`). When `admin=False`, that prefix is **not** reserved — you may `route` your own pages there. Optional `login_redirect` / `logout_redirect` override post-auth landing. Optional `shell_css` / `layout` / `asset_version` become defaults for pages that do not set their own (see `page.shell_css` / `page.layout` / `page.asset_version`).
> ensure_plugin
**> web_app_new page=`page` db=`db` admin=`admin` host=`host` port=`port`**
**> web_app_new page=`page` db=`db` admin=`admin` host=`host` port=`port` admin_prefix=`admin_prefix` login_redirect=`login_redirect` logout_redirect=`logout_redirect` shell_css=`shell_css` layout=`layout` asset_version=`asset_version`**
## route
+ `path`
@@ -510,18 +678,25 @@ Register a WebSocket endpoint at `path` (e.g. `/live`). `mode` is `echo` (defaul
## auth
+ `users`
+ `session_ttl`=3600
+ `admin_prefix`=None
+ `login_redirect`=None
+ `logout_redirect`=None
+ `login_path`=None
Keep the app's `admin=True`, and gate `/admin*` behind a login page. `users` is an admin-users table (`|username|password|` / `|用户名|密码|`); optional `role` / `角色` column (`admin` / `author` / `visitor`). Unauthenticated requests redirect to `/admin/login`. Registers a default gate `/admin*` → `admin`.
Keep the app's `admin=True`, and gate `{admin_prefix}` (segment-boundary prefix) behind a login page (default `/admin`). Unauthenticated requests **redirect** to `login_path` (default `{admin_prefix}/login`, auto-excluded). Does **not** match `/admin-publish`-style siblings.
**> web_app_auth app=`self` users=`users` session_ttl=`session_ttl`**
**> web_app_auth app=`self` users=`users` session_ttl=`session_ttl` admin_prefix=`admin_prefix` login_redirect=`login_redirect` logout_redirect=`logout_redirect` login_path=`login_path`**
## gate
+ `path`
+ `roles`=admin
+ `match`=prefix
+ `on_deny`=forbid
+ `exclude`=None
Require one of `roles` (CSV) for `path` (prefix or `path*`). Anonymous sessions count as `visitor`.
Require one of `roles` (CSV) for `path`. `match=prefix` uses segment boundaries; `exact` is equality. Trailing `*` on `path` means prefix. `on_deny=redirect` sends visitors to `login_path` (with `?next=`); `forbid` returns 403. `exclude` is CSV or list of open paths.
**> web_app_gate app=`self` path=`path` roles=`roles`**
**> web_app_gate app=`self` path=`path` roles=`roles` match=`match` on_deny=`on_deny` exclude=`exclude`**
## gallery
+ `path`=/gallery
+177 -9
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
---
## 确保插件
@@ -20,14 +21,19 @@ import sys:lib/sys.mq.md
## 样式装配
+ `名`=""
+ `表`
+ `严格`=False
把 GFM 样式表装配成一段 CSS 文本。支持两种表形:
`|选择器|属性|值|` 规则行(选择器任意,同一选择器多行合并成一条规则;
加 `|媒体|` 列即可分组进 `@media` 块),或 `|属性|值|` 属性行(按 `.名 { … }` 包裹)。
选择器以 `@keyframes 名` 开头时输出关键帧块(`属性` 为停点 `from`/`to`/`N%`,
`值` 写 `opacity: 0` 等声明;也可用 `@keyframes 名 from` + 普通属性/值)。
含 `/` 的 CSS 值请加引号(如 `"16/9"`、`"1 / 5"`);裸 `1 / 5` 会按表达式除法变成数字单元格——默认告警,`严格=真` 时报错。
复杂主题优先 `页面.样式`(原始 CSS 字符串,不经表求值)或外链 `static/*.css` + `页面.头装配`。
样式即数据、装配即函数 —— 主题模块据此把样式表拼成完整样式表。
> 确保插件
**> web_style name=`名` table=`表`**
**> web_style name=`名` table=`表` strict=`严格`**
## 图片装配
+ `表`
@@ -47,12 +53,159 @@ 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**
# 页面
+ `标题`="站点"
+ `引言`=""
+ `壳样式`=None
+ `布局`=None
+ `资源版本`=None
> 确保插件
**> web_page_new title=`标题` intro=`引言`**
**> web_page_new title=`标题` intro=`引言` shell_css=`壳样式` layout=`布局` asset_version=`资源版本`**
## 壳样式
+ `模式`=full
框架壳 CSS:`full`(默认)/ `minimal`(仅变量)/ `off`。
*`out` = > table.put in=`自` at="shell_css" value=模式*
**out**
## 布局
+ `布局`=sidebar
页面壳:`sidebar`(有侧栏时默认双列)/ `stacked`(单列、不加 has-sidebar)/ `bare`(仅 main)/ `rail`。
*`out` = > table.put in=`自` at="layout" value=布局*
**out**
## 资源版本
+ `版本`=""
为未写 `版本` 列的 head 脚本/样式统一追加 `?v=`。
*`out` = > table.put in=`自` at="asset_version" value=版本*
**out**
## 组件装配
+ `组件`
@@ -88,7 +241,7 @@ import sys:lib/sys.mq.md
## 样式
+ `样式`
把一段手写 CSS 字符串追加到页面样式表(`styles_css`),用于在装配好的外壳上叠加自定义主题。
把一段**原始** CSS 字符串追加到页面样式表(`styles_css`),不经表单元格表达式求值——适合含 `/`、`@keyframes` 或长 media 的主题。也可外链 `static/theme.css` 再经 `头装配`。
**> web_page_css page=`self` css=`样式`**
@@ -109,7 +262,7 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c
## 头装配
+ `表`
把 Head 资源表(`|关系|地址|类型|尺寸|媒体|作为|跨域|`)挂到页面的 `head`。`关系=script` / `module` 生成 `<script>`,其余生成 `<link>`。与已有 `head` 合并。
把 Head 资源表(`|关系|地址|类型|尺寸|媒体|作为|跨域|推迟|异步|版本|`)挂到页面的 `head`。`关系=script` / `module` 生成 `<script>`,其余生成 `<link>`。经典脚本仅在 `推迟`/`异步` 为真时输出对应属性(缺省仍同步,兼容旧站)。非空 `版本` 追加 `?v=`,否则用页面/应用的 `资源版本`。与已有 `head` 合并。
**> web_page_head page=`self` table=`表`**
@@ -421,9 +574,17 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c
+ `后台`=False
+ `主机`=127.0.0.1
+ `端口`=18081
+ `后台前缀`=/admin
+ `登录回跳`=None
+ `登出回跳`=None
+ `壳样式`=None
+ `布局`=None
+ `资源版本`=None
构造应用。`后台=真` 时在 `后台前缀`(默认 `/admin`)挂载内置 CRUD。`后台=假` 时该前缀**不再保留**,可自行 `路由` 到 `/admin…`。可选 `登录回跳` / `登出回跳`。可选 `壳样式` / `布局` / `资源版本` 作为未自设页面的默认(见 `页面.壳样式` / `页面.布局` / `页面.资源版本`)。
> 确保插件
**> web_app_new page=`页面` db=`数据库` admin=`后台` host=`主机` port=`端口`**
**> web_app_new page=`页面` db=`数据库` admin=`后台` host=`主机` port=`端口` admin_prefix=`后台前缀` login_redirect=`登录回跳` logout_redirect=`登出回跳` shell_css=`壳样式` layout=`布局` asset_version=`资源版本`**
## 路由
+ `路径`
@@ -487,18 +648,25 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c
## 鉴权
+ `用户表`
+ `会话时长`=3600
+ `后台前缀`=None
+ `登录回跳`=None
+ `登出回跳`=None
+ `登录路径`=None
在保持 `后台=真` 的同时,为 `/admin*` 加登录门禁。`用户表` 为 `|用户名|密码|`(可选 `角色`:`admin`/`author`/`visitor`);未登录重定向到 `/admin/login`。默认登记门禁 `/admin*` → `admin`。
在保持 `后台=真` 的同时,为 `{后台前缀}` 加**段边界**前缀门禁(默认 `/admin`)。未登录 **重定向** 到 `登录路径`(默认 `{前缀}/login`,自动排除)。不会匹配 `/admin-publish` 这类旁系路径。
**> web_app_auth app=`self` users=`用户表` session_ttl=`会话时长`**
**> web_app_auth app=`self` users=`用户表` session_ttl=`会话时长` admin_prefix=`后台前缀` login_redirect=`登录回跳` logout_redirect=`登出回跳` login_path=`登录路径`**
## 门禁
+ `路径`
+ `角色`=admin
+ `匹配`=prefix
+ `拒绝`=forbid
+ `排除`=None
要求会话角色落在 `角色`(CSV)之一才可访问 `路径`(前缀或 `路径*`)。匿名视为 `visitor`。
要求会话角色落在 `角色`(CSV)之一。`匹配=prefix` 为段边界前缀;`exact` 为精确路径。路径末尾 `*` 亦表示前缀。`拒绝=redirect` 时访客跳转登录页(带 `?next=`);`forbid` 返回 403。`排除` 为 CSV/列表(如登录页)。
**> web_app_gate app=`self` path=`路径` roles=`角色`**
**> web_app_gate app=`self` path=`路径` roles=`角色` match=`匹配` on_deny=`拒绝` exclude=`排除`**
## 相册
+ `路径`=/gallery
+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**
+122 -5
View File
@@ -15,6 +15,11 @@ pub struct HeadLink {
pub media: String,
pub as_: String,
pub crossorigin: String,
/// When `Some(true)`, emit `defer` on classic scripts (not modules).
pub defer: Option<bool>,
pub async_: bool,
/// Query `?v=` bump for cache busting.
pub version: String,
}
#[derive(Clone, Debug)]
@@ -38,6 +43,37 @@ fn pick<'a>(m: &'a Map<String, Value>, keys: &[&str]) -> Option<&'a Value> {
keys.iter().find_map(|k| m.get(*k))
}
fn cell_boolish(v: &Value) -> Option<bool> {
match v {
Value::Bool(b) => Some(*b),
Value::Number(n) => Some(n.as_i64().unwrap_or(0) != 0),
Value::String(s) => {
let s = s.trim();
if s.is_empty() {
return None;
}
if matches!(
s,
"1" | "true" | "True" | "yes" | "on" | "真" | "是"
) {
Some(true)
} else if matches!(
s,
"0" | "false" | "False" | "no" | "off" | "假" | "否"
) {
Some(false)
} else {
None
}
}
_ => None,
}
}
fn row_bool(m: &Map<String, Value>, keys: &[&str]) -> Option<bool> {
pick(m, keys).and_then(cell_boolish)
}
fn row_str(m: &Map<String, Value>, keys: &[&str]) -> String {
pick(m, keys)
.map(|v| normalize_ref(&cell_str(v)))
@@ -46,6 +82,19 @@ fn row_str(m: &Map<String, Value>, keys: &[&str]) -> String {
.to_string()
}
/// Append `?v=` / `&v=` for cache busting.
pub fn href_with_version(href: &str, version: &str) -> String {
let version = version.trim();
if version.is_empty() {
return href.to_string();
}
if href.contains('?') {
format!("{href}&v={version}")
} else {
format!("{href}?v={version}")
}
}
fn esc(s: &str) -> String {
s.replace('&', "&amp;")
.replace('<', "&lt;")
@@ -142,6 +191,9 @@ pub fn as_head_links(table: &Value) -> Vec<HeadLink> {
media: row_str(&m, &["媒体", "media", "Media"]),
as_: row_str(&m, &["作为", "as", "As"]),
crossorigin: row_str(&m, &["跨域", "crossorigin", "crossOrigin"]),
defer: row_bool(&m, &["推迟", "defer", "Defer"]),
async_: row_bool(&m, &["异步", "async", "Async"]).unwrap_or(false),
version: row_str(&m, &["版本", "version", "Version", "v"]),
});
}
out
@@ -152,7 +204,7 @@ pub fn head_links_to_json(links: &[HeadLink]) -> Value {
links
.iter()
.map(|l| {
json!({
let mut o = json!({
"rel": l.rel,
"href": l.href,
"type": l.type_,
@@ -160,7 +212,15 @@ pub fn head_links_to_json(links: &[HeadLink]) -> Value {
"media": l.media,
"as": l.as_,
"crossorigin": l.crossorigin,
})
"async": l.async_,
"version": l.version,
});
if let Some(d) = l.defer {
o.as_object_mut()
.unwrap()
.insert("defer".into(), json!(d));
}
o
})
.collect(),
)
@@ -187,6 +247,9 @@ pub fn head_links_from_json(v: &Value) -> Vec<HeadLink> {
media: row_str(m, &["media", "媒体"]),
as_: row_str(m, &["as", "作为"]),
crossorigin: row_str(m, &["crossorigin", "跨域"]),
defer: row_bool(m, &["defer", "推迟"]),
async_: row_bool(m, &["async", "异步"]).unwrap_or(false),
version: row_str(m, &["version", "版本", "v"]),
});
}
out
@@ -194,24 +257,42 @@ pub fn head_links_from_json(v: &Value) -> Vec<HeadLink> {
/// Render HeadLink list to HTML (link / script tags).
pub fn render_head_links(links: &[HeadLink]) -> String {
render_head_links_with_version(links, "")
}
pub fn render_head_links_with_version(links: &[HeadLink], asset_version: &str) -> String {
let mut s = String::new();
for l in links {
let rel = l.rel.trim().to_ascii_lowercase();
let ver = if !l.version.trim().is_empty() {
l.version.as_str()
} else {
asset_version
};
let href = href_with_version(&l.href, ver);
if rel == "script" || rel == "module" {
let mut tag = String::from("<script");
if rel == "module" || l.type_ == "module" {
let is_module = rel == "module" || l.type_ == "module";
if is_module {
tag.push_str(" type=\"module\"");
} else if !l.type_.is_empty() {
tag.push_str(&format!(" type=\"{}\"", esc(&l.type_)));
}
// Modules are deferred by browsers; classic scripts honor explicit defer.
if !is_module && l.defer == Some(true) {
tag.push_str(" defer");
}
if l.async_ {
tag.push_str(" async");
}
if !l.crossorigin.is_empty() {
tag.push_str(&format!(" crossorigin=\"{}\"", esc(&l.crossorigin)));
}
tag.push_str(&format!(" src=\"{}\"></script>", esc(&l.href)));
tag.push_str(&format!(" src=\"{}\"></script>", esc(&href)));
s.push_str(&tag);
continue;
}
let mut tag = format!("<link rel=\"{}\" href=\"{}\"", esc(&l.rel), esc(&l.href));
let mut tag = format!("<link rel=\"{}\" href=\"{}\"", esc(&l.rel), esc(&href));
if !l.type_.is_empty() {
tag.push_str(&format!(" type=\"{}\"", esc(&l.type_)));
}
@@ -295,6 +376,9 @@ pub fn normalize_icons(table: &Value) -> (Value, Vec<HeadLink>, Vec<IconRoute>)
media: String::new(),
as_: String::new(),
crossorigin: String::new(),
defer: None,
async_: false,
version: String::new(),
});
}
@@ -347,6 +431,9 @@ pub fn normalize_icons(table: &Value) -> (Value, Vec<HeadLink>, Vec<IconRoute>)
media: String::new(),
as_: String::new(),
crossorigin: String::new(),
defer: None,
async_: false,
version: String::new(),
},
);
}
@@ -369,6 +456,9 @@ pub fn convention_favicon(static_dir: &Path) -> Option<(Vec<HeadLink>, Vec<IconR
media: String::new(),
as_: String::new(),
crossorigin: String::new(),
defer: None,
async_: false,
version: String::new(),
}];
let routes = vec![IconRoute {
url: "/favicon.ico".into(),
@@ -486,5 +576,32 @@ mod tests {
let h = make_head_html(&t);
assert!(h.contains("rel=\"icon\""));
assert!(h.contains("<script src=\"/static/a.js\"></script>"));
assert!(!h.contains(" defer"), "{h}");
}
#[test]
fn head_script_defer_async_version() {
let t = json!([
{"关系": "script", "地址": "/static/a.js", "推迟": true, "版本": "3"},
{"关系": "module", "地址": "/static/b.js", "版本": "9"},
{"关系": "stylesheet", "地址": "/static/t.css", "版本": "1"},
]);
let h = make_head_html(&t);
assert!(h.contains("<script defer src=\"/static/a.js?v=3\"></script>"), "{h}");
assert!(h.contains("type=\"module\""), "{h}");
assert!(h.contains("src=\"/static/b.js?v=9\""), "{h}");
assert!(h.contains("href=\"/static/t.css?v=1\""), "{h}");
}
#[test]
fn head_asset_version_fallback() {
let links = as_head_links(&json!([
{"关系": "script", "地址": "/static/a.js", "推迟": "真"},
]));
let h = render_head_links_with_version(&links, "2026-09-04");
assert!(
h.contains("<script defer src=\"/static/a.js?v=2026-09-04\"></script>"),
"{h}"
);
}
}
+8 -4
View File
@@ -193,11 +193,13 @@ fn sql_type_to_input(sql_type: &str, name: &str) -> &'static str {
}
/// Build a form handle from live SQLite schema (admin new/edit).
/// `admin_prefix` is the mount root (default `/admin`), without trailing slash.
pub fn from_schema(
db_url: &str,
table: &str,
action: &str,
id: Option<&str>,
admin_prefix: &str,
) -> Result<Value, String> {
let action = match action {
"update" | "更新" => "update",
@@ -223,22 +225,24 @@ pub fn from_schema(
"pk": c.pk,
}));
}
let base = admin_prefix.trim_end_matches('/');
let table_href = format!("{base}/{table}");
let mut form = form_new(Some(table), action, id);
if let Some(obj) = form.as_object_mut() {
obj.insert("fields".into(), Value::Array(fields));
obj.insert("redirect".into(), json!(format!("/admin/{table}")));
obj.insert("redirect".into(), json!(&table_href));
if action == "insert" {
obj.insert("action_url".into(), json!(format!("/admin/{table}/new")));
obj.insert("action_url".into(), json!(format!("{table_href}/new")));
obj.insert("title".into(), json!(format!("New {table}")));
} else if let Some(i) = id {
obj.insert(
"action_url".into(),
json!(format!("/admin/{table}/{i}/edit")),
json!(format!("{table_href}/{i}/edit")),
);
obj.insert("title".into(), json!(format!("Edit {table} #{i}")));
obj.insert("id".into(), json!(i));
}
obj.insert("cancel_href".into(), json!(format!("/admin/{table}")));
obj.insert("cancel_href".into(), json!(&table_href));
}
Ok(form)
}
+332 -81
View File
@@ -32,6 +32,24 @@ fn with_site_head(base: &Value, site_head: &[crate::assets::HeadLink]) -> Value
page
}
/// Stamp session login state so nav `when=auth|guest` can filter at render time.
fn with_nav_auth(base: &Value, cookie: Option<&str>) -> Value {
let mut page = base.clone();
let Some(obj) = page.as_object_mut() else {
return page;
};
let user = session::session_id_from_cookie(cookie)
.and_then(|sid| session::session_get(&sid, "username"));
let logged_in = user.is_some();
obj.insert("_logged_in".into(), json!(logged_in));
if let Some(u) = user {
obj.insert("_nav_user".into(), u);
} else {
obj.remove("_nav_user");
}
page
}
fn serve_icon_file(path: PathBuf, content_type: String) -> Response {
match std::fs::read(&path) {
Ok(bytes) => {
@@ -69,11 +87,115 @@ pub struct DownloadRoute {
pub disposition: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GateMatch {
Exact,
/// Segment-boundary prefix: `/desk` matches `/desk` and `/desk/…`, not `/desk-x`.
Prefix,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OnDeny {
Redirect,
Forbid,
}
#[derive(Clone, Debug)]
pub struct Gate {
pub path: String,
pub roles: Vec<String>,
pub match_mode: GateMatch,
pub on_deny: OnDeny,
pub exclude: Vec<String>,
}
impl Gate {
pub fn from_json(g: &Value) -> Option<Self> {
let raw = g.get("path").and_then(|v| v.as_str())?.trim();
if raw.is_empty() {
return None;
}
let starred = raw.ends_with('*');
let mut path = raw.trim_end_matches('*').trim_end_matches('/').to_string();
if path.is_empty() {
path = "/".into();
} else if !path.starts_with('/') {
path = format!("/{path}");
}
let roles = match g.get("roles") {
Some(Value::Array(a)) => a
.iter()
.filter_map(|v| v.as_str().map(|s| s.to_ascii_lowercase()))
.collect(),
Some(Value::String(s)) => session::parse_roles_csv(s),
_ => vec!["admin".into()],
};
let match_s = g
.get("match")
.or_else(|| g.get("匹配"))
.and_then(|v| v.as_str())
.unwrap_or("")
.to_ascii_lowercase();
let match_mode = match match_s.as_str() {
"exact" | "精确" => GateMatch::Exact,
"prefix" | "前缀" => GateMatch::Prefix,
_ if starred => GateMatch::Prefix,
_ => GateMatch::Prefix,
};
let deny_s = g
.get("on_deny")
.or_else(|| g.get("拒绝"))
.and_then(|v| v.as_str())
.unwrap_or("")
.to_ascii_lowercase();
let on_deny = match deny_s.as_str() {
"redirect" | "重定向" | "login" => OnDeny::Redirect,
"forbid" | "禁止" | "403" => OnDeny::Forbid,
_ => OnDeny::Forbid,
};
let mut exclude = Vec::new();
if let Some(Value::Array(a)) = g.get("exclude").or_else(|| g.get("排除")) {
for v in a {
if let Some(s) = v.as_str() {
let s = s.trim();
if !s.is_empty() {
exclude.push(s.to_string());
}
}
}
} else if let Some(s) = g
.get("exclude")
.or_else(|| g.get("排除"))
.and_then(|v| v.as_str())
{
for part in s.split(',') {
let part = part.trim();
if !part.is_empty() {
exclude.push(part.to_string());
}
}
}
Some(Gate {
path,
roles,
match_mode,
on_deny,
exclude,
})
}
}
#[derive(Clone)]
pub struct AppState {
page: Value,
pub db_url: Option<String>,
admin: bool,
/// Built-in admin mount root (e.g. `/admin` or `/desk`); unused when `admin` is false.
admin_prefix: String,
/// Login form URL (GET/POST); may differ from `{admin_prefix}/login`.
login_path: String,
login_redirect: String,
logout_redirect: String,
forms: HashMap<String, Value>,
/// Page that owns an embedded form (for re-render on validation errors).
form_owners: HashMap<String, Value>,
@@ -90,6 +212,22 @@ pub struct AppState {
site_head: Vec<crate::assets::HeadLink>,
}
impl AppState {
fn ap(&self) -> &str {
self.admin_prefix.trim_end_matches('/')
}
fn admin_href(&self, rest: &str) -> String {
let p = self.ap();
let rest = rest.trim().trim_start_matches('/');
if rest.is_empty() {
p.to_string()
} else {
format!("{p}/{rest}")
}
}
}
fn collect_page_forms(
page: &Value,
forms: &mut HashMap<String, Value>,
@@ -118,6 +256,10 @@ pub fn listen(
host: &str,
port: u16,
admin: bool,
admin_prefix: &str,
login_path: &str,
login_redirect: &str,
logout_redirect: &str,
mut forms: HashMap<String, Value>,
routes: HashMap<String, Value>,
static_dir: Option<PathBuf>,
@@ -134,7 +276,7 @@ pub fn listen(
robots_body: Option<String>,
page_404: Option<Value>,
page_500: Option<Value>,
gates: Vec<(String, Vec<String>)>,
gates: Vec<Gate>,
gallery_routes: HashMap<String, Value>,
middleware: &Middleware,
mut site_head: Vec<crate::assets::HeadLink>,
@@ -166,10 +308,31 @@ pub fn listen(
// Resolve relative icon paths: try as-is absolute, else leave for entry_dir resolve in lib.
// (Absolute paths preferred; relative already joined in web_listen.)
let admin_prefix = {
let mut p = admin_prefix.trim().to_string();
if !p.starts_with('/') {
p = format!("/{p}");
}
while p.len() > 1 && p.ends_with('/') {
p.pop();
}
p
};
let state = Arc::new(AppState {
page: page.clone(),
db_url: db_url.map(|s| s.to_string()),
admin,
admin_prefix: admin_prefix.clone(),
login_path: {
let lp = login_path.trim();
if lp.is_empty() {
format!("{}/login", admin_prefix.trim_end_matches('/'))
} else {
lp.to_string()
}
},
login_redirect: login_redirect.to_string(),
logout_redirect: logout_redirect.to_string(),
forms,
form_owners,
auth_users,
@@ -185,17 +348,23 @@ pub fn listen(
let mut app = Router::new()
.route("/", get(home))
.route("/_part/{id}", get(home_part))
.route("/_form/{id}", get(form_get).post(form_post))
.route("/admin", get(admin_home))
.route("/admin/login", get(admin_login_get).post(admin_login_post))
.route("/admin/logout", get(admin_logout))
.route("/admin/{table}", get(admin_table))
.route("/admin/{table}/new", get(admin_new_get).post(admin_new_post))
.route(
"/admin/{table}/{id}/edit",
get(admin_edit_get).post(admin_edit_post),
)
.route("/admin/{table}/{id}/delete", get(admin_delete));
.route("/_form/{id}", get(form_get).post(form_post));
// Built-in admin only when enabled — otherwise `/admin…` is free for author routes.
if admin {
let admin_routes = Router::new()
.route("/", get(admin_home))
.route("/login", get(admin_login_get).post(admin_login_post))
.route("/logout", get(admin_logout))
.route("/{table}", get(admin_table))
.route("/{table}/new", get(admin_new_get).post(admin_new_post))
.route(
"/{table}/{id}/edit",
get(admin_edit_get).post(admin_edit_post),
)
.route("/{table}/{id}/delete", get(admin_delete));
app = app.nest(&admin_prefix, admin_routes);
}
// Register each author route as an exact GET path + `{path}/_part/{id}`.
// Paths containing `{param}` become dynamic routes (e.g. `/post/{slug}`);
@@ -214,6 +383,8 @@ pub fn listen(
inject_params(&mut p, &params);
let p = with_site_head(&p, &st.site_head);
let (_, csrf, set_cookie) = resolve_session(&headers);
let cookie = cookie_from_headers(&headers);
let p = with_nav_auth(&p, cookie);
let mut resp = Html(render::render_page(&p, st.db_url.as_deref(), Some(&csrf))).into_response();
append_set_cookie(&mut resp, set_cookie);
resp
@@ -237,6 +408,7 @@ pub fn listen(
get(async move |State(st): State<Arc<AppState>>, headers: axum::http::HeaderMap| {
let (_, csrf, set_cookie) = resolve_session(&headers);
let p = with_site_head(&page_for_render, &st.site_head);
let p = with_nav_auth(&p, cookie_from_headers(&headers));
let mut resp = Html(render::render_page(&p, st.db_url.as_deref(), Some(&csrf)))
.into_response();
append_set_cookie(&mut resp, set_cookie);
@@ -434,10 +606,12 @@ pub fn listen(
let app = crate::middleware::apply(app, middleware);
let app = if !gates.is_empty() {
let gates_for_mw = gates.clone();
let login_path_for_mw = state.login_path.clone();
app.layer(axum::middleware::from_fn(
move |req: axum::http::Request<axum::body::Body>, next: axum::middleware::Next| {
let gates = gates_for_mw.clone();
async move { rbac_middleware(gates, req, next).await }
let login_path = login_path_for_mw.clone();
async move { rbac_middleware(gates, login_path, req, next).await }
},
))
} else {
@@ -515,6 +689,7 @@ fn rss_feed(st: &AppState, _path: &str, cfg: &Value) -> Response {
async fn home(State(st): State<Arc<AppState>>, headers: axum::http::HeaderMap) -> Response {
let (_, csrf, set_cookie) = resolve_session(&headers);
let page = with_site_head(&st.page, &st.site_head);
let page = with_nav_auth(&page, cookie_from_headers(&headers));
let html = render::render_page(&page, st.db_url.as_deref(), Some(&csrf));
let mut resp = Html(html).into_response();
append_set_cookie(&mut resp, set_cookie);
@@ -902,17 +1077,34 @@ fn weak_etag(bytes: &[u8]) -> String {
format!("W/\"{h:x}-{}\"", bytes.len())
}
fn path_matches(path: &str, pattern: &str) -> bool {
let pat = pattern.trim_end_matches('*');
if pattern.ends_with('*') {
path == pat.trim_end_matches('/') || path.starts_with(pat)
} else {
path == pattern || path.starts_with(&format!("{pattern}/"))
fn gate_matches(path: &str, gate: &Gate) -> bool {
let pat = gate.path.trim_end_matches('*').trim_end_matches('/');
let pat = if pat.is_empty() { "/" } else { pat };
match gate.match_mode {
GateMatch::Exact => path == pat || path == gate.path,
GateMatch::Prefix => path == pat || path.starts_with(&format!("{pat}/")),
}
}
fn path_excluded(path: &str, exclude: &[String], login_path: &str) -> bool {
if path == login_path || path.starts_with(&format!("{login_path}?")) {
return true;
}
for ex in exclude {
let ex = ex.trim_end_matches('*').trim_end_matches('/');
if ex.is_empty() {
continue;
}
if path == ex || path.starts_with(&format!("{ex}/")) {
return true;
}
}
false
}
async fn rbac_middleware(
gates: Vec<(String, Vec<String>)>,
gates: Vec<Gate>,
login_path: String,
req: axum::http::Request<axum::body::Body>,
next: axum::middleware::Next,
) -> Response {
@@ -922,18 +1114,23 @@ async fn rbac_middleware(
.get(header::COOKIE)
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string());
for (prefix, roles) in &gates {
if !path_matches(&path, prefix) {
for gate in &gates {
if !gate_matches(&path, gate) {
continue;
}
// Login page itself must stay reachable.
if path == "/admin/login" || path.starts_with("/admin/login?") {
if path_excluded(&path, &gate.exclude, &login_path) {
break;
}
let role = session::session_role(cookie.as_deref());
if !session::role_allowed(&role, roles) {
if role == "visitor" && path.starts_with("/admin") {
return Redirect::to("/admin/login").into_response();
if !session::role_allowed(&role, &gate.roles) {
if role == "visitor" && gate.on_deny == OnDeny::Redirect {
let next_q = urlencoding_path(&path);
let dest = if next_q.is_empty() || path == login_path {
login_path.clone()
} else {
format!("{login_path}?next={next_q}")
};
return Redirect::to(&dest).into_response();
}
return (
StatusCode::FORBIDDEN,
@@ -948,6 +1145,19 @@ async fn rbac_middleware(
next.run(req).await
}
fn urlencoding_path(path: &str) -> String {
let mut out = String::new();
for b in path.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => {
out.push(b as char)
}
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
fn gallery_page(_st: &AppState, cfg: &Value) -> Response {
let storage_url = cfg
.get("storage")
@@ -1044,18 +1254,15 @@ h1{{margin:0 0 1rem;font-size:1.5rem}}
}
fn admin_gate(st: &AppState, cookie_header: Option<&str>) -> Option<Response> {
// When admin=false the built-in routes are not mounted; defense-in-depth only.
if !st.admin {
return Some(Html(admin_shell(st, "Admin", None, "<p class=\"flash err\">Admin is disabled for this app.</p>")).into_response());
return Some((StatusCode::NOT_FOUND, "Not Found").into_response());
}
if st.db_url.is_none() {
return Some(Html(admin_shell(st, "Admin", None, "<p class=\"flash err\">No database bound to this app.</p>")).into_response());
}
// Login-gated admin: require a valid admin-role session.
if st.auth_users.is_some() && !admin_authed(st, cookie_header) {
return Some(
Redirect::to("/admin/login")
.into_response(),
);
return Some(Redirect::to(&st.login_path).into_response());
}
None
}
@@ -1074,10 +1281,10 @@ fn admin_authed(_st: &AppState, cookie_header: Option<&str>) -> bool {
async fn admin_login_get(State(st): State<Arc<AppState>>, headers: axum::http::HeaderMap) -> Response {
if st.auth_users.is_none() {
return Redirect::to("/admin").into_response();
return Redirect::to(&st.login_redirect).into_response();
}
if admin_authed(&st, cookie_from_headers(&headers)) {
return Redirect::to("/admin").into_response();
return Redirect::to(&st.login_redirect).into_response();
}
let (_, csrf, set_cookie) = resolve_session(&headers);
let mut resp = Html(login_page(&st, None, Some(&csrf))).into_response();
@@ -1091,7 +1298,7 @@ async fn admin_login_post(
Form(posted): Form<HashMap<String, String>>,
) -> Response {
let Some(users) = &st.auth_users else {
return Redirect::to("/admin").into_response();
return Redirect::to(&st.login_redirect).into_response();
};
let (_, csrf, set_cookie, posted) = match validate_csrf_post(&headers, posted) {
Ok(v) => v,
@@ -1117,7 +1324,7 @@ async fn admin_login_post(
let sid = session::session_new(Some(st.session_ttl));
session::session_set(&sid, "username", json!(user));
session::session_set(&sid, "role", json!(role));
let mut resp = Redirect::to("/admin").into_response();
let mut resp = Redirect::to(&st.login_redirect).into_response();
let _ = resp.headers_mut().try_append(
axum::http::header::SET_COOKIE,
session::session_cookie(&sid, st.session_ttl, st.cookie_secure)
@@ -1128,7 +1335,7 @@ async fn admin_login_post(
resp
}
fn login_page(_st: &AppState, error: Option<&str>, csrf: Option<&str>) -> String {
fn login_page(st: &AppState, error: Option<&str>, csrf: Option<&str>) -> String {
let err = match error {
Some(e) => format!("<p class=\"flash err\">{}</p>", esc(e)),
None => String::new(),
@@ -1163,7 +1370,7 @@ body {{ margin:0; min-height:100vh; display:grid; place-items:center; background
<h1>Admin</h1>
<p class="sub">Sign in to manage this site.</p>
{err}
<form method="post" action="/admin/login">
<form method="post" action="{login_action}">
{csrf_field}
<label>Username<input name="username" autocomplete="username" required autofocus/></label>
<label>Password<input name="password" type="password" autocomplete="current-password" required/></label>
@@ -1173,11 +1380,12 @@ body {{ margin:0; min-height:100vh; display:grid; place-items:center; background
</body></html>"#,
err = err,
csrf_field = csrf_field,
login_action = esc(&st.login_path),
)
}
async fn admin_logout(
State(_st): State<Arc<AppState>>,
State(st): State<Arc<AppState>>,
headers: axum::http::HeaderMap,
) -> Response {
if let Some(sid) = session::session_id_from_cookie(
@@ -1187,7 +1395,7 @@ async fn admin_logout(
) {
session::session_destroy(&sid);
}
let mut resp = Redirect::to("/admin/login").into_response();
let mut resp = Redirect::to(&st.logout_redirect).into_response();
if let Ok(h) = resp.headers_mut().try_append(
axum::http::header::SET_COOKIE,
"marqdo_sid=; HttpOnly; Path=/; Max-Age=0; SameSite=Lax"
@@ -1211,23 +1419,13 @@ 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
.as_deref()
.and_then(|u| db::list_tables(u).ok())
.unwrap_or_default();
let mut side = String::from("<nav class=\"admin-nav\"><a class=\"brand\" href=\"/admin\">Admin</a>");
let mut side = format!("<nav class=\"admin-nav\"><a class=\"brand\" href=\"{}\">Admin</a>", esc(st.ap()));
if tables.is_empty() {
side.push_str("<p class=\"muted\">No tables yet.</p>");
} else {
@@ -1239,8 +1437,8 @@ fn admin_shell(st: &AppState, title: &str, active: Option<&str>, inner: &str) ->
""
};
side.push_str(&format!(
"<li><a{cls} href=\"/admin/{}\">{}</a></li>",
esc(t),
"<li><a{cls} href=\"{}\">{}</a></li>",
esc(&st.admin_href(t)),
esc(t)
));
}
@@ -1270,7 +1468,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 +1478,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 +1488,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; }}
@@ -1333,7 +1533,9 @@ fn admin_form_page(
csrf: Option<&str>,
) -> String {
let mut body = format!(
"<p class=\"crumbs\"><a href=\"/admin\">Admin</a> / <a href=\"/admin/{t}\">{t}</a> / {kind}</p><h1>{kind} {t}</h1>",
"<p class=\"crumbs\"><a href=\"{home}\">Admin</a> / <a href=\"{table_href}\">{t}</a> / {kind}</p><h1>{kind} {t}</h1>",
home = esc(st.ap()),
table_href = esc(&st.admin_href(table)),
t = esc(table),
kind = esc(kind),
);
@@ -1363,14 +1565,16 @@ 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>",
"<tr><td><a href=\"{href}\">{t}</a></td><td class=\"actions\"><a class=\"btn\" href=\"{new_href}\">New</a></td></tr>",
href = esc(&st.admin_href(t)),
new_href = esc(&st.admin_href(&format!("{t}/new"))),
t = esc(t)
));
}
inner.push_str("</tbody></table>");
inner.push_str("</tbody></table></div>");
}
Html(admin_shell(&st, "Admin", None, &inner)).into_response()
}
@@ -1415,25 +1619,26 @@ async fn admin_table(
}
let mut inner = format!(
"<p class=\"crumbs\"><a href=\"/admin\">Admin</a> / {t}</p><h1>{t}</h1>",
"<p class=\"crumbs\"><a href=\"{home}\">Admin</a> / {t}</p><h1>{t}</h1>",
home = esc(st.ap()),
t = esc(&table)
);
inner.push_str(&flash_html(q.flash.as_deref()));
inner.push_str(&format!(
"<div class=\"toolbar\"><a class=\"btn\" href=\"/admin/{}/new\">New row</a><span class=\"meta\">{} row{}</span></div>",
esc(&table),
"<div class=\"toolbar\"><a class=\"btn\" href=\"{new_href}\">New row</a><span class=\"meta\">{} row{}</span></div>",
rows.len(),
if rows.len() == 1 { "" } else { "s" }
if rows.len() == 1 { "" } else { "s" },
new_href = esc(&st.admin_href(&format!("{table}/new"))),
));
if rows.is_empty() {
inner.push_str(&format!(
"<div class=\"empty\"><strong>No rows in {}</strong><a class=\"btn\" href=\"/admin/{}/new\">Create the first row</a></div>",
"<div class=\"empty\"><strong>No rows in {}</strong><a class=\"btn\" href=\"{new_href}\">Create the first row</a></div>",
esc(&table),
esc(&table)
new_href = esc(&st.admin_href(&format!("{table}/new"))),
));
} 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 +1655,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")
@@ -1461,14 +1667,17 @@ async fn admin_table(
.unwrap_or_default();
if !id.is_empty() {
inner.push_str(&format!(
"<td class=\"actions\"><a href=\"/admin/{table}/{id}/edit\">Edit</a> · <a class=\"danger\" href=\"/admin/{table}/{id}/delete\" onclick=\"return confirm('Delete row #{id}?')\">Delete</a></td>"
"<td class=\"actions\"><a href=\"{edit}\">Edit</a> · <a class=\"danger\" href=\"{del}\" onclick=\"return confirm('Delete row #{id}?')\">Delete</a></td>",
edit = esc(&st.admin_href(&format!("{table}/{id}/edit"))),
del = esc(&st.admin_href(&format!("{table}/{id}/delete"))),
id = esc(&id),
));
} else {
inner.push_str("<td></td>");
}
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()
}
@@ -1483,7 +1692,7 @@ async fn admin_new_get(
}
let url = st.db_url.as_deref().unwrap();
let (_, csrf, set_cookie) = resolve_session(&headers);
match form::from_schema(url, &table, "insert", None) {
match form::from_schema(url, &table, "insert", None, st.ap()) {
Ok(frm) => {
let mut resp = Html(admin_form_page(
&st,
@@ -1523,7 +1732,7 @@ async fn admin_new_post(
Ok(v) => v,
Err(r) => return r,
};
match form::from_schema(url, &table, "insert", None) {
match form::from_schema(url, &table, "insert", None, st.ap()) {
Ok(frm) => {
let mut resp = submit_and_respond(
&st,
@@ -1578,7 +1787,7 @@ async fn admin_edit_get(
}
};
let (_, csrf, set_cookie) = resolve_session(&headers);
match form::from_schema(url, &table, "update", Some(&id)) {
match form::from_schema(url, &table, "update", Some(&id), st.ap()) {
Ok(frm) => {
let mut resp = Html(admin_form_page(
&st,
@@ -1618,7 +1827,7 @@ async fn admin_edit_post(
Ok(v) => v,
Err(r) => return r,
};
match form::from_schema(url, &table, "update", Some(&id)) {
match form::from_schema(url, &table, "update", Some(&id), st.ap()) {
Ok(frm) => {
let mut resp = submit_and_respond(
&st,
@@ -1660,7 +1869,7 @@ async fn admin_delete(
))
.into_response();
}
Redirect::to(&with_flash(&format!("/admin/{table}"), "deleted")).into_response()
Redirect::to(&with_flash(&st.admin_href(&table), "deleted")).into_response()
}
fn esc(s: &str) -> String {
@@ -1816,3 +2025,45 @@ async fn ws_socket_loop(
}
}
}
#[cfg(test)]
mod gate_tests {
use super::*;
fn g(path: &str, mode: GateMatch) -> Gate {
Gate {
path: path.into(),
roles: vec!["admin".into()],
match_mode: mode,
on_deny: OnDeny::Forbid,
exclude: vec![],
}
}
#[test]
fn prefix_segment_boundary() {
let gate = g("/admin", GateMatch::Prefix);
assert!(gate_matches("/admin", &gate));
assert!(gate_matches("/admin/news", &gate));
assert!(!gate_matches("/admin-publish", &gate));
assert!(!gate_matches("/administrator", &gate));
}
#[test]
fn starred_json_becomes_prefix() {
let gate = Gate::from_json(&json!({"path": "/admin*", "roles": ["admin"]})).unwrap();
assert_eq!(gate.match_mode, GateMatch::Prefix);
assert!(gate_matches("/admin/x", &gate));
assert!(!gate_matches("/admin-publish", &gate));
}
#[test]
fn exclude_login() {
assert!(path_excluded(
"/desk/login",
&["/desk/login".into()],
"/desk/login"
));
assert!(!path_excluded("/desk", &["/desk/login".into()], "/desk/login"));
}
}
+324 -58
View File
@@ -22,7 +22,7 @@ mod upload;
mod ws;
mod ws_hub;
use crate::table::as_css_named;
use crate::table::as_css_named_checked;
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_void};
@@ -273,10 +273,24 @@ macro_rules! web_ffi {
web_ffi!(web_page_new, |args: &Value| {
let title = arg_str_opt(args, "title").unwrap_or("Marqdo Web");
let intro = arg_str_opt(args, "intro").unwrap_or("");
Ok(json!({
let mut out = json!({
"title": title,
"intro": intro,
}))
});
if let Some(s) = arg_str_opt(args, "shell_css").or_else(|| arg_str_opt(args, "壳样式")) {
out.as_object_mut().unwrap().insert("shell_css".into(), json!(s));
}
if let Some(s) = arg_str_opt(args, "layout").or_else(|| arg_str_opt(args, "布局")) {
out.as_object_mut().unwrap().insert("layout".into(), json!(s));
}
if let Some(s) = arg_str_opt(args, "asset_version")
.or_else(|| arg_str_opt(args, "资源版本"))
{
out.as_object_mut()
.unwrap()
.insert("asset_version".into(), json!(s));
}
Ok(out)
});
web_ffi!(web_compose_components, |args: &Value| {
@@ -348,7 +362,21 @@ web_ffi!(web_page_css, |args: &Value| {
web_ffi!(web_style, |args: &Value| {
let name = arg_str_opt(args, "name").unwrap_or("").to_string();
let table = args.get("table").cloned().unwrap_or(json!([]));
Ok(Value::String(as_css_named(&name, &table)))
let strict = args
.get("strict")
.or_else(|| args.get("strict_css_cells"))
.or_else(|| args.get("严格"))
.map(|v| match v {
Value::Bool(b) => *b,
Value::Number(n) => n.as_i64().unwrap_or(0) != 0,
Value::String(s) => matches!(
s.trim(),
"1" | "true" | "True" | "yes" | "on" | "真" | "是"
),
_ => false,
})
.unwrap_or(false);
as_css_named_checked(&name, &table, strict).map(Value::String)
});
web_ffi!(web_page_detail, |args: &Value| {
@@ -500,7 +528,7 @@ web_ffi!(web_rss_build, |args: &Value| {
web_ffi!(web_app_route_rss, |args: &Value| {
let mut app = args.get("app").cloned().unwrap_or(json!({}));
let path = normalize_route_path(arg_str(args, "path")?)?;
let path = normalize_route_path_in_app(arg_str(args, "path")?, &app)?;
let table = arg_str(args, "table")?.to_string();
let limit = args
.get("limit")
@@ -537,7 +565,7 @@ web_ffi!(web_app_route_rss, |args: &Value| {
web_ffi!(web_app_redirect, |args: &Value| {
let mut app = args.get("app").cloned().unwrap_or(json!({}));
let from = normalize_route_path(arg_str(args, "from").or_else(|_| arg_str(args, "path"))?)?;
let from = normalize_route_path_in_app(arg_str(args, "from").or_else(|_| arg_str(args, "path"))?, &app)?;
let to = arg_str(args, "to")?.to_string();
let permanent = match args
.get("permanent")
@@ -588,7 +616,7 @@ web_ffi!(web_app_error_page, |args: &Value| {
web_ffi!(web_app_sitemap, |args: &Value| {
let mut app = args.get("app").cloned().unwrap_or(json!({}));
let path = normalize_route_path(arg_str(args, "path").unwrap_or("/sitemap.xml"))?;
let path = normalize_route_path_in_app(arg_str(args, "path").unwrap_or("/sitemap.xml"), &app)?;
let base = arg_str_opt(args, "base").unwrap_or("").to_string();
let table = arg_str_opt(args, "table").map(|s| s.to_string());
let loc = arg_str_opt(args, "loc").unwrap_or("path").to_string();
@@ -655,7 +683,7 @@ fn storage_url_arg(args: &Value, key: &str) -> Result<String, String> {
web_ffi!(web_app_upload, |args: &Value| {
let mut app = args.get("app").cloned().unwrap_or(json!({}));
let path = normalize_route_path(arg_str(args, "path").unwrap_or("/_upload"))?;
let path = normalize_route_path_in_app(arg_str(args, "path").unwrap_or("/_upload"), &app)?;
let field = arg_str_opt(args, "field").unwrap_or("file").to_string();
let storage_url = storage_url_arg(args, "storage")?;
let prefix = arg_str_opt(args, "prefix").unwrap_or("uploads/").to_string();
@@ -1023,27 +1051,57 @@ web_ffi!(web_app_new, |args: &Value| {
Some(Value::Number(n)) => n.as_i64().unwrap_or(0) != 0,
_ => false,
};
Ok(json!({
let admin_prefix = arg_str_opt(args, "admin_prefix")
.or_else(|| arg_str_opt(args, "后台前缀"))
.map(normalize_admin_prefix)
.transpose()?
.unwrap_or_else(|| "/admin".into());
let login_redirect = arg_str_opt(args, "login_redirect")
.or_else(|| arg_str_opt(args, "登录回跳"))
.map(|s| s.to_string());
let logout_redirect = arg_str_opt(args, "logout_redirect")
.or_else(|| arg_str_opt(args, "登出回跳"))
.map(|s| s.to_string());
let mut out = json!({
"page": page,
"db": db,
"host": host,
"port": port,
"admin": admin,
"admin_prefix": admin_prefix,
"forms": {},
"routes": {},
"ws_routes": {},
"static_dir": null,
"static_mount": "/static",
}))
});
if let Some(v) = login_redirect {
out.as_object_mut().unwrap().insert("login_redirect".into(), json!(v));
}
if let Some(v) = logout_redirect {
out.as_object_mut().unwrap().insert("logout_redirect".into(), json!(v));
}
if let Some(s) = arg_str_opt(args, "shell_css").or_else(|| arg_str_opt(args, "壳样式")) {
out.as_object_mut().unwrap().insert("shell_css".into(), json!(s));
}
if let Some(s) = arg_str_opt(args, "layout").or_else(|| arg_str_opt(args, "布局")) {
out.as_object_mut().unwrap().insert("layout".into(), json!(s));
}
if let Some(s) = arg_str_opt(args, "asset_version")
.or_else(|| arg_str_opt(args, "资源版本"))
{
out.as_object_mut()
.unwrap()
.insert("asset_version".into(), json!(s));
}
Ok(out)
});
fn normalize_route_path(raw: &str) -> Result<String, String> {
/// Normalize a URL path: leading slash, no trailing slash (except never `/` here).
fn clean_mount_path(raw: &str) -> Result<String, String> {
let s = raw.trim();
if s.is_empty() {
return Err("route path is empty".into());
}
if s == "/" {
return Err("route path `/` is reserved for the home page".into());
return Err("path is empty".into());
}
let mut path = if s.starts_with('/') {
s.to_string()
@@ -1053,24 +1111,88 @@ fn normalize_route_path(raw: &str) -> Result<String, String> {
while path.len() > 1 && path.ends_with('/') {
path.pop();
}
// reserved prefixes
if path == "/admin"
|| path.starts_with("/admin/")
|| path == "/_form"
Ok(path)
}
fn normalize_admin_prefix(raw: &str) -> Result<String, String> {
let path = clean_mount_path(raw)?;
if path == "/" {
return Err("admin_prefix cannot be `/`".into());
}
if path == "/_form"
|| path.starts_with("/_form/")
|| path == "/_part"
|| path.starts_with("/_part/")
|| path == "/static"
|| path.starts_with("/static/")
{
return Err(format!("admin_prefix `{path}` collides with framework paths"));
}
Ok(path)
}
fn path_under_prefix(path: &str, prefix: &str) -> bool {
path == prefix || path.starts_with(&format!("{prefix}/"))
}
fn is_framework_reserved(path: &str, static_mount: &str) -> bool {
path == "/_form"
|| path.starts_with("/_form/")
|| path == "/_part"
|| path.starts_with("/_part/")
|| path_under_prefix(path, static_mount)
}
/// Reserved only while built-in admin is enabled, for the active prefix.
fn normalize_route_path_for(
raw: &str,
admin: bool,
admin_prefix: &str,
static_mount: &str,
) -> Result<String, String> {
let path = clean_mount_path(raw)?;
if path == "/" {
return Err("route path `/` is reserved for the home page".into());
}
if is_framework_reserved(&path, static_mount) {
return Err(format!("route path `{path}` is reserved"));
}
if admin && path_under_prefix(&path, admin_prefix) {
return Err(format!("route path `{path}` is reserved"));
}
Ok(path)
}
fn app_admin_flag(app: &Value) -> bool {
app.get("admin")
.and_then(|v| v.as_bool())
.unwrap_or(false)
}
fn app_admin_prefix(app: &Value) -> String {
app.get("admin_prefix")
.and_then(|v| v.as_str())
.and_then(|s| normalize_admin_prefix(s).ok())
.unwrap_or_else(|| "/admin".into())
}
fn app_static_mount(app: &Value) -> String {
app.get("static_mount")
.and_then(|v| v.as_str())
.map(http::normalize_static_mount)
.unwrap_or_else(|| "/static".into())
}
fn normalize_route_path_in_app(raw: &str, app: &Value) -> Result<String, String> {
normalize_route_path_for(
raw,
app_admin_flag(app),
&app_admin_prefix(app),
&app_static_mount(app),
)
}
web_ffi!(web_app_route, |args: &Value| {
let mut app = args.get("app").cloned().unwrap_or(json!({}));
let path = normalize_route_path(arg_str(args, "path")?)?;
let path = normalize_route_path_in_app(arg_str(args, "path")?, &app)?;
let mut page = args
.get("page")
.cloned()
@@ -1094,7 +1216,7 @@ web_ffi!(web_app_route, |args: &Value| {
web_ffi!(web_app_route_ws, |args: &Value| {
let mut app = args.get("app").cloned().unwrap_or(json!({}));
let path = normalize_route_path(arg_str(args, "path")?)?;
let path = normalize_route_path_in_app(arg_str(args, "path")?, &app)?;
let mode = if let Some(m) = args.get("mode").or_else(|| args.get("模式")) {
crate::ws_hub::WsMode::parse(m)
} else {
@@ -1179,26 +1301,62 @@ web_ffi!(web_app_auth, |args: &Value| {
.get("session_ttl")
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
.unwrap_or(3600);
if let Some(p) = arg_str_opt(args, "admin_prefix").or_else(|| arg_str_opt(args, "后台前缀")) {
let p = normalize_admin_prefix(p)?;
app.as_object_mut()
.ok_or_else(|| "app must be a map".to_string())?
.insert("admin_prefix".into(), json!(p));
}
if let Some(v) = arg_str_opt(args, "login_redirect").or_else(|| arg_str_opt(args, "登录回跳")) {
app.as_object_mut()
.ok_or_else(|| "app must be a map".to_string())?
.insert("login_redirect".into(), json!(v));
}
if let Some(v) = arg_str_opt(args, "logout_redirect").or_else(|| arg_str_opt(args, "登出回跳")) {
app.as_object_mut()
.ok_or_else(|| "app must be a map".to_string())?
.insert("logout_redirect".into(), json!(v));
}
if let Some(v) = arg_str_opt(args, "login_path").or_else(|| arg_str_opt(args, "登录路径")) {
app.as_object_mut()
.ok_or_else(|| "app must be a map".to_string())?
.insert("login_path".into(), json!(v));
}
let prefix = app_admin_prefix(&app);
let login_path = app
.get("login_path")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.unwrap_or_else(|| format!("{prefix}/login"));
let obj = app
.as_object_mut()
.ok_or_else(|| "app must be a map".to_string())?;
obj.insert("login_path".into(), json!(&login_path));
obj.insert(
"auth".to_string(),
json!({ "users": users, "session_ttl": session_ttl }),
);
// Default RBAC: `/admin*` requires role `admin` when auth is configured.
// Default RBAC: segment-boundary prefix on admin_prefix; redirect visitors to login.
let mut gates = obj
.get("gates")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
let has_admin_gate = gates.iter().any(|g| {
g.get("path")
.and_then(|v| v.as_str())
.is_some_and(|p| p == "/admin" || p == "/admin*")
g.get("path").and_then(|v| v.as_str()).is_some_and(|p| {
let cleaned = p.trim_end_matches('*').trim_end_matches('/');
cleaned == prefix.trim_end_matches('/')
})
});
if !has_admin_gate {
gates.push(json!({ "path": "/admin*", "roles": ["admin"] }));
gates.push(json!({
"path": prefix,
"roles": ["admin"],
"match": "prefix",
"on_deny": "redirect",
"exclude": [login_path],
}));
obj.insert("gates".into(), Value::Array(gates));
}
Ok(app)
@@ -1211,6 +1369,17 @@ web_ffi!(web_app_gate, |args: &Value| {
.or_else(|| arg_str_opt(args, "角色"))
.unwrap_or("admin");
let roles: Vec<String> = session::parse_roles_csv(roles_raw);
let match_mode = arg_str_opt(args, "match")
.or_else(|| arg_str_opt(args, "匹配"))
.unwrap_or("prefix");
let on_deny = arg_str_opt(args, "on_deny")
.or_else(|| arg_str_opt(args, "拒绝"))
.unwrap_or("forbid");
let exclude = args
.get("exclude")
.or_else(|| args.get("排除"))
.cloned()
.unwrap_or(Value::Null);
let obj = app
.as_object_mut()
.ok_or_else(|| "app must be a map".to_string())?;
@@ -1219,17 +1388,30 @@ web_ffi!(web_app_gate, |args: &Value| {
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
gates.push(json!({ "path": path, "roles": roles }));
let mut entry = json!({
"path": path,
"roles": roles,
"match": match_mode,
"on_deny": on_deny,
});
if !matches!(exclude, Value::Null) {
entry
.as_object_mut()
.unwrap()
.insert("exclude".into(), exclude);
}
gates.push(entry);
obj.insert("gates".into(), Value::Array(gates));
Ok(app)
});
web_ffi!(web_app_gallery, |args: &Value| {
let mut app = args.get("app").cloned().unwrap_or(json!({}));
let path = normalize_route_path(
let path = normalize_route_path_in_app(
arg_str(args, "path")
.or_else(|_| arg_str(args, "路径"))
.unwrap_or("/gallery"),
&app,
)?;
let storage_url = storage_url_arg(args, "storage")
.or_else(|_| storage_url_arg(args, "存储"))?;
@@ -1293,16 +1475,16 @@ web_ffi!(web_app_static, |args: &Value| {
}
let mount = arg_str_opt(args, "mount").unwrap_or("/static");
let mount = http::normalize_static_mount(mount);
// Also reserve custom mounts against later routes.
if mount == "/admin"
|| mount.starts_with("/admin/")
|| mount == "/_form"
if mount == "/_form"
|| mount.starts_with("/_form/")
|| mount == "/_part"
|| mount.starts_with("/_part/")
{
return Err(format!("static mount `{mount}` is reserved"));
}
if app_admin_flag(&app) && path_under_prefix(&mount, &app_admin_prefix(&app)) {
return Err(format!("static mount `{mount}` is reserved"));
}
let obj = app
.as_object_mut()
.ok_or_else(|| "app must be a map".to_string())?;
@@ -1463,7 +1645,10 @@ web_ffi!(web_form_from_schema, |args: &Value| {
None | Some(Value::Null) => None,
Some(_) => Some(arg_text(args, "id")?),
};
form::from_schema(&url, &table, action, id.as_deref())
let admin_prefix = arg_str_opt(args, "admin_prefix")
.or_else(|| arg_str_opt(args, "后台前缀"))
.unwrap_or("/admin");
form::from_schema(&url, &table, action, id.as_deref(), admin_prefix)
});
web_ffi!(web_db_table_info, |args: &Value| {
@@ -1484,6 +1669,48 @@ web_ffi!(web_db_table_info, |args: &Value| {
Ok(json!({ "columns": arr }))
});
fn stamp_page_shell(
page: &mut Value,
shell_css: Option<&str>,
layout: Option<&str>,
asset_version: Option<&str>,
) {
let Some(obj) = page.as_object_mut() else {
return;
};
if let Some(s) = shell_css {
let empty = obj
.get("shell_css")
.and_then(|v| v.as_str())
.unwrap_or("")
.is_empty();
if empty {
obj.insert("shell_css".into(), json!(s));
}
}
if let Some(s) = layout {
let empty = obj
.get("layout")
.and_then(|v| v.as_str())
.unwrap_or("")
.is_empty();
if empty {
obj.insert("layout".into(), json!(s));
}
}
if let Some(s) = asset_version {
let empty = obj
.get("asset_version")
.and_then(|v| v.as_str())
.unwrap_or("")
.is_empty();
if empty {
obj.insert("asset_version".into(), json!(s));
}
}
}
web_ffi!(web_listen, |args: &Value| {
use std::collections::HashMap;
use std::path::PathBuf;
@@ -1564,7 +1791,7 @@ web_ffi!(web_listen, |args: &Value| {
None,
None,
None,
Vec::<(String, Vec<String>)>::new(),
Vec::<http::Gate>::new(),
HashMap::new(),
middleware::Middleware::default(),
cookie_secure,
@@ -1702,26 +1929,12 @@ web_ffi!(web_listen, |args: &Value| {
.map(|s| s.to_string());
let page_404 = app.get("page_404").cloned().filter(|v| !v.is_null());
let page_500 = app.get("page_500").cloned().filter(|v| !v.is_null());
let mut gates: Vec<(String, Vec<String>)> = Vec::new();
let mut gates: Vec<http::Gate> = Vec::new();
if let Some(arr) = app.get("gates").and_then(|v| v.as_array()) {
for g in arr {
let path = g
.get("path")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
if path.is_empty() {
continue;
if let Some(gate) = http::Gate::from_json(g) {
gates.push(gate);
}
let roles = match g.get("roles") {
Some(Value::Array(a)) => a
.iter()
.filter_map(|v| v.as_str().map(|s| s.to_ascii_lowercase()))
.collect(),
Some(Value::String(s)) => session::parse_roles_csv(s),
_ => vec!["admin".into()],
};
gates.push((path, roles));
}
}
let mut gallery_routes = HashMap::new();
@@ -1852,12 +2065,61 @@ web_ffi!(web_listen, |args: &Value| {
r
})
.collect();
let admin_cfg_app = args.get("app").cloned().unwrap_or_else(|| {
json!({
"admin": admin,
"admin_prefix": arg_str_opt(args, "admin_prefix").unwrap_or("/admin"),
"login_redirect": args.get("login_redirect").cloned().unwrap_or(Value::Null),
"logout_redirect": args.get("logout_redirect").cloned().unwrap_or(Value::Null),
})
});
let admin_prefix = app_admin_prefix(&admin_cfg_app);
let login_path = admin_cfg_app
.get("login_path")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.unwrap_or_else(|| format!("{admin_prefix}/login"));
let login_redirect = admin_cfg_app
.get("login_redirect")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.unwrap_or_else(|| admin_prefix.clone());
let logout_redirect = admin_cfg_app
.get("logout_redirect")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.unwrap_or_else(|| login_path.clone());
let app_shell = admin_cfg_app
.get("shell_css")
.or_else(|| admin_cfg_app.get("壳样式"))
.and_then(|v| v.as_str());
let app_layout = admin_cfg_app
.get("layout")
.or_else(|| admin_cfg_app.get("布局"))
.and_then(|v| v.as_str());
let app_asset_version = admin_cfg_app
.get("asset_version")
.or_else(|| admin_cfg_app.get("资源版本"))
.and_then(|v| v.as_str());
let mut page = page;
let mut routes = routes;
stamp_page_shell(&mut page, app_shell, app_layout, app_asset_version);
for (_k, p) in routes.iter_mut() {
stamp_page_shell(p, app_shell, app_layout, app_asset_version);
}
http::listen(
&page,
db_url.as_deref(),
&host,
port,
admin,
&admin_prefix,
&login_path,
&login_redirect,
&logout_redirect,
forms,
routes,
static_dir,
@@ -1915,7 +2177,11 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
}
let regs = [
("web_page_new", "title,intro", web_page_new as PluginFn),
(
"web_page_new",
"title,intro,shell_css,layout,asset_version",
web_page_new as PluginFn,
),
(
"web_compose_components",
"page,components",
@@ -2024,7 +2290,7 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
("web_media_new", "storage", web_media_new as PluginFn),
(
"web_style",
"name,table",
"name,table,strict",
web_style as PluginFn,
),
(
@@ -2087,7 +2353,7 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
("web_db_list_tables", "url", web_db_list_tables as PluginFn),
(
"web_app_new",
"page,db,admin,host,port",
"page,db,admin,host,port,admin_prefix,login_redirect,logout_redirect,shell_css,layout,asset_version",
web_app_new as PluginFn,
),
("web_app_route", "app,path,page", web_app_route as PluginFn),
@@ -2136,8 +2402,8 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
("web_auth_logout", "session_id", web_auth_logout as PluginFn),
("web_password_hash", "password", web_password_hash as PluginFn),
("web_auth_new", "users,session_ttl", web_auth_new as PluginFn),
("web_app_auth", "app,users,session_ttl", web_app_auth as PluginFn),
("web_app_gate", "app,path,roles", web_app_gate as PluginFn),
("web_app_auth", "app,users,session_ttl,admin_prefix,login_redirect,logout_redirect,login_path", web_app_auth as PluginFn),
("web_app_gate", "app,path,roles,match,on_deny,exclude", web_app_gate as PluginFn),
(
"web_app_gallery",
"app,path,storage,prefix,title,download_base",
+515 -95
View File
@@ -4,7 +4,10 @@ use serde_json::{json, Map, Value};
use crate::db;
use crate::markdown;
use crate::table::{as_bind, normalize_ref, normalize_slot, parse_site_path, project_rows, SitePath};
use crate::table::{
as_bind, as_nav_rows, nav_label_href, nav_media_when_class, normalize_ref, normalize_slot,
parse_site_path, project_rows, SitePath,
};
fn esc(s: &str) -> String {
s.replace('&', "&amp;")
@@ -58,71 +61,244 @@ fn is_db_bind_back(back: &str) -> bool {
}
}
fn resolve_links(raw: Option<&Value>, db_url: Option<&str>) -> Vec<(String, String)> {
#[derive(Clone, Debug)]
struct NavLink {
label: String,
href: String,
class: String,
media: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum NavWhen {
Always,
Hide,
Auth,
Guest,
}
fn parse_nav_when(raw: &str) -> NavWhen {
let t = raw.trim();
if t.is_empty()
|| matches!(
t,
"*" | "always" | "Always" | "真" | "yes" | "on" | "show" | "all"
)
{
return NavWhen::Always;
}
if matches!(
t,
"hide" | "never" | "off" | "no" | "假" | "否" | "0" | "false" | "False"
) {
return NavWhen::Hide;
}
if matches!(
t,
"auth" | "user" | "登录" | "已登录" | "logged_in" | "logged-in"
) {
return NavWhen::Auth;
}
if matches!(
t,
"guest" | "anon" | "anonymous" | "访客" | "匿名" | "未登录"
) {
return NavWhen::Guest;
}
// Unknown token: keep visible (forward-compatible).
NavWhen::Always
}
/// `Some(true)` logged in, `Some(false)` guest, `None` unknown (do not filter auth/guest).
fn page_auth_state(page: Option<&Value>) -> Option<bool> {
let page = page?;
if let Some(v) = page
.get("_nav_user")
.or_else(|| page.get("user"))
.or_else(|| page.get("username"))
.or_else(|| page.get("_user"))
{
match v {
Value::Null => Some(false),
Value::Bool(b) => Some(*b),
Value::String(s) => Some(!s.trim().is_empty()),
Value::Number(n) => Some(n.as_i64().unwrap_or(0) != 0),
_ => Some(true),
}
} else if let Some(v) = page.get("_logged_in").or_else(|| page.get("logged_in")) {
match v {
Value::Bool(b) => Some(*b),
Value::String(s) => Some(matches!(
s.trim(),
"1" | "true" | "True" | "yes" | "on" | "真" | "是"
)),
Value::Number(n) => Some(n.as_i64().unwrap_or(0) != 0),
_ => None,
}
} else {
None
}
}
fn nav_when_visible(when: NavWhen, auth: Option<bool>) -> bool {
match when {
NavWhen::Always => true,
NavWhen::Hide => false,
NavWhen::Auth => auth.unwrap_or(true), // unknown → keep (compat)
NavWhen::Guest => match auth {
Some(logged_in) => !logged_in,
None => true,
},
}
}
fn resolve_links(raw: Option<&Value>, db_url: Option<&str>, page: Option<&Value>) -> Vec<NavLink> {
let Some(raw) = raw else {
return Vec::new();
};
let auth = page_auth_state(page);
let binds = as_bind(raw);
let arr = binds.as_array().cloned().unwrap_or_default();
if arr.is_empty() {
return Vec::new();
}
let has_db = arr
.iter()
.any(|b| b.get("back").and_then(|v| v.as_str()).is_some_and(is_db_bind_back));
if has_db {
let Some(url) = db_url else {
return Vec::new();
};
let table = crate::table::bind_table_name(&arr);
let Some(table) = table else {
return Vec::new();
};
let data = select_page_data(url, &table, raw, 200, 0);
let rows = data
.get("rows")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
let projected = project_rows(&arr, &rows);
let mut out = Vec::new();
for it in projected.as_array().cloned().unwrap_or_default() {
let m = it.as_object().cloned().unwrap_or_default();
let label = m
.get("title")
.or_else(|| m.get("label"))
.map(text)
.unwrap_or_default();
let href = m
.get("href")
.or_else(|| m.get("path"))
.map(text)
.unwrap_or_else(|| "#".into());
if !label.is_empty() {
out.push((label, href));
}
let rows: Vec<Map<String, Value>> = if !arr.is_empty() {
let has_db = arr
.iter()
.any(|b| b.get("back").and_then(|v| v.as_str()).is_some_and(is_db_bind_back));
if has_db {
let Some(url) = db_url else {
return Vec::new();
};
let table = crate::table::bind_table_name(&arr);
let Some(table) = table else {
return Vec::new();
};
let data = select_page_data(url, &table, raw, 200, 0);
let projected = project_rows(
&arr,
&data
.get("rows")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default(),
);
projected
.as_array()
.cloned()
.unwrap_or_default()
.into_iter()
.filter_map(|it| it.as_object().cloned())
.collect()
} else {
arr.into_iter()
.filter_map(|b| b.as_object().cloned())
.collect()
}
return out;
} else {
as_nav_rows(raw)
};
let mut out = Vec::new();
for m in rows {
let (label, href) = nav_label_href(&m);
if label.is_empty() {
continue;
}
let (media, when_raw, class) = nav_media_when_class(&m);
// DB-projected rows may use title/href without media keys on bind.
let when_raw = if when_raw.is_empty() {
m.get("when")
.or_else(|| m.get("当"))
.map(text)
.unwrap_or_default()
} else {
when_raw
};
let media = if media.is_empty() {
m.get("media")
.or_else(|| m.get("媒体"))
.map(text)
.unwrap_or_default()
} else {
media
};
let when = parse_nav_when(&when_raw);
if !nav_when_visible(when, auth) {
continue;
}
out.push(NavLink {
label,
href,
class,
media,
});
}
// static: front=label back=href (URLs with `.` must stay here)
arr.into_iter()
.map(|b| {
let label = b.get("front").map(text).unwrap_or_default();
let href = b.get("back").map(text).unwrap_or_else(|| "#".into());
(label, href)
})
.filter(|(l, _)| !l.is_empty())
.collect()
out
}
fn render_ul(links: &[(String, String)], class: &str) -> String {
fn nav_media_class_map(links: &[NavLink]) -> (String, Vec<(String, String)>) {
nav_media_class_map_many(&[links])
}
fn nav_media_class_map_many(groups: &[&[NavLink]]) -> (String, Vec<(String, String)>) {
let mut pairs: Vec<(String, String)> = Vec::new();
let mut css = String::new();
for links in groups {
for link in *links {
let media = link.media.trim();
if media.is_empty() || pairs.iter().any(|(m, _)| m == media) {
continue;
}
let class = format!("nav-mq-{}", pairs.len());
css.push_str(&format!(
"@media not {media} {{ li.{class} {{ display:none !important; }} }}\n"
));
pairs.push((media.to_string(), class));
}
}
(css, pairs)
}
fn render_ul(links: &[NavLink], class: &str) -> String {
let (_css, mq_pairs) = nav_media_class_map(links);
render_ul_with_mq(links, class, &mq_pairs)
}
fn render_ul_with_mq(links: &[NavLink], class: &str, mq_pairs: &[(String, String)]) -> String {
let mut s = format!("<ul class=\"{}\">", esc(class));
for (label, href) in links {
s.push_str(&format!(
"<li><a href=\"{}\">{}</a></li>",
esc(href),
esc(label)
));
for link in links {
let mq = link.media.trim();
let mq_class = if mq.is_empty() {
""
} else {
mq_pairs
.iter()
.find(|(m, _)| m == mq)
.map(|(_, c)| c.as_str())
.unwrap_or("")
};
let mut li_class = String::new();
if !link.class.is_empty() {
li_class.push_str(&link.class);
}
if !mq_class.is_empty() {
if !li_class.is_empty() {
li_class.push(' ');
}
li_class.push_str(mq_class);
}
if li_class.is_empty() {
s.push_str(&format!(
"<li><a href=\"{}\">{}</a></li>",
esc(&link.href),
esc(&link.label)
));
} else {
s.push_str(&format!(
"<li class=\"{}\"><a href=\"{}\">{}</a></li>",
esc(&li_class),
esc(&link.href),
esc(&link.label)
));
}
}
s.push_str("</ul>");
s
@@ -307,19 +483,35 @@ fn slot_class(args: &Value, slot: &str, base: &str) -> String {
}
}
const SHELL_CSS: &str = r#"
const SHELL_VARS: &str = r#"
:root { --ink:#1c1917; --muted:#57534e; --paper:#fafaf9; --line:#e7e5e4; --accent:#0f766e; }
body { margin:0; font-family: "IBM Plex Sans", "Noto Sans SC", sans-serif; background:var(--paper); color:var(--ink); display:grid; min-height:100vh; grid-template-rows:auto 1fr auto; }
body { margin:0; font-family: "IBM Plex Sans", "Noto Sans SC", sans-serif; background:var(--paper); color:var(--ink); }
a { color:var(--ink); text-decoration:none; }
a:hover { color:var(--accent); }
"#;
const SHELL_LAYOUT: &str = r#"
body { display:grid; min-height:100vh; grid-template-rows:auto 1fr auto; }
body.has-sidebar { grid-template-columns:14rem 1fr; grid-template-areas:"top top" "side main" "foot foot"; }
body.no-sidebar { grid-template-areas:"top" "main" "foot"; }
@media (max-width:720px) {
body.has-sidebar { grid-template-columns:1fr; grid-template-areas:"top" "main" "foot" "side"; }
body.has-sidebar aside.side { border-right:0; border-top:1px solid var(--line); }
}
body.layout-stacked { display:flex; flex-direction:column; min-height:100vh; }
body.layout-stacked header.topnav, body.layout-stacked aside.side, body.layout-stacked main.main, body.layout-stacked footer.foot { width:100%; }
body.layout-stacked aside.side { border-right:0; border-bottom:1px solid var(--line); }
body.layout-bare { display:block; min-height:100vh; }
body.layout-bare main.main { padding:1.5rem 1.25rem 2rem; }
header.topnav { grid-area:top; border-bottom:1px solid var(--line); padding:.85rem 1.25rem; background:#fff; }
aside.side { grid-area:side; border-right:1px solid var(--line); padding:1.25rem 1rem; background:#f5f5f4; }
main.main { grid-area:main; padding:1.5rem 1.25rem 2rem; }
footer.foot { grid-area:foot; border-top:1px solid var(--line); padding:.85rem 1.25rem; color:var(--muted); background:#fff; }
ul.nav, ul.side-nav, ul.foot-nav { list-style:none; margin:0; padding:0; display:flex; flex-wrap:wrap; gap:.35rem 1rem; }
ul.side-nav { flex-direction:column; }
a { color:var(--ink); text-decoration:none; }
a:hover { color:var(--accent); }
"#;
const SHELL_WIDGETS: &str = r#"
.content.cards { display:grid; gap:1rem; margin-top:1.25rem; grid-template-columns:repeat(auto-fill,minmax(16rem,1fr)); }
.content.cards article { background:#fff; border:1px solid var(--line); border-radius:6px; padding:1rem; }
.main-intro h1 { margin:0 0 .75rem; font-size:2rem; }
@@ -349,6 +541,52 @@ a:hover { color:var(--accent); }
.pagination .page-status { color:var(--muted); }
"#;
fn normalize_shell_css(raw: &str) -> &'static str {
match raw.trim().to_ascii_lowercase().as_str() {
"" | "full" | "default" => "full",
"minimal" | "min" | "vars" => "minimal",
"off" | "none" | "false" | "0" => "off",
_ => "full",
}
}
fn shell_css_for(mode: &str) -> String {
match normalize_shell_css(mode) {
"off" => String::new(),
"minimal" => SHELL_VARS.to_string(),
_ => format!("{SHELL_VARS}{SHELL_LAYOUT}{SHELL_WIDGETS}"),
}
}
fn normalize_layout(raw: &str) -> String {
match raw.trim().to_ascii_lowercase().as_str() {
"" | "auto" | "default" => String::new(),
"sidebar" | "side" => "sidebar".into(),
"stacked" | "stack" | "column" => "stacked".into(),
"bare" | "main" | "none" => "bare".into(),
"rail" => "rail".into(),
other => other.to_string(),
}
}
fn resolve_shell_css(args: &Value) -> String {
let raw = args
.get("shell_css")
.or_else(|| args.get("壳样式"))
.and_then(|v| v.as_str())
.unwrap_or("full");
shell_css_for(raw)
}
fn resolve_layout(args: &Value) -> String {
let raw = args
.get("layout")
.or_else(|| args.get("布局"))
.and_then(|v| v.as_str())
.unwrap_or("");
normalize_layout(raw)
}
fn head_html(args: &Value, default_title: &str) -> String {
let meta = args.get("meta").and_then(|v| v.as_object());
let page_title = meta
@@ -407,7 +645,15 @@ fn head_html(args: &Value, default_title: &str) -> String {
}
if let Some(head) = args.get("head") {
let links = crate::assets::head_links_from_json(head);
s.push_str(&crate::assets::render_head_links(&links));
let asset_version = args
.get("asset_version")
.or_else(|| args.get("资源版本"))
.and_then(|v| v.as_str())
.unwrap_or("");
s.push_str(&crate::assets::render_head_links_with_version(
&links,
asset_version,
));
}
s
}
@@ -469,26 +715,58 @@ pub fn render_page_ex(
.get("title")
.and_then(|v| v.as_str())
.unwrap_or("Marqdo Web");
let extra = args
.get("styles_css")
.and_then(|v| v.as_str())
.unwrap_or("");
let shell = resolve_shell_css(args);
let layout = resolve_layout(args);
let parts = args
.get("parts")
.and_then(|v| v.as_object())
.cloned()
.unwrap_or_default();
let nav = resolve_links(args.get("nav"), db_url);
let side = resolve_links(args.get("sidebar"), db_url);
let foot = resolve_links(args.get("footer"), db_url);
let nav = resolve_links(args.get("nav"), db_url, Some(args));
let side = resolve_links(args.get("sidebar"), db_url, Some(args));
let foot = resolve_links(args.get("footer"), db_url, Some(args));
let (intro, items, total) = resolve_main(args, db_url);
let (nav_css, mq_pairs) = nav_media_class_map_many(&[&nav, &side, &foot]);
let extra_owned = {
let base = args
.get("styles_css")
.and_then(|v| v.as_str())
.unwrap_or("");
if nav_css.is_empty() {
base.to_string()
} else {
format!("{base}\n{nav_css}")
}
};
let extra = extra_owned.as_str();
let has_side = args.get("sidebar").is_some() || !side.is_empty();
let body_class = if has_side {
"has-sidebar"
} else {
"no-sidebar"
let bare = layout == "bare";
let body_class = match layout.as_str() {
"bare" => "layout-bare".to_string(),
"stacked" => "layout-stacked".to_string(),
"rail" => {
if has_side {
"has-rail has-sidebar".into()
} else {
"has-rail no-sidebar".into()
}
}
"sidebar" => {
if has_side {
"has-sidebar".into()
} else {
"no-sidebar".into()
}
}
"" => {
if has_side {
"has-sidebar".into()
} else {
"no-sidebar".into()
}
}
other => other.to_string(),
};
let mut main_html = String::new();
@@ -532,39 +810,61 @@ pub fn render_page_ex(
}
}
let style_block = if shell.is_empty() && extra.is_empty() {
String::new()
} else {
format!("<style>{shell}{extra}</style>")
};
let show_chrome = !bare;
let side_html = if show_chrome && has_side {
format!(
"<aside class=\"{}\"{}><span class=\"side-label\">侧栏</span>{}</aside>",
slot_class(args, "sidebar", "side"),
slot_attrs("sidebar", &parts, args),
render_ul_with_mq(&side, "side-nav", &mq_pairs)
)
} else {
String::new()
};
let header_html = if show_chrome {
format!(
"<header class=\"{}\"{}>{}</header>",
slot_class(args, "nav", "topnav"),
slot_attrs("nav", &parts, args),
render_ul_with_mq(&nav, "nav", &mq_pairs)
)
} else {
String::new()
};
let footer_html = if show_chrome {
format!(
"<footer class=\"{}\"{}>{}</footer>",
slot_class(args, "footer", "foot"),
slot_attrs("footer", &parts, args),
render_ul_with_mq(&foot, "foot-nav", &mq_pairs)
)
} else {
String::new()
};
format!(
r#"<!DOCTYPE html>
<html lang="zh-CN"><head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
{head}
<style>{SHELL_CSS}{extra}</style>
{style_block}
</head>
<body class="{body_class}">
<header class="{nav_class}"{nav_attrs}>{nav_ul}</header>
{header_html}
{side_html}
<main class="{main_class}"{main_attrs}>{main_html}</main>
<footer class="{foot_class}"{foot_attrs}>{foot_ul}</footer>
{footer_html}
</body></html>"#,
head = head_html(args, title),
nav_class = slot_class(args, "nav", "topnav"),
nav_attrs = slot_attrs("nav", &parts, args),
nav_ul = render_ul(&nav, "nav"),
side_html = if has_side {
format!(
"<aside class=\"{}\"{}><span class=\"side-label\">侧栏</span>{}</aside>",
slot_class(args, "sidebar", "side"),
slot_attrs("sidebar", &parts, args),
render_ul(&side, "side-nav")
)
} else {
String::new()
},
main_class = slot_class(args, "main", "main"),
main_attrs = slot_attrs("main", &parts, args),
foot_class = slot_class(args, "footer", "foot"),
foot_attrs = slot_attrs("footer", &parts, args),
foot_ul = render_ul(&foot, "foot-nav"),
)
}
@@ -577,21 +877,21 @@ pub fn render_fragment(args: &Value, db_url: Option<&str>) -> String {
.unwrap_or_else(|| "main".into());
match slot.as_str() {
"nav" => {
let links = resolve_links(args.get("nav"), db_url);
let links = resolve_links(args.get("nav"), db_url, Some(args));
format!(
"<header class=\"topnav\" data-slot=\"nav\">{}</header>",
render_ul(&links, "nav")
)
}
"sidebar" => {
let links = resolve_links(args.get("sidebar"), db_url);
let links = resolve_links(args.get("sidebar"), db_url, Some(args));
format!(
"<aside class=\"side\" data-slot=\"sidebar\"><span class=\"side-label\">侧栏</span>{}</aside>",
render_ul(&links, "side-nav")
)
}
"footer" => {
let links = resolve_links(args.get("footer"), db_url);
let links = resolve_links(args.get("footer"), db_url, Some(args));
format!(
"<footer class=\"foot\" data-slot=\"footer\">{}</footer>",
render_ul(&links, "foot-nav")
@@ -704,3 +1004,123 @@ fn render_article(it: &Map<String, Value>) -> String {
s.push_str("</article>");
s
}
#[cfg(test)]
mod shell_tests {
use super::*;
use serde_json::json;
#[test]
fn shell_off_omits_sidebar_grid() {
let page = json!({
"title": "t",
"shell_css": "off",
"layout": "stacked",
"sidebar": [{"label": "A", "href": "/a"}],
});
let html = render_page(&page, None, None);
assert!(html.contains("layout-stacked"));
assert!(!html.contains("has-sidebar"));
assert!(!html.contains("grid-template-columns:14rem"));
}
#[test]
fn shell_minimal_keeps_vars_not_cards() {
let page = json!({ "title": "t", "shell_css": "minimal" });
let html = render_page(&page, None, None);
assert!(html.contains("--ink:"));
assert!(!html.contains(".content.cards article"));
assert!(!html.contains("grid-template-columns:14rem"));
}
#[test]
fn layout_bare_skips_aside() {
let page = json!({
"title": "t",
"layout": "bare",
"sidebar": [{"label": "A", "href": "/a"}],
"nav": [{"label": "Home", "href": "/"}],
});
let html = render_page(&page, None, None);
assert!(html.contains("layout-bare"));
assert!(!html.contains("<aside"));
assert!(!html.contains("<header"));
}
#[test]
fn default_full_keeps_sidebar_grid() {
let page = json!({
"title": "t",
"sidebar": [{"label": "A", "href": "/a"}],
});
let html = render_page(&page, None, None);
assert!(html.contains("has-sidebar"));
assert!(html.contains("grid-template-columns:14rem"));
}
}
#[cfg(test)]
mod nav_tests {
use super::*;
use serde_json::json;
#[test]
fn when_hide_omits_item() {
let page = json!({
"title": "t",
"shell_css": "off",
"nav": [
{"label": "Home", "href": "/"},
{"label": "Secret", "href": "/x", "when": "hide"},
],
});
let html = render_page(&page, None, None);
assert!(html.contains(">Home<"), "{html}");
assert!(!html.contains("/x"), "{html}");
}
#[test]
fn when_auth_guest_respects_logged_in() {
let nav = json!([
{"front": "Public", "back": "/"},
{"front": "Admin", "back": "/admin", "when": "auth"},
{"front": "Login", "back": "/login", "when": "guest"},
]);
let guest = json!({
"title": "t",
"shell_css": "off",
"_logged_in": false,
"nav": nav,
});
let g = render_page(&guest, None, None);
assert!(g.contains("/login"), "{g}");
assert!(!g.contains("/admin"), "{g}");
let user = json!({
"title": "t",
"shell_css": "off",
"_logged_in": true,
"_nav_user": "alice",
"nav": nav,
});
let u = render_page(&user, None, None);
assert!(u.contains("/admin"), "{u}");
assert!(!u.contains("/login"), "{u}");
}
#[test]
fn media_emits_class_and_css() {
let page = json!({
"title": "t",
"shell_css": "off",
"nav": [
{"label": "Wide", "href": "/w", "media": "(min-width: 900px)"},
{"label": "Home", "href": "/"},
],
});
let html = render_page(&page, None, None);
assert!(html.contains("nav-mq-0"), "{html}");
assert!(html.contains("@media not (min-width: 900px)"), "{html}");
assert!(html.contains(">Home<"), "{html}");
}
}
+395 -112
View File
@@ -14,6 +14,10 @@ const PROP_KEYS: &[&str] = &["属性", "property", "prop", "名", "name"];
const VAL_KEYS: &[&str] = &["值", "value"];
const SEL_KEYS: &[&str] = &["选择器", "selector", "sel"];
const MEDIA_KEYS: &[&str] = &["媒体", "media", "mq", "@media"];
const WHEN_KEYS: &[&str] = &["当", "when", "if", "条件", "visible"];
const NAV_LABEL_KEYS: &[&str] = &["标签", "label", "title", "text", "名"];
const NAV_HREF_KEYS: &[&str] = &["链接", "href", "url", "path", "地址"];
pub fn normalize_ref(s: &str) -> String {
let s = s.trim();
@@ -214,7 +218,7 @@ pub fn as_rows(table: &Value) -> Value {
}
}
/// Bind table → `[{front,back,css}, …]`
/// Bind table → `[{front,back,css,media,when}, …]`
pub fn as_bind(table: &Value) -> Value {
match table {
Value::Array(rows) => {
@@ -224,8 +228,17 @@ pub fn as_bind(table: &Value) -> Value {
let front = normalize_ref(&pick(m, FRONT_KEYS).map(cell_str).unwrap_or_default());
let back = normalize_ref(&pick(m, BACK_KEYS).map(cell_str).unwrap_or_default());
let css = normalize_ref(&pick(m, CSS_KEYS).map(cell_str).unwrap_or_default());
let media =
normalize_ref(&pick(m, MEDIA_KEYS).map(cell_str).unwrap_or_default());
let when = normalize_ref(&pick(m, WHEN_KEYS).map(cell_str).unwrap_or_default());
if !front.is_empty() || !back.is_empty() {
out.push(json!({ "front": front, "back": back, "css": css }));
out.push(json!({
"front": front,
"back": back,
"css": css,
"media": media,
"when": when,
}));
}
}
}
@@ -235,14 +248,24 @@ pub fn as_bind(table: &Value) -> Value {
let fronts = pick(m, FRONT_KEYS).map(as_str_list).unwrap_or_default();
let backs = pick(m, BACK_KEYS).map(as_str_list).unwrap_or_default();
let csses = pick(m, CSS_KEYS).map(as_str_list).unwrap_or_default();
let medias = pick(m, MEDIA_KEYS).map(as_str_list).unwrap_or_default();
let whens = pick(m, WHEN_KEYS).map(as_str_list).unwrap_or_default();
let n = fronts.len().max(backs.len());
let mut out = Vec::new();
for i in 0..n {
let front = normalize_ref(&fronts.get(i).cloned().unwrap_or_default());
let back = normalize_ref(&backs.get(i).cloned().unwrap_or_default());
let css = normalize_ref(&csses.get(i).cloned().unwrap_or_default());
let media = normalize_ref(&medias.get(i).cloned().unwrap_or_default());
let when = normalize_ref(&whens.get(i).cloned().unwrap_or_default());
if !front.is_empty() || !back.is_empty() {
out.push(json!({ "front": front, "back": back, "css": css }));
out.push(json!({
"front": front,
"back": back,
"css": css,
"media": media,
"when": when,
}));
}
}
Value::Array(out)
@@ -251,6 +274,61 @@ pub fn as_bind(table: &Value) -> Value {
}
}
/// Nav / link table → row maps with label/href (and optional media/when/class).
/// Accepts bind rows (`front`/`back`) or author tables (`标签`/`链接`).
pub fn as_nav_rows(table: &Value) -> Vec<Map<String, Value>> {
let binds = as_bind(table);
let bind_arr = binds.as_array().cloned().unwrap_or_default();
if !bind_arr.is_empty() {
return bind_arr
.into_iter()
.filter_map(|v| v.as_object().cloned())
.collect();
}
as_rows(table)
.as_array()
.cloned()
.unwrap_or_default()
.into_iter()
.filter_map(|v| v.as_object().cloned())
.collect()
}
/// Pick label/href from a nav row (bind or 标签/链接 shape).
pub fn nav_label_href(m: &Map<String, Value>) -> (String, String) {
let label = pick(m, NAV_LABEL_KEYS)
.or_else(|| m.get("front"))
.map(cell_str)
.map(|s| normalize_ref(&s))
.unwrap_or_default();
let href = pick(m, NAV_HREF_KEYS)
.or_else(|| m.get("back"))
.map(cell_str)
.map(|s| normalize_ref(&s))
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "#".into());
(label, href)
}
pub fn nav_media_when_class(m: &Map<String, Value>) -> (String, String, String) {
let media = pick(m, MEDIA_KEYS)
.or_else(|| m.get("media"))
.map(cell_str)
.map(|s| normalize_ref(&s))
.unwrap_or_default();
let when = pick(m, WHEN_KEYS)
.or_else(|| m.get("when"))
.map(cell_str)
.map(|s| normalize_ref(&s))
.unwrap_or_default();
let class = pick(m, CSS_KEYS)
.or_else(|| m.get("css"))
.map(cell_str)
.map(|s| normalize_ref(&s))
.unwrap_or_default();
(media, when, class)
}
/// Page table → `[{src,style,slot}, …]`
pub fn as_compose(table: &Value) -> Value {
match table {
@@ -310,13 +388,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,27 +408,35 @@ 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 {
as_css_named_checked(name, table, false).unwrap_or_default()
}
/// Like [`as_css_named`], but when `strict` is true, reject cells that look like
/// T5 evaluated a bare `/` (numeric/bool CSS values). Default mode warns on stderr.
pub fn as_css_named_checked(name: &str, table: &Value, strict: bool) -> Result<String, String> {
let name = normalize_ref(name);
if name.is_empty() {
return String::new();
return Ok(String::new());
}
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();
let vals_raw = pick(m, VAL_KEYS);
let vals = vals_raw.map(as_str_list).unwrap_or_default();
let medias = pick(m, MEDIA_KEYS).map(as_str_list).unwrap_or_default();
let n = props.len().max(sels.len()).max(vals.len());
if n == 0 {
return String::new();
return Ok(String::new());
}
if let Some(raw) = vals_raw {
check_css_value_cells(raw, &props, strict)?;
}
let rows: Vec<(String, String, String, String)> = (0..n)
.map(|i| {
@@ -359,115 +448,244 @@ 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();
let mut collected = 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() {
let Some(m) = row.as_object() else {
continue;
};
let prop = pick(m, PROP_KEYS).map(cell_str).unwrap_or_default();
if let Some(v) = pick(m, VAL_KEYS) {
note_css_value_cell(&prop, v, strict)?;
}
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")));
collected.push((
pick(m, MEDIA_KEYS).map(cell_str).unwrap_or_default(),
pick(m, SEL_KEYS).map(cell_str).unwrap_or_default(),
prop,
pick(m, VAL_KEYS).map(cell_str).unwrap_or_default(),
));
}
emit_css_rows(&collected, &name, &mut out);
}
_ => {}
}
out
Ok(out)
}
fn css_value_suspicious(v: &Value) -> Option<&'static str> {
match v {
Value::Number(_) => Some(
"numeric CSS value (likely bare `/` division such as `1 / 5`; quote the cell, e.g. `\"1 / 5\"`)",
),
Value::Bool(_) => Some("boolean CSS value (quote the cell if intentional)"),
_ => None,
}
}
fn note_css_value_cell(prop: &str, val: &Value, strict: bool) -> Result<(), String> {
let Some(why) = css_value_suspicious(val) else {
return Ok(());
};
let prop = if prop.trim().is_empty() {
"(value)"
} else {
prop.trim()
};
let msg = format!("ext/web style: suspicious cell for `{prop}`: {why}");
if strict {
Err(msg)
} else {
eprintln!("warning: {msg}");
Ok(())
}
}
fn check_css_value_cells(vals: &Value, props: &[String], strict: bool) -> Result<(), String> {
match vals {
Value::Array(a) => {
for (i, v) in a.iter().enumerate() {
let prop = props.get(i).map(|s| s.as_str()).unwrap_or("");
note_css_value_cell(prop, v, strict)?;
}
}
other => note_css_value_cell(props.first().map(|s| s.as_str()).unwrap_or(""), other, strict)?,
}
Ok(())
}
/// 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,
@@ -614,3 +832,68 @@ 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}");
}
#[test]
fn strict_rejects_numeric_css_value() {
let t = json!([
{"选择器": ".x", "属性": "grid-column", "值": 0},
]);
let err = as_css_named_checked("x", &t, true).unwrap_err();
assert!(err.contains("suspicious"), "{err}");
// Non-strict still emits (with warning on stderr).
let css = as_css_named_checked("x", &t, false).unwrap();
assert!(css.contains("grid-column: 0;"), "{css}");
}
#[test]
fn quoted_string_ok_in_strict() {
let t = json!([
{"选择器": ".x", "属性": "grid-column", "值": "1 / 5"},
]);
let css = as_css_named_checked("x", &t, true).unwrap();
assert!(css.contains("grid-column: 1 / 5;"), "{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** + **customization C0–C4**. **Browser embed (routes D/E/F, v0.3.4)**: `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** + **定制 C0–C4**。**浏览器挂载(路线 D/E/F,v0.3.4)**:`网页.客户端挂载` / `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
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env bash
# Wave B1 — offline constitution / OKF harness (no network required).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
MQ="${MARQDO_BIN:-$ROOT/target/release/marqdo}"
export MARQDO_EXT="${MARQDO_EXT:-$ROOT/.marqdo-ext}"
export MARQDO_AGENT_PLUGIN="${MARQDO_AGENT_PLUGIN:-$ROOT/.marqdo-ext/native/libagent.so}"
if [[ ! -x "$MQ" ]]; then
echo "missing $MQ — run: cargo build --release -p marqdo -p marqdo_plugin_agent" >&2
exit 1
fi
fail=0
run() {
local f="$1"
echo "==> $f"
if ! "$MQ" run "$f"; then
echo "FAIL $f" >&2
fail=1
fi
}
run tests/ext/agent-constitution-b0.mq.md
run tests/ext/agent-dump-context.mq.md
run tests/ext/agent-writeback-shadow.mq.md
run tests/ext/agent-kb-plan-hit.mq.md
run tests/ext/agent-context-budget-a3.mq.md
run tests/ext/agent-workbook-patch-a0.mq.md
run examples/agent-okf-flywheel/index.mq.md
run examples/agent-pong/index.mq.md
if [[ "${AGENT_HARNESS_LIVE:-}" == "1" ]]; then
export AGENT_LIVE=1
if [[ ! -f "$ROOT/.env" ]]; then
echo "AGENT_HARNESS_LIVE=1 needs repo-root .env (see .env.example)" >&2
exit 1
fi
run examples/agent-pong/index.mq.md
run tests/ext/agent-run-live.mq.md
fi
if [[ "$fail" -ne 0 ]]; then
echo "agent harness: FAILED" >&2
exit 1
fi
echo "agent harness: OK"
+30 -5
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)
@@ -134,13 +141,27 @@ import clock:lib/time.mq.md
- Instance methods stay `` > `obj`.method `` (backticks on the receiver only).
- `lib/…` resolves via `MARQDO_LIB`, cwd `lib/`, or `lib/` next to the `marqdo` binary.
- Design: [module-namespace.md](../../doc/design/module-namespace.md).
- Official optional extensions (`ext/`, not stdlib): install with `marqdo ext add llm|agent|web|quantum` (see `doc/design/ext-cli.md`). `ext/llm` — chat; `ext/agent` — document-driven agents: **step** (default writeback) / **plan** workbook ([ext-agent.md](../../doc/design/ext-agent.md), [ext-agent-plan.md](../../doc/design/ext-agent-plan.md)); **`ext/web`** — dynamic sites (W0–W7 + P3 complete; see below); **`ext/quantum`** — circuits + Q7 density/viz + Q8 themed SVG (see below).
- Official optional extensions (`ext/`, not stdlib): install with `marqdo ext add llm|agent|web|quantum` (see `doc/design/ext-cli.md`). `ext/llm` — chat; **`ext/agent`** — document-driven agents (see **ext/agent** below); **`ext/web`** — dynamic sites (see below); **`ext/quantum`** — circuits + Q7/Q8 (see below).
- Native plugins: `lib/plugin` — `## load` / `unload` / `list`. C ABI: `include/marqdo_abi.h`.
- Prefer `table.put` / `表.改` for list/map element updates; keep `json` for parse/stringify/quote (see `doc/design/stdlib-table.md`).
- Builtins (no import): `print`/`打印`, `input`/`输入`, `len`/`长度`, `str`/`文本`, `int`/`整数`; literals `True`/`真`, `False`/`假`, `None`/`空`; logic `and`/`且`, `or`/`或`, `not`/`非`.
Stdlib map: [reference.md](reference.md).
## Official extension: `ext/agent` (document-driven)
Install: `marqdo ext add agent` (ZH: `智能体`). Native: `cargo build --release -p marqdo_plugin_agent`.
**Constitution (do not dilute):**
1. **Code is documentation** — the runbook `.mq.md` is the model’s ground truth, not a hidden system prompt bag.
2. **Call site is first-class** — `build_step_context` injects path/function/line so the model knows where it is in the program.
3. **Document is the knowledge base (OKF)** — writeback → promote/solidify → reuse / `llm_free`; MCP/corpus are evidence only.
APIs: `# agent` / `# 智能体` → `## step` / `## plan`. Context: standing + task + **call site** + tools + budgeted source/skill + act protocol (`CALL:` / `READ:`).
Examples: [agent-pong](../../examples/agent-pong/) · [agent-okf-flywheel](../../examples/agent-okf-flywheel/). Harness: `scripts/agent-harness.sh`. Design: [ext-agent.md](../../doc/design/ext-agent.md) · Wave B: [agent-framework-2026-09.md](../../doc/research/agent-framework-2026-09.md). Dev LLM: copy [.env.example](../../.env.example) → `.env` (gitignored).
## Official extension: `ext/web` (dynamic sites)
Install: `marqdo ext add web` (ZH id: `网页`). Build native plugin first: `cargo build --release -p marqdo_plugin_web`.
@@ -172,11 +193,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 +246,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 +264,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
+3 -2
View File
@@ -44,16 +44,17 @@ 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 |
| `ext/agent.mq.md` | `ext/智能体.mq.md` | agent **framework** (layout now; LLM orchestration roadmap in `ext-agent.md`) |
| `ext/agent.mq.md` | `ext/智能体.mq.md` | document-driven **step** / **plan** + OKF;示例 `examples/agent-pong` · `agent-okf-flywheel`;Wave B:[agent-framework-2026-09.md](../../doc/research/agent-framework-2026-09.md) |
| `ext/web/web.mq.md` | `ext/web/网页.mq.md` | dynamic sites — see **ext/web** section below |
| `ext/quantum/quantum.mq.md` | `ext/quantum/量子.mq.md` | circuits + Q7 density/viz + Q8 themes — see **ext/quantum** below |
+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}");
Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff. Show more