diff --git a/.cursor/skills/marqdo-dev/SKILL.md b/.cursor/skills/marqdo-dev/SKILL.md index 3d9ed31..3932852 100644 --- a/.cursor/skills/marqdo-dev/SKILL.md +++ b/.cursor/skills/marqdo-dev/SKILL.md @@ -1,229 +1,14 @@ --- 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. +description: Write, refactor and verify Marqdo programs, standard libraries and extensions through the executable development handbook. Use native Marqdo file tools and marqdo call; extend capability gaps through plugins or explicit external tools. --- -# Marqdo development (author + library) +Read [the executable development entry](../../../skills/marqdo-dev/index.mq.md), then [the programming guide](../../../doc/library-development.mq.md). The same guide governs programs, libraries and executable SKILLs. For installed skills, resolve these paths against the Marqdo source checkout. -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. +Use `**statement**` to execute and `*return*` to return; write `[intent](actual code)` inside executable positions, and `access(coll, key)` to read collections. The guide provides real examples. Native file tasks live in [files.mq.md](../../../skills/marqdo-dev/files.mq.md): read, write, patch, search, inventory, audit and apply. Do not generate Python or shell programs for ordinary file operations. -## Non-negotiable: code is documentation +Prepare the native engineering plugin with the development entry before using its analysis or process tasks. The repository development binary is `target/debug/marqdo`; installed older binaries may need a bootstrap Cargo build through `lib/sys.mq.md exec`. All subsequent task execution uses `marqdo call`. Keep decisions and sequencing in readable mq.md; use a new extension or a documented foreign tool only for a real capability gap. -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. +The guide is authoritative for narrative over 50%, immediate parameter/return tables, inline statements and returns, GFM data, index.mq.md organization, recursive Markdown web components, failure evidence and verification. Read each task's contract and grant its actual effects. External processes retain their OS authority. Do not rewrite intentional test fixtures or restore removed compose_* APIs. -| 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 (copy these — not `json.set`) - -**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` | -``` - -**Agent / LLM result map** — one readable row, not a `json.parse` + `json.set` chain: - -```markdown -`out` = - -| status | task | result | llm_calls | tokens | -|--------|------|--------|-----------|--------| -| ok | `task` | `reply` | `llm_calls` | `tokens` | - -*out* -``` - -**Soft error pack** (transport / gate failure) — still a table humans can skim: - -```markdown -`pack` = - -| finish | text | error | usage | tool_calls | -|--------|------|-------|-------|------------| -| error | "" | `msg` | `usage0` | `empty_tc` | - -*pack* -``` - -**Optional / conditional key** — sparse `table.put` after the static table (one dynamic key only): - -```markdown -`out` = - -| status | task | -|--------|------| -| error | `task` | - -1. `err` - **out = > table.put in=`out` at="error" value=`err`** -2. * - **_ = 1** -``` - -**Empty list / empty map** — prefer stdlib seeds over `json.parse text=[]` / `{}`: - -```markdown -**empty_tc = > table.empty_list** -**empty_map = > table.empty_map** -``` - -**Single dynamic key from scratch** — 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** -``` - -**When `json.*` is OK:** `json.parse` / `json.stringify` / `json.quote` on **wire text**; `json.get` to read an opaque map. Never use `json.set` / `json.append` to *build* author-facing structures. - -### 3. Bad pattern (do not write — and do not copy from old `ext/ai`) - -```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** -**`out` = json.parse text={"status":"ok"}** -**`out` = json.set map=out key="task" value=task** -``` - -Matching surrounding **legacy** `json.set` in `ext/ai/*.mq.md` is **not** compliance. Refactor the call site to tables / `table.put` instead of extending the glue. - -## 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. -6. **Calls in narrative:** explain the action in its sentence, for example `` 读取之后得到**结果 = [读取文件](文件.读文本(路径=`路径`))**。 `` Return in the sentence with `` 完成后返回*结果*。 `` Keep real control structures and data tables separate when that improves reading. The label describes intent; the payload contains the actual call. See the executable library development guide. -7. **Do not use `##` inside `# main` for document sectioning** — those become nested functions. Use paragraphs / `---` breaks instead. -8. **Index:** use `access(collection, key)` (or `取`); `[描述](payload)` is executable occlusion, never an index by label. - -Browser client programs: prefer nested `import:` with `browser: lib/browser.mq.md` (no native plugin). Server sites: Artifact Metadata (`type: web|endpoint`) + `ext/web` facade + `ext/data` / `ext/security` / `ext/net` — see [ext-web-artifact.md](../../doc/design/ext-web-artifact.md). **Never** restore `compose_*` / `app.configure`. - -## Developing libraries (`lib/*`, `ext/*`) - -Start with the [executable library development guide](../../../doc/library-development.mq.md): parameter/return tables below headings, prose >50%, inline assignments/returns and occlusion labels. Single-file stdlib needs no index; multi-file extensions organize through index.mq.md. - -Design background + waves: [lib-code-as-docs.md](../../doc/design/lib-code-as-docs.md) · [roadmap/lib-ext-code-as-docs.md](../../doc/roadmap/lib-ext-code-as-docs.md). - -### 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`). -- Collection get: **`access(coll, key)`**; bracket labels are inert descriptions. Calls in examples may use `修饰 [fn] …` or classic `>` / bold. - -### Library checklist - -- [ ] Single-file stdlib is its own handbook; no forced index/module guide directory -- [ ] Parameter/type/default table directly below the function heading, then return contract -- [ ] Prose parameters; remove legacy `+` declarations in standard library sources -- [ ] Explain purpose, real input shape, output, failure and limits; narrative >50% per function -- [ ] Put assignments, occlusion calls and returns in explanatory sentences where natural; reserve separate blocks for real structure -- [ ] Use `[action](actual code)` inside return/statement markers for opaque host calls -- [ ] One actual example + short implementation; never pad prose to satisfy the ratio -- [ ] Public examples use **tables + helpers**, not json glue -- [ ] Read with `access(c, k)`; foreach `- [description](遍历 coll 为 item)` -- [ ] Function heading names the tool; tables and task explanation follow it -- [ ] 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 | `ext/web` Document/Endpoint + View tables | -| DB / cache / storage | `ext/data` | -| Auth / OIDC / RBAC | `ext/security` | -| 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 unused `json:` (or other) entries under nested `import:`. - -## 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) - -## 渐进式契约 + MLSP(Phase 2/3 落地后的开发戒律) - -- **契约实现**:`src/contract.rs`(类型词汇 / 三形状契约表解析 / 合并 / 四边界校验诊断); - `src/parse/mod.rs::extract_function_contract`(位置 + 形状双重判定,**在升参推断之前**执行; - 绑定表与普通文档表绝不吃 ⇒ 无契约文件零回归)。契约表从 body 移除——元数据永不执行。 -- **静态互查**:`src/check.rs`(`marqdo check [--json]`)——契约行 vs 升参推断形参双向漂移、 - 未知类型名、错位契约;Error ⇒ 非零退出。 -- **AI 工具面**:`src/mlsp.rs`(`marqdo mlsp`,行分隔 JSON)——`locate` / `syntax` / `validate` / - `repair_targets` / `schema`。语法唯一事实来源 = `parse::CORE_CONSTRUCTS`(CI 守卫与 - `doc/design/core-surface.md` 同步);MLSP 只加检索别名,**不定义语法**。 -- **准入戒律**:新特性先过 `doc/design/layers.md` 三层归属(Language 层改动须 ADR + core-surface); - 新契约形状/类型词汇 = 文档层扩展,进 `src/contract.rs`,不进词法/语法。 -- **错误出口唯一**:`src/load.rs::label_error` 已示范——装载层/任何新代码都**不许**把 - `Diagnostic` 拍平成字符串;错误链里必须能 `Diagnostic::find` 找回结构化诊断(AI/MLSP 面)。 +Use the development entry's audit task to discover and review maintained repository sources. Its failed Result retains every finding; write_report=True saves the same evidence under .marqdo/audit. It does not execute inspected source or treat known placeholder warnings as completed logic. diff --git a/.cursor/skills/marqdo-release/SKILL.md b/.cursor/skills/marqdo-release/SKILL.md index fd64d7a..906be08 100644 --- a/.cursor/skills/marqdo-release/SKILL.md +++ b/.cursor/skills/marqdo-release/SKILL.md @@ -1,215 +1,14 @@ --- name: marqdo-release -description: >- - Run a Marqdo product release: detect latest version and ask the user for the - next tag (or confirm mode), update CHANGELOG/README/skills/public docs, bump - Cargo and/or ext/VERSION, sync VS Code extension when needed, publish GitHub - Release assets, upload extension packs to Cloudflare R2 (ext.marqdo.com) and - GitHub, ship Ubuntu CLI via PPA (scripts/ppa-ship.sh), and print manual - commands when sudo/GPG/network steps need the user. Use when the user asks to - release, cut a version, publish vX.Y.Z, ext-only pack, PPA, 发版, 发布新版本, - or tag marqdo. +description: Prepare, publish and verify a user-authorized Marqdo full, cli or extension release through its executable mq.md handbook. Use for release versioning, immutable tags, matching CI gates, GitHub/R2 parity and Ubuntu PPA publication. --- -# Marqdo release +Read [the executable release entry](../../../skills/marqdo-release/index.mq.md) and use its task routing. Version and mode come from the user; an already stated choice remains authorized. Inspection of an old release does not authorize republishing it. Never infer a new version, replace a tag, force-push or bypass hooks. -Canonical release playbook for **cflmy/marqdo**. Read this skill **before** tagging or uploading assets. Details: [reference.md](reference.md). +Use `marqdo call` on the actual handbook headings. The repository development binary is `target/debug/marqdo`; prepare its engineering plugin through [the development entry](../../../skills/marqdo-dev/index.mq.md). File reading and authoring use native [file tools](../../../skills/marqdo-dev/files.mq.md). No Python release orchestrator is required. New OS/service capabilities belong at explicit plugin or external-tool boundaries; version decisions, retries and publication order remain readable mq.md. -## Hard rules +The entry preserves full/cli/ext deliverables, separate editor sources, clean-main tagging, bilingual authored notes, exact-commit Release and EK gates, both native platforms, GitHub/R2 identical bytes, VERSION-after-ZIP ordering and Ubuntu source/build/apt evidence. Every applicable obligation must be verified before declaring completion. Default full/cli work includes PPA; gh-pages deployment needs its own instruction. -1. **Never invent the next version.** Detect current versions → **stop and ask the user** for the next SemVer (`X.Y.Z`) and **release mode** if unclear. Do not proceed until they confirm (unless they already stated both in the same message). -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:** CLI/full → `vX.Y.Z` matching root `Cargo.toml`. Ext-only → `ext-vX.Y.Z` matching `ext/VERSION` (Cargo may stay unchanged). -6. Prefer **tag push → GitHub Actions** (`.github/workflows/release.yml`) for Windows/Linux install assets. Local packaging is fallback / verification. -7. After network errors: apply [reference.md § Proxy](reference.md). **First try** `https://proxy.cflmy.top/github.com/cflmy/marqdo.git`. Retry; do not silently skip uploads. If needed: **HK jump** (`scripts/push-via-hk-jump.py`). -8. **Do not ship a full GitHub Release without the Linux extension/native zip** when the mode includes ext packs. Missing Linux packages = incomplete for that mode. -9. **Extension packs always publish to both** Cloudflare R2 (`https://ext.marqdo.com` via `scripts/upload-ext-r2.py`) **and** GitHub (Release assets / `ext-v*` tag). Credentials only in `~/.marqdo/r2.env` / CI — **never** commit. See [ext-cdn.md](../../../doc/design/ext-cdn.md). -10. **CLI Ubuntu package = PPA** (`ppa:cflmy/marqdo`) via `./scripts/ppa-ship.sh` / `ppa-build-source.sh`. GitHub zips remain for Windows and non-apt Linux. -11. **When a step needs the user** (sudo password, GPG passphrase, Launchpad UI, interactive `dput`): **stop, state what failed, and give the exact commands** to run in their terminal. Do not pretend the step succeeded. -12. **GitHub auto-build must be green before declaring a release done.** For full/cli: wait for the tag-triggered **Release** workflow (`windows` + `linux`) **and** the push-triggered **`executable-knowledge`** workflow on the release commit / `main` tip. Release asset zips alone are **not** sufficient — a green Release job with a red EK gate is an incomplete release. Do not skip or reframe a red `executable-knowledge` as “assets already uploaded.” +Read-only status and verification are separate from publication. Grant effects stated by each task. Inspect Result.ok before value; use --require-ok when an external automation must stop on a failed Result. Credentials stay in their existing private stores. Interactive sudo/GPG/dput or a failed service request remains incomplete: report the concrete failure and the exact handbook recovery call, preserving local evidence. -## Release modes - -Ask (or take from user message) which mode: - -| Mode | Bumps | Git tag | GitHub assets | R2 CDN | Ubuntu PPA | -|------|-------|---------|---------------|--------|------------| -| **full** (default) | `Cargo.toml` + `ext/VERSION` (same SemVer) | `vX.Y.Z` | CLI + ext + native + VSIX + … | yes | yes | -| **cli** | `Cargo.toml` only | `vX.Y.Z` | CLI (+ optional attach prior ext) | no (unless user asks) | yes | -| **ext** | `ext/VERSION` only | `ext-vX.Y.Z` (or attach to latest CLI release) | ext.zip + native-*.zip | **required** | no | - -Defaults after version+mode confirmed — **do not re-ask**: - -| Setting | Default | -|---------|---------| -| Sync / bump `vscode-extension` to same `VER` | **yes** for full/cli; **no** for ext-only | -| Push `main`, create annotated tag, push tag (trigger CI) | **yes** for full/cli | -| Ext packs → R2 **and** GitHub | **yes** whenever ext ships | -| Ubuntu PPA upload after CLI tag | **yes** for full/cli | -| Release notes language | **中英双语** | -| Deploy gh-pages after release | **no** (only if user asks) | - -Phase 0 ask example: - -> 当前最新 CLI **vA.B.C**,扩展包 **E.F.G**。请指定下一个版本号与模式(`full` / `cli` / `ext`,如 `1.0.3 full`)。 - -## Phase 0 — Detect versions (mandatory stop) - -```bash -python3 .cursor/skills/marqdo-release/scripts/detect_version.py -``` - -Report briefly, then **ask for SemVer + mode** (unless already given). Normalize `VER` / `TAG`. - -## Phase 1 — Preflight - -``` -Release progress: -- [ ] Phase 0: version + mode confirmed -- [ ] Phase 1: preflight green -- [ ] Phase 2: docs + version bumps committed -- [ ] Phase 3: extension branch (full/cli) -- [ ] Phase 4: main pushed; tag created & pushed -- [ ] Phase 5: CI / GitHub assets / notes -- [ ] Phase 6: R2 upload (if ext ships) -- [ ] Phase 7: Ubuntu PPA (full/cli) -- [ ] Phase 8: post-release checks -``` - -Checks: clean tree; `main` ff-only; smoke tests; CHANGELOG Unreleased; no secrets. -Also confirm the latest `main` **`executable-knowledge`** Actions run is green (or that this release commit will be covered after push) — do not proceed to tag if EK is already red on tip without a fix in the same release PR. - -## Phase 2 — Docs & version bumps (main) - -| File | full | cli | ext | -|------|------|-----|-----| -| `Cargo.toml` + `crates/marqdo-wasm/Cargo.toml` | bump | bump | — | -| `ext/VERSION` | bump | — | bump | -| `CHANGELOG.md` | `## vVER`(含**核心表面 Δ**,见 `doc/design/layers.md`) | same | `## Ext pack vVER` | -| `README.md` / `public/**` install + download table | update | update | update ext notes | -| `.cursor/skills/marqdo/SKILL.md` | if surface changed | same | rare | -| `.github/workflows/release.yml` Highlights stub | yes | yes | — | - -```bash -./scripts/build-public.sh # when public/ sources changed -``` - -Commit + push `main` (proxy origin). On push failure → reference § Proxy; if still blocked, **print** for the user: - -```bash -git push https://proxy.cflmy.top/github.com/cflmy/marqdo.git HEAD:main -# or: python3 scripts/push-via-hk-jump.py -``` - -## Phase 3 — VS Code / Cursor extension (full/cli only) - -Default: bump `vscode-extension` package.json to `VER`, compile, push branch `vscode-extension`, return to `main`. - -## Phase 4 — Tag & trigger CI (full/cli) - -```bash -git tag -a "vVER" -m "vVER" -git push origin "vVER" -``` - -Ext-only: - -```bash -git tag -a "ext-vVER" -m "ext-vVER" -git push origin "ext-vVER" -``` - -(or build zips locally / via workflow and `gh release upload`). - -If tag push needs the user: - -```bash -git push https://proxy.cflmy.top/github.com/cflmy/marqdo.git vVER -``` - -## Phase 5 — GitHub Release notes & assets - -1. Wait for Actions (full/cli): - - Tag **Release** workflow: both `windows` and `linux` green when ext natives required. - - Push **`executable-knowledge`** workflow on the release commit / `main`: **must be success**. Poll with `gh run list --workflow=executable-knowledge.yml --branch main` / `gh run watch`. If EK is red → **stop**; fix plugin/harness on `main`, re-run; do **not** declare the release complete from assets alone. -2. Rewrite release body 中英双语 — [reference.md § Notes](reference.md). -3. Confirm Linux `marqdo-VER-native-x86_64-unknown-linux-gnu.zip` when mode ships ext. - -## Phase 6 — Extension CDN (R2) — required when ext ships - -```bash -# credentials: ~/.marqdo/r2.env (never commit) -python3 scripts/upload-ext-r2.py --version VER --from-dir dist/ -curl -fsS https://ext.marqdo.com/latest/VERSION -``` - -Also ensure the **same** zips are on GitHub (`vVER` or `ext-vVER`). If R2 credentials missing, **tell the user**: - -```bash -# put keys in ~/.marqdo/r2.env then: -python3 scripts/upload-ext-r2.py --version VER --from-dir dist/ -``` - -## Phase 7 — Ubuntu PPA (full/cli) - -Linux CLI for apt users. After `Cargo.toml` is at `VER` and `debian/changelog` has a matching `VER-1ppaN` stanza: - -```bash -./scripts/ppa-ship.sh noble -``` - -Packaging notes / noble Cargo.lock v4: [ubuntu-ppa.md](../../../doc/design/ubuntu-ppa.md). - -**If the agent cannot sudo / sign / dput**, print exactly: - -```bash -cd ~/work/marqdo -./scripts/ppa-ship.sh noble -# or build then upload: -./scripts/ppa-build-source.sh noble -dput ppa:cflmy/marqdo ../build-area/marqdo_*~noble_source.changes -``` - -Watch: https://launchpad.net/~cflmy/+archive/ubuntu/marqdo/+builds -On Launchpad failure: read the build log, fix `debian/` or bundle script, bump `1ppaN`, re-upload. Tell the user the new `dput` command. - -## Phase 8 — Post-release - -1. `gh release view TAG` — assets + notes. -2. Confirm **`executable-knowledge`** and **Release** Actions are both green for this tag/commit; if either is red, say so and do not claim “发版完成”. -3. CDN `https://ext.marqdo.com/vVER/` (if ext shipped). -4. PPA build green (if cli shipped). -5. Tell user URLs: GitHub release, CDN, PPA install one-liner. -6. Optional gh-pages only if asked. - -## Extension-only release (mode=ext) - -1. User confirms **ext** SemVer (may differ from CLI). -2. Bump `ext/VERSION`; CHANGELOG → `## Ext pack vVER`. -3. Build/package `marqdo-VER-ext.zip` + `marqdo-VER-native-*.zip` (CI or local). -4. Upload to **R2 and GitHub** (required both). -5. Do **not** retag CLI / do **not** PPA unless user also asked for cli. - -## Failure matrix (short) - -| Failure | Action | -|---------|--------| -| `gh` / git TLS or Clash `7890` refused | Unset bad proxy; see [reference § Proxy](reference.md) | -| GitHub blocked | proxy.cflmy.top, then HK jump; **print commands** if agent cannot push | -| Tag exists | Stop; ask user | -| CI red (Release assets) | Fix on main; retag only if user allows | -| `executable-knowledge` red | Fix agent plugin / test harness (e.g. `ensure_agent_plugin_built`); push `main`; wait for EK green. **Do not** treat uploaded Release zips as a successful release | -| R2 upload fails | Print `upload-ext-r2.py` command; do not skip silently | -| PPA / sudo / GPG | Print `./scripts/ppa-ship.sh noble` (or `dput …`); do not skip silently | -| Launchpad `Cargo.lock` v4 / old cargo | Ensure bundled `third_party/rust` via current `ppa-build-source.sh`; bump `1ppaN` | -| Linux native zip missing (full/ext) | Incomplete — fix linux job or upload | - -## Do not - -- Ship without user-confirmed version (and mode when ambiguous). -- Ship ext packs to only one of R2 / GitHub. -- Call a full/cli release done without attempting PPA **or** giving the user the PPA commands. -- Commit `target/`, `dist/`, `*.wasm`, `third_party/rust/`, or `public/**/*.html` unless policy changes. -- Merge extension tree into `main`. +Independent extension releases commit reviewed bilingual notes at doc/releases/ext-X.Y.Z.md before tagging. The [pack handbook](../../../skills/marqdo-release/packs.mq.md) and extension-release.yml run native staging, both platform builds, exact-tag release creation and non-clobbering gh asset upload through marqdo call. An existing upload is inspected rather than replaced. Windows execution remains a CI obligation; a local Linux ZIP cannot prove it. diff --git a/.cursor/skills/marqdo-release/reference.md b/.cursor/skills/marqdo-release/reference.md index 835a162..50c4d95 100644 --- a/.cursor/skills/marqdo-release/reference.md +++ b/.cursor/skills/marqdo-release/reference.md @@ -1,406 +1,3 @@ -# Marqdo release — reference +# Release task 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** (`windows` job) and **ubuntu-latest** (`linux` job, **required**, `needs: windows`): - -| Asset | Role | Job | -|-------|------|-----| -| `marqdo-VER-x86_64-pc-windows-msvc.exe` | CLI (stdlib embedded) | windows | -| `marqdo-VER-x86_64-pc-windows-msvc.zip` | `marqdo.exe` + `lib/` + `ext/` + native DLL | windows | -| `marqdo-VER-stdlib.zip` | `lib/` only | windows | -| `marqdo-VER-ext.zip` | Official `ext/` L1 | windows | -| `marqdo-VER-native-x86_64-pc-windows-msvc.zip` | Prebuilt Windows plugins (`native/*.dll`) | windows | -| `marqdo-VER-native-x86_64-unknown-linux-gnu.zip` | Prebuilt Linux plugins (`native/lib*.so`) — **must ship** | linux | -| `marqdo-VER-x86_64-unknown-linux-gnu.zip` | Linux CLI + `lib/` + `ext/` + native `.so` — **must ship** | linux | -| `marqdo-VER-source.zip` | `git archive` of tagged commit | windows | -| `marqdo-VER.vsix` | VS Code / Cursor (from branch `vscode-extension`) | windows | -| `marqdo-VER-public.zip` | Static user docs (`marqdo view output public`) | windows | - -Not CI-uploaded (document in notes): macOS build from source; WASM via `marqdo wasm build` → `dist/wasm/`. - -A release **without** the Linux native zip is incomplete (`marqdo ext add` on Linux cannot download prebuilts). - -## 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 -p marqdo_plugin_linalg -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/` + `ext/`(含 native) | -| `marqdo-*-unknown-linux-gnu.zip` | Linux CLI + `lib/` + `ext/` + `.so` | -| `marqdo-*-native-*.zip` | 预编译 `web`/`agent`/`quantum`/`linalg`(Win + **Linux 必出**) | -| `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 Clash on `127.0.0.1:7890`, flaky GitHub TLS, `gh` needing token, Cursor agent sandbox with only `lo`. - -### `proxy.cflmy.top` (try this first) - -This machine’s `origin` is typically: - -``` -https://proxy.cflmy.top/github.com/cflmy/marqdo.git -``` - -Push / fetch / tag through that remote (HTTPS reverse proxy to GitHub): - -```bash -git remote -v # confirm origin uses proxy.cflmy.top -git push origin main -git push origin vVER -git push origin vscode-extension - -# one-shot if origin still points at github.com: -git push https://proxy.cflmy.top/github.com/cflmy/marqdo.git HEAD:main -git push https://proxy.cflmy.top/github.com/cflmy/marqdo.git vVER -``` - -Short GETs via the proxy often work; **long `git push` may still time out**. If push hangs or drops, skip Clash retries and go to **HK SSH jump** below. - -`gh` / Release API can use the same path reverse-proxy: - -| Path prefix | Upstream | -|-------------|----------| -| `/github.com/` | `https://github.com/` | -| `/api.github.com/` | `https://api.github.com/` | -| `/uploads.github.com/` | `https://uploads.github.com/` (Release asset POST; OpenResty on HK) | - -```bash -# Upload a Release asset through proxy.cflmy.top (Content-Type: application/octet-stream) -curl -X POST \ - -H "Authorization: Bearer $GH_TOKEN" \ - -H "Accept: application/vnd.github+json" \ - -H "Content-Type: application/octet-stream" \ - --data-binary @dist/FILE.zip \ - "https://proxy.cflmy.top/uploads.github.com/repos/cflmy/marqdo/releases/RELEASE_ID/assets?name=FILE.zip" -``` - -Do **not** rewrite `Host: uploads.github.com` against `proxy.cflmy.top` without the `/uploads.github.com/` path prefix — that returns 404. - -### Diagnose - -```bash -env | grep -iE 'proxy|PROXY' || true -curl -sI --max-time 15 https://github.com | head -5 -curl -sS --max-time 15 -o /dev/null -w 'proxy=%{http_code}\n' https://proxy.cflmy.top/ || true -gh auth status -ip -br addr | head -5 # agent may lack enp*; use required_permissions: ["all"] -``` - -### Fix order - -1. **Unset bad proxy** if connection refused: - -```bash -unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY all_proxy -# also clear for one git call: git -c http.proxy= -c https.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. **HK SSH jump (preferred when GitHub is blocked but HK is reachable)** — see next subsection. - -7. **Partial upload**: - -```bash -gh release upload "vVER" dist/FILE --clobber -``` - -8. **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). - -**Also required before declaring release done:** the push-triggered **`executable-knowledge`** workflow on the release commit / `main` tip must be **success**. Poll with: - -```bash -gh run list --workflow=executable-knowledge.yml --branch main --limit 5 -gh run watch -``` - -A green Release asset job with a red `executable-knowledge` gate is an **incomplete** release — fix the plugin/harness (e.g. `ensure_agent_plugin_built` for agent-dependent EK tests), push `main`, and wait for EK green. Do not skip. - -### HK SSH jump (Paramiko CONNECT) - -**When to use:** local → GitHub fails (timeout / TLS / Clash flaky / reverse-proxy `proxy.cflmy.top` connect drops), but this host can reach an overseas box that has stable GitHub (default `hk.cflmy.de`). Proven path for v0.3.9 push/tag/`gh`. - -**Do not** rely on OpenSSH + `sshpass` here — password auth has hung; use **Paramiko** (`python3-paramiko`). - -**Never** commit the HK root password or tokens. Ask the user for the password (or a key), put it in env / a `600` temp file, scrub after. - -```bash -# one-shot password file (example — use the secret the user gave this session) -printf '%s' "$HK_PASSWORD_FROM_USER" > /tmp/.hk_ssh_pw && chmod 600 /tmp/.hk_ssh_pw - -export HK_SSH_HOST=hk.cflmy.de # or 83.229.126.119 -export HK_SSH_USER=root -export HK_SSH_PASSWORD_FILE=/tmp/.hk_ssh_pw -# optional: HK_JUMP_PORT=18081 - -SCRIPT=.cursor/skills/marqdo-release/scripts/push-via-hk-jump.py - -# push / tag / extension (git gets CONNECT proxy + github.com askpass) -python3 "$SCRIPT" -- git push origin main -python3 "$SCRIPT" -- git push origin vscode-extension -python3 "$SCRIPT" -- git push origin vVER - -# gh (sets GH_TOKEN from git credential fill if unset) -python3 "$SCRIPT" -- gh release edit vVER --notes-file /tmp/notes.md -python3 "$SCRIPT" -- gh run list --workflow=Release --limit 3 - -# leave proxy up for manual commands -python3 "$SCRIPT" --serve # then: export https_proxy=http://127.0.0.1:18081 - -rm -f /tmp/.hk_ssh_pw -``` - -Script behavior: SSH to HK → local `http://127.0.0.1:$HK_JUMP_PORT` HTTP CONNECT via `direct-tcpip` → run `git`/`gh`/`curl` with that proxy. Git auth uses local `git credential` via `http.extraHeader` (Basic) — **not** `GIT_ASKPASS` (askpass has hung under agent/no TTY). Tokens never go to the jump host disk. - -Optional path reverse-proxy (`https://proxy.cflmy.top/github.com/…` `insteadOf`) may work for short GETs; treat long `git push` failures as a signal to use the HK jump instead of retrying Clash forever. -## 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 — - -``` - -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 发版、发布说明中英双语。 -若要改默认请一并说明。 -``` +Use [the executable release entry](../../../skills/marqdo-release/index.mq.md) and [its maintained task reference](../../../skills/marqdo-release/reference.md). File authoring, mode rules, native service/process boundaries and recovery live with the actual mq.md tasks. Do not reconstruct the former Python or terminal playbook from historical copies. diff --git a/.cursor/skills/marqdo/SKILL.md b/.cursor/skills/marqdo/SKILL.md index 37afebb..2254761 100644 --- a/.cursor/skills/marqdo/SKILL.md +++ b/.cursor/skills/marqdo/SKILL.md @@ -1,281 +1,62 @@ --- name: marqdo -description: >- - Author and edit Marqdo programs (.mq.md): Markdown markers are executable - syntax (functions, calls, statements, returns, control flow). Use when writing - or modifying .mq.md files, teaching Marqdo, generating Marqdo from prose, - importing lib/* or ext/web or ext/quantum, running marqdo CLI, building dynamic - sites with ext/web, quantum circuits with ext/quantum, or when the user - mentions Marqdo, mq.md, markup-as-syntax, code-as-documentation, web/网页, or - quantum/量子 extension (ZH under ext/quantum/量子/). +description: Author, run and review readable Marqdo programs, libraries and executable knowledge. Use for .mq.md, marqdo call, Document/Endpoint/Resource web projects and quantum tools; read the executable programming and development handbooks. --- -# Marqdo development +# Marqdo -Marqdo = **Markdown markers as syntax**. A `.mq.md` file is both documentation and a runnable program. Read this skill **before** inventing syntax from Markdown habits or Python. + - +## CORE SYNTAX -## CORE SYNTAX (v2.1 Occlusion — mandatory) +Occlusion is the current default. `**…**` executes a statement; `*…*` returns. +Use `[intent](actual code)` in an executable position: the label is prose and +only its payload executes. Empty parentheses are a pending None stub. +Read collections with `access(coll, key)`. Classic indexing is only for explicit +legacy sources and migration. Reading narrative references never runs effects. -These rules are the **current default**. Do **not** teach Classic `[key](map)` index or “bold is return of print”. Classic migration only: [migration-classic.md](migration-classic.md). - -1. **File suffix** `.mq.md`. Print with `> print text=…` / `> 打印 内容=…` — never use `**…**` to print. -2. **`**…**` = statement** (assign / call / expression). `*…*` = return. Closing markers touch the last token (no trailing space). -3. **`[描述](payload)` = occlusion:** `[]` is prose (never executed); `()` is the only executed part. Empty `()` → `None` stub. -4. **Read collections with `access(coll, key)`** (aliases `取` / `取值`). **Never** use `[key](map)` as index under default Occlusion. -5. **Foreach:** `- [描述](遍历 coll 为 item)` (`遍历`/`for`, `为`/`as`/`in`). Prefer explicit traversal when generating new code. -6. **Import / call:** frontmatter `import:` / `导入:`; call `lib.member`. One language (EN or ZH) per file. -7. **Control flow:** `#` object/type, `##`+ function, prose params (legacy `+` remains parseable), `1.`/`2.` branches, `-` loops, `N. *` else. No invented `if`/`for`/`def`/`return` keywords. -8. **Prose vs code:** blank line separates comment paragraphs from executable lines. -9. **GFM tables** for data; prefer `table.put` over `json.set` chains. `ext/**` never calls `host_*`. -10. Body narrative `[描述](target)` is lazy (NarrativeRef) — reading does not execute side effects. - -| Marker | Meaning (v2.1) | -|--------|----------------| -| `#` / `##`+ | Object/type · function/method | +| Marker | Meaning | +|---|---| | `**…**` | Statement (assign / call / expression) | | `*…*` | Return | -| `[描述](payload)` | Occlusion step (payload executes) | +| `[intent](payload)` | Readable intent with executable payload | | `access(c, k)` | Collection read | -| `> fn …` | Call | -| GFM table | Collection literal | - -Canonical: `doc/design/core-surface.md`, `doc/design/document-native-development-guide.md`. Deeper tables: [reference.md](reference.md). Patterns: [examples.md](examples.md). Authoring craft: [marqdo-dev](../marqdo-dev/SKILL.md). Release: [marqdo-release](../marqdo-release/SKILL.md). - -Executable-knowledge gate: [`tests/executable_knowledge/`](../../tests/executable_knowledge/README.md). - -## Hard rules (do not violate) - -1. Obey **CORE SYNTAX** above — Occlusion is default; do not emit Classic index links. -2. **Identifiers:** declare library parameters in prose as `` input `name` `` (defaults follow `=`); inside `*…*` / `**…**` bare ids are variables. Quote text literals. Standalone `>` calls: backticks where bare would be text. -3. **Structure lines** (`#` `>` `+` `-` `|`) are not wrapped in italics. -4. **Paths:** bare `/` in expressions is division; in call args / table cells unspaced `a/b` is path text. Ratios as text need quotes (`"1/5"`). -5. End side-effect-only helpers with `*None*` / `*空*` / `**` / `****` when the outer function continues. Lone `---` is a thematic break, not function end. -6. **`ext/**` never calls `host_*`.** Prefer tables over `json.set` / `json.append`. -7. **One language per file.** Sandbox trial before promoting Agent-generated trees. -8. Browser: Marqdo on WASM + `lib/browser` tables; do not hand-write business JS. - - -## Call one function - -```markdown -# 计算器 - -## 加法 - -计算两个数字`a`和`b`的和。 - -*[计算结果](a + b)* -``` - -``` -marqdo call calculator.mq.md 计算器.加法 a=2 b=3 -``` - -prints `5`. The same command works on any `.mq.md`; the file does not need a special skill name. - -## Minimal program - -```markdown -# main - -> print text=Hello World! -``` - -Chinese builtins (same functions, no import): - -```markdown -# main - -> 打印 内容=你好 -``` - -## Functions, calls, end-body - -```markdown -# main - -> greet who=Marqdo - -## greet - + `who` - -> print text=Hello, `who`! - -*None* -``` - -- Call: `> name key=value` or `> name value`. -- Nested helpers use deeper `#` (`##`, `###`, …). -- After a helper with only side effects, end with `*None*` / whole-line `**` / `****` when later lines must stay in the outer function. Lone `---` is only a thematic break (skipped). -- In bold assigns, prefer bare calls: `**摘要 = 结账摘要 …**` (omit `>`). - -## Statements, returns, branches - -```markdown -**x = 1** -**y = x + 2** - -## add_one - + `n` - -*n + 1* -``` - -```markdown -*n = 0* - -1. `n` > 0 - > print text=positive -2. `n` < 0 - > print text=negative -3. * - > print text=zero -``` - -## Frontmatter imports + stdlib - -A standard library is normally one `lib/*.mq.md` file: read/import/call that file directly. It is its own manual and skill; no `index.mq.md` or module handbook directory is required. Each function puts parameter/default and return tables directly below its heading, explains purpose, failures and limits, and keeps narrative above 50%. Use prose parameters, not legacy `+` declarations. Describe opaque instructions with `[what it does](actual code)` inside statement/return markers; labels do not execute. Multi-file extensions use an index to organize their files. File tools require explicit `--effects fs.read` or `--effects fs.write` with `--fs-root`; real workflows live in `examples/stdlib-handbook`. Read the [executable authoring guide](../../../doc/library-development.mq.md) for inline prose and complete runnable examples. - - -Imports use nested YAML `import:` (`导入` equivalent): file (`.mq.md`) or short name (`lib.member`). Members are **not** flattened into the caller. Call with a bare dotted path: - -```markdown ---- -title: example -import: - text: lib/text.mq.md - clock: lib/time.mq.md ---- - -# main - -**xs = > text.split value="a,b,c" sep=","** -> print text=`xs` -**t = > clock.now_unix** -``` - -- Import **English** or **Chinese** library file; call that file’s API names via `lib.member` (do not mix languages). -- 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 (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/) · [agent-sandbox-okf](../../examples/agent-sandbox-okf/). Harness: `scripts/agent-harness.sh`. Design: [ext-agent.md](../../doc/design/ext-agent.md) · optimize O1–O5: [ext-ai-optimize.md](../../doc/roadmap/ext-ai-optimize.md). Dev LLM: copy [.env.example](../../.env.example) → `.env` (gitignored). - -**Sandbox (O1):** `import sandbox:ext/ai/sandbox.mq.md` · `agent.trial` / `智能体.试跑` · `run`/`step` take `sandbox=` / `沙盒=` (default `False`). Profile caps are tables via `sandbox.profile`. Gold: `tests/ext/agent-sandbox-optin.mq.md`. - -## Official extension: `ext/web` (Document / Endpoint / Resource) - -Install: `marqdo ext add web` (ZH id: `网页`). See ADR 0007 · [ext-web-artifact.md](../../doc/design/ext-web-artifact.md). - -**Do not degrade:** Document/Endpoint metadata; facade `web.page|route|serve|render|inspect`; View `|type|slot|value|attrs|style|` only; no `compose_*` / `configure` / author `ensure_plugin`. DB → `ext/data`; auth → `ext/security`; net → `ext/net`. - -- **Root skill (agents first):** [`ext/web/index.mq.md`](../../ext/web/index.mq.md) · ZH [`ext/web/网页/索引.mq.md`](../../ext/web/网页/索引.mq.md)(作者门面仍为 `网页.mq.md`) -- **Layout law (in-package):** file-partition pages (nav/sidebar/footer/…) until simple; no HTML/CSS injection as default — [`ext/web/layout/index.mq.md`](../../ext/web/layout/index.mq.md) · [ext-web-layout-paradigm.md](../../doc/design/ext-web-layout-paradigm.md) -- **Recursive practice:** home → nav/main/footer → footer brand/links → links docs/community; continue until a leaf is plain Markdown. Parents import children and declare one relationship. Use `component.markdown`, `component.wrap`, `layout.stack`, and `layout.columns`; merge alone gives siblings, not columns. -- **Runnable reference:** [web-layout-handbook](../../../examples/web-layout-handbook/index.mq.md) and [Chinese reference](../../../examples/web-layout-handbook-zh/index.mq.md). A composed Document declares `view: main` and returns node rows at startup; ordinary Documents keep their Markdown/data-source path. Use `inspect root=...` for disk routes, and `run` for a live server. -- EN author facade: `import web:ext/web/web.mq.md` -- Agent: `marqdo call ext/web/layout/index.mq.md rules --json` then facade tools with `--effects plugin` - -Design: [ext-web-artifact.md](../../doc/design/ext-web-artifact.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/). - -## Official extension: `ext/quantum` (circuits + Q7/Q8) - -Install: `marqdo ext add quantum` (ZH id: `量子`). Build: `cargo build --release -p marqdo_plugin_quantum`, then **`marqdo ext add quantum` again** so view loads the new `libquantum.so` (stale plugin = old black/white circuits). - -- **Root skill (read first):** [`ext/quantum/index.mq.md`](../../ext/quantum/index.mq.md) — explains every module and exact `marqdo call` commands for agents with no other context. -- **Ext paradigm:** [`doc/design/ext-skill-tools-paradigm.md`](../../doc/design/ext-skill-tools-paradigm.md) — code=doc=skill=tools; checklist for new packs. -- **Modules:** `circuit/` · `gate/` · `simulate/` · `state/` · `density/` · `viz/` · `_capability/` (each has `index.mq.md`). ZH package: `ext/quantum/量子/`(根 `索引.mq.md`,模块同名中文目录). -- **Agent:** `marqdo call ext/quantum//index.mq.md … --effects plugin` (`--toget` / `$name`). Narration: `marqdo check --narrative-ratio FILE`. -- **Author import example:** `circuit: ext/quantum/circuit/index.mq.md` then `circuit.circuit` / method chain. - -**Hard rules:** `ext/**` never calls `host_*`; hot path is ABI plugin; ≤12 qubits for statevector; density-matrix ops ≤6 qubits; one language file per program; quote draw string args (`kind="…"`, `theme="…"`). - -**Core:** domain skills above (`# circuit` / `# gate` / `# density` on module files) — table `steps=` or method chain; `simulate` / `probabilities` / `run` / `draw`. - -**Q7 linear algebra:** `density`, `partial_trace`, `eig`, `expect` (Pauli string, left=high bit), `purity`, `kron`, `schmidt`, `fidelity`. - -**Draw kinds:** `circuit|probs|bloch|hinton|city|density|paulivec|qsphere|multibloch`. - -**Q8 themes (circuit / probs / bloch):** `theme="dark"|"light"|"bw"` (ZH `主题=`; **default `dark`** — slate lab look, gate-family colors, label chips so wires never cross `q0` text). View plot chrome follows `data-theme` on the SVG. Advanced kinds (hinton/…) still Q8c pending full re-skin. - -```markdown -**_ = > `qc`.draw kind="circuit" theme="dark"** -**_ = > `qc`.draw kind="probs" theme="light"** -``` - -Design: [ext-quantum.md](../../doc/design/ext-quantum.md) · Q7: [ext-quantum-q7.md](../../doc/design/ext-quantum-q7.md) · Q8 viz: [ext-quantum-viz-style.md](../../doc/design/ext-quantum-viz-style.md) · examples: [quantum-bell](../../examples/quantum-bell/) · [quantum-entanglement](../../examples/quantum-entanglement/). - -## Foreign kernels (v1.5.0) - -`lib/foreign` is now a full foreign-kernel surface, not only `run`: - -- `invoke` returns a record (`ok`, `code`, `stdout`, `stderr`, `ms`, `timed_out`, `truncated`, `result`); pass `input` for JSON stdin and `output="json"` for a parsed result. -- `call` is JSON-in / JSON-out; `call_many` fans out one program over a list with ordered results. -- `session_open` starts a persistent Python/Node kernel; `session_eval` evaluates source; `session_set` / `session_get` bridge values explicitly as JSON. Close it with `session_close`. -- A view document opts into kernel state with `会话 = > foreign.session kernels=... cells=...`; the table names are free. `view` consumes only the `会话` handle and never scans source lines or reserved table names. Without `会话`, cells are stateless one-shot runs; no kernel is created. Clearing outputs calls `/api/session/clear` and keeps persistent kernel state. There is no separate notebook CLI mode or command, and no new Markdown marker exists. -- The same source remains the authority; state crossing kernels is explicit, never implicitly mirrored. - -## AI authoring workflow - -1. Decide language surface (English builtins + `lib/text.mq.md`, or Chinese + `lib/文本.mq.md`). -2. Write `.mq.md` with `# main`, blank lines around prose, correct markers. -3. Run: `marqdo run path/to/file.mq.md` (cwd = project root so `lib/` resolves). -4. On `path:line:col: message`, fix that span; re-run until exit 0. -5. Optional: `marqdo view .` / `marqdo debug .` for structure and breakpoints. - -## Anti-patterns (common model mistakes) - -| Wrong | Right | -|-------|-------| -| `**Hello**` to print | `> print text=Hello` | -| `# main` then prose then code with no blank line | Blank line before code | -| `if x > 0:` | `1. `x` > 0` | -| `* > print text=hi *` | `> print text=hi` | -| `` *`a` = 1 * `` (trailing space + backticks) | `**a = 1**` — bare bind, no trailing space before `*` / `**` | -| `*xs = > text.split value=a,b sep=,*` (italic is return, and bare text args) | `**xs = > text.split value="a,b" sep=","**` — statement; quote text literals | -| Forgetting empty return after nested `##` helper when outer continues | Add `*None*` / `**` / `****` (not `---`) | -| 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` / `compose_*` page parts | `type: web` Document + View table / `web.render` / `web.serve` | -| 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 | -| Bare `kind=hinton` inside `*…*` | `kind="hinton"` — quote text literals | -| Bare `theme=dark` inside `*…*` | `theme="dark"` — quote; ZH `主题="dark"` | -| Rebuild plugin but skip `ext add` | `cargo build -p marqdo_plugin_quantum` then `marqdo ext add quantum` (or set `MARQDO_QUANTUM_PLUGIN`) | - -## Checklist before finishing - -- [ ] File ends with `.mq.md` -- [ ] Print via `print` / `打印`, not bold -- [ ] Blank lines separate comment paragraphs from code -- [ ] `# main` exists when the file is an entry program -- [ ] Nested side-effect helpers ended with `*None*` / `**` / `****` when the outer function continues -- [ ] 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) +| `- [intent](for items as item)` | Explicit traversal | +| `1.` / `2.` | Branches; numbered * is else | +| GFM table | Data: one column list, one row record, @ row records | + +Read [the executable programming guide](../../../doc/library-development.mq.md) +before authoring. Its actual callable examples demonstrate inline computation, +structured results, defaults and recoverable native file reads. Use +[the development entry](../../../skills/marqdo-dev/index.mq.md) and its file tools for source +work, and [the release entry](../../../skills/marqdo-release/index.mq.md) for an authorized +release. These mq.md files are the working instructions and tools; do not rebuild +a parallel command playbook in SKILL.md. + +Call the actual file and heading with `marqdo call`. In a source checkout use +the built `target/debug/marqdo`; prepare its engineering plugin through the +development entry. Large structured inputs use --args-json FILE or stdin; +JSON strings stay literal during call-session replay. --require-ok makes failed +Results stop external automation while preserving their returned evidence. +Read each function's parameter/return tables and effect contract before calling. + +Author programs as readable explanations: useful narrative exceeds half of +each callable unit; parameter and return tables immediately follow its heading; +inline assignments, actions and returns explain their purpose. Standard libraries +remain single-file handbooks. Multi-file projects and extensions use index.mq.md. +GFM describes data, public helpers describe operations, and components recursively +split web layouts until their content leaves are ordinary Markdown. + +Native Marqdo capabilities handle file reading/writing, tables, parsing, hashing +and network reads. Add an extension for a reusable capability gap or call an +explicit existing external tool with argument arrays. Keep decisions, retries +and the execution flow in mq.md. Do not generate Python or shell programs for +already available native operations. OS processes and plugins retain their OS +authority; an fs-root does not sandbox their own access. + +Use the current [web entry](../../../ext/web/index.mq.md) for Document, Endpoint and +Resource artifacts, or [quantum entry](../../../ext/quantum/index.mq.md) for circuit +workflows. Do not restore removed compose_* or app.configure APIs. Preserve +intentional fixtures and [classic migration context](migration-classic.md). +Validate the real calls and error paths; a narrative ratio or uploaded asset +alone is never functional evidence. diff --git a/.cursor/skills/marqdo/examples.md b/.cursor/skills/marqdo/examples.md index 0048837..db46baa 100644 --- a/.cursor/skills/marqdo/examples.md +++ b/.cursor/skills/marqdo/examples.md @@ -1,328 +1,3 @@ -# Marqdo examples (AI) +# Marqdo executable examples -## 1. Hello (English) - -```markdown -# main - -> print text=Hello World! -``` - -## 2. Hello (Chinese builtins) - -```markdown -# main - -> 打印 内容=你好,世界! -``` - -## 3. Function + named call + body end - -```markdown -# main - -Greeting via a nested function: - -> greet who=Marqdo - -## greet - + `who` - -> print text=Hello, `who`! - ---- -``` - -## 4. Bindings and return - -```markdown -# main - -*a = 2* -*b = > add_one n=`a`* -> print text=`b` - -## add_one - + `n` - -**n + 1** -``` - -## 5. Branch with else - -```markdown -# main - -*n = 0* - -1. `n` > 0 - > print text=positive -2. `n` < 0 - > print text=negative -3. * - > print text=zero -``` - -## 6. Foreach loop - -```markdown -# main - -`篮子` = - -| 果 | -|----| -| 苹果 | - -- [果](篮子) - > print text=`果` -``` - - -## 6b. Map table + footnote get - -```markdown -# main - -`分类` = - -| 苹果 | 黄瓜 | -|------|------| -| 水果 | 蔬菜 | - -*种 = 分类[^苹果]* -> print text=`种` - -*第一 = 篮子[^1]* -``` - -One column → list; ≥2 columns + one data row → map; ≥2 columns + many rows → map of lists. Data cells are expressions (same as call-arg values): bare words, numbers, `` `var` ``, quoted strings; URLs and `gpt-4o-mini` stay text via path/hyphen folding. Footnotes: lists use 1-based digit indices; maps use key text (including digit keys like `[^00]`). Foreach on a map walks **keys**. - -Row-oriented records (SQL-like): first header `@` / `行` / `row` → list of maps (marker column excluded): - -```markdown -`订单` = - -| 行 | 品名 | 数量 | -|----|------|------| -| 1 | 苹果 | 2 | - -*名 = 订单[^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 ---- -title: split demo -import: - text: lib/text.mq.md ---- - -# main - -*parts = > split value=a,b,c sep=,* -> print text=`parts` -``` - -## 8. Comment paragraphs (blank-line rule) - -```markdown -# main - -This whole paragraph is a comment, including lines that look like code: -*not_executed = 1* -> print text=also still comment - -After a blank line, code runs: - -> print text=this runs -``` - -## 9. Frontmatter import only - -```markdown ---- -description: loads math -import: - math: lib/math.mq.md ---- - -# main - -*t = > num value=3.5* -> print text=`t` -``` - -## 10. Object handle + method - -See `tests/structure/object-handle.mq.md` and `ext/llm.mq.md`: `# Type` constructs a map with `_type`; methods use `` > `obj`.method `` and read `self` / `自`. - -## 10b. Object inheritance - -```markdown -# Greeter - -## hello - + `who` - -*msg = "Hello, `who`!"* -**msg** - -# Loud = > Greeter - -## hello - + `who` - -*msg = "HELLO, `who`!"* -**msg** -``` - -`_type` stays the most specific name (`Loud`). Methods walk the base chain; same-name `##` on the child overrides. **No implicit super** — if the child needs parent fields, call the parent explicitly: - -```markdown -# Child = > Parent - + `name` - -*self = > Parent name=`name`* -*self = > json.set map=`self` key=extra value=1* -**self** -``` - -## 11. Agent layout (ABI) - -```markdown ---- -import: - agent: ext/agent.mq.md ---- - -# main - -> load_native - -*ws = > agent* -*n = > `ws`.ensure_layout* -> print text=`n` -``` - -Requires `MARQDO_AGENT_PLUGIN` pointing at the built `agent` shared library (see `doc/design/ext-agent.md`). - -## 12. What not to emit - -```markdown -# BAD — bold is return, not print -**Hello** - -# BAD — Python control keywords -if x > 0: - print(x) - -# BAD — wrapping a call in italics -*> print text=hi* - -# BAD — old branch syntax (removed) -+ `x` > 0 - -# GOOD — ordered list arms -1. `x` > 0 - > print text=pos -2. * - > print text=other - -# GOOD — another independent branch (restart at 1.) -1. `y` > 0 - > print text=y-pos -2. * - > print text=y-other -``` - -## 13. Dynamic site (Web Artifact, minimal) - -`index.mq.md`: - -```markdown ---- -type: web -title: Hello -route: / -method: GET ---- - -# Hello - -Executable document as a page. -``` - -`serve.mq.md`: - -```markdown ---- -import: - web: ext/web/web.mq.md ---- - -# main - -> web.serve root="." host="127.0.0.1" port=8080 -``` - -- Import `ext/web/web.mq.md` **or** `ext/web/网页.mq.md` — not both. -- Full Artifact blog: `examples/marqdo-blog/` (`pages/` · `api/` · `db/` · `data_source`). -- Design: `doc/design/ext-web-artifact.md` · ADR 0007. No `compose_*` / `configure`. - -## 14. Quantum entanglement lab (ext/quantum Q7/Q8) - -```markdown ---- -import: - quantum: ext/quantum/circuit/index.mq.md ---- - -# main - -`steps` = - -| step | gate | qubits | -|------|------|--------| -| 1 | H | 0 | -| 2 | CX | 0,1 | - -*qc = > quantum.circuit qubits=2 steps=`steps`* -*rho = > `qc`.density* -*red = > `rho`.partial_trace keep=0* -*sch = > `qc`.schmidt cut=1* -*_ = > `qc`.draw kind="circuit" theme="dark"* -*_ = > `qc`.draw kind="hinton"* -> print text=`red` -``` - -- Full lab: `examples/quantum-entanglement/`. Bell-only: `examples/quantum-bell/`. -- `theme="dark"|"light"|"bw"` (default dark) on `circuit` / `probs` / `bloch`. Quote `kind=` / `theme=`. -- After rebuilding the plugin: `marqdo ext add quantum` so view loads the new native lib. +Read [the maintained discovery note](../../../skills/marqdo/examples.md) and its actual mq.md source entries. The [programming guide](../../../doc/library-development.mq.md) is authoritative; source examples and real workflow tests stay together rather than being copied into SKILL reference fences. diff --git a/.cursor/skills/marqdo/migration-classic.md b/.cursor/skills/marqdo/migration-classic.md new file mode 100644 index 0000000..4be585c --- /dev/null +++ b/.cursor/skills/marqdo/migration-classic.md @@ -0,0 +1,3 @@ +# Classic migration + +Read [the maintained migration context](../../../skills/marqdo/migration-classic.md) and [the executable programming guide](../../../doc/library-development.mq.md). Historical fixtures retain explicit classic markup; new code uses readable occlusion and access(collection, key). diff --git a/.cursor/skills/marqdo/reference.md b/.cursor/skills/marqdo/reference.md index 6481ab8..d060290 100644 --- a/.cursor/skills/marqdo/reference.md +++ b/.cursor/skills/marqdo/reference.md @@ -1,191 +1,3 @@ -# Marqdo reference (AI) +# Marqdo executable reference -Load this when you need stdlib names, CLI, or edge cases. Core rules stay in [SKILL.md](SKILL.md). - -## CLI - -```text -marqdo --version -marqdo run FILE.mq.md -marqdo run FILE.mq.md --backend bytecode -marqdo view PATH # docs browser, default port 7429 -marqdo debug PATH # debugger UI, default port 7430 -marqdo catalog PATH -o .marqdo -marqdo ext list -marqdo ext add llm|agent|web|quantum -marqdo ext remove llm|agent|web|quantum -``` - -Diagnostics look like `path:line:col: message` (1-based line/col). - -**v0.2 surface:** parameters `` + `name` ``; branches `` 1. `cond` `` / `` 2. * `` (same-indent restart at `1.` = **new** branch statement); loops `` - [item](coll) `` or `` - [`item`](`coll`) ``; identifiers in backticks (foreach header may omit ticks). See `doc/design/markdown-mapping.md`. - -Stdlib search order for `lib/…` imports: `MARQDO_LIB`, `./lib`, directory of the `marqdo` executable (and a few parents). Prefer the **bundle zip** (`marqdo.exe` + `lib/`) over a bare exe. - -官方扩展(`ext/…`,非 stdlib):`marqdo ext add` 装到 `MARQDO_EXT` 或 `~/.marqdo/ext`;导入仍写 `import llm:ext/llm.mq.md`。解析还含 cwd `ext/`、二进制旁 `ext/`。对象:`doc/design/objects.md`。Agent:`doc/design/ext-agent.md` · 安装器:`doc/design/ext-cli.md`。 - -## Builtins (no import) - -| EN | ZH | Role | -|----|----|------| -| `print` | `打印` | stdout; arg `text` / `内容` | -| `input` | `输入` | one line; arg `prompt` / `提示` | -| `len` | `长度` | length; arg `value` / `值` | -| `str` | `文本` | to text; arg `value` / `值` | -| `int` | `整数` | to int; arg `value` / `值` | - -Keywords (not variable names): `True`/`真`, `False`/`假`, `None`/`空`, `and`/`且`, `or`/`或`, `not`/`非`. - -## Standard library files - -Import one file; use **that** file’s function names. - -| EN import | ZH import | Typical APIs (EN / ZH) | -|-----------|-----------|-------------------------| -| `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) | **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` | 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/index.mq.md` · `web.mq.md` | `ext/web/网页/索引.mq.md` · `网页.mq.md` | dynamic sites — see **ext/web** section below | -| `ext/quantum/index.mq.md` + modules | `ext/quantum/量子/索引.mq.md` + modules | circuits + Q7 density/viz + Q8 themes — see **ext/quantum** below | - -Open the imported `.mq.md` under `lib/` or `ext/` to see exact `##` / `#` names and parameters. Gold tests: `tests/lib/`, `tests/structure/`, `tests/ext/`. - -## ext/web (Artifact sites · ADR 0007) - -Install: `marqdo ext add web` (`网页`). Native: `bash scripts/build-web-plugin.sh`. - -Layout practice: split home into nav/main/footer; split footer into brand/links, -then links into docs/community until content leaves are ordinary Markdown. -Use `component.markdown|wrap`, `layout.stack|columns`, and @ record lists. -A parent value holds child rows of the same five-column View schema. -Explicit `view: main` Documents assemble once at startup; `inspect root=...` -scans disk declarations. See the Web root handbook and reference layout site. - - -| EN import | ZH import | Surface | -|-----------|-----------|---------| -| `ext/web/web.mq.md` | `ext/web/网页.mq.md` | facade: `page` · `route` · `serve` · `render` · `inspect` · `use` | - -| Kind | Metadata | Notes | -|------|----------|-------| -| Document | `type: web` / `类型: 网页` | `route` · `data_source` · `data_order` · `data_where` | -| Endpoint | `type: endpoint` / `类型: 端点` | `path` · `method` · `# main` handler · `request`/`response` | -| View | `|type|slot|value|attrs|style|` | `web.render nodes=` | -| Resource | `ext/data` · `ext/security` · `ext/net` | db/cache/storage · auth/rbac/oidc · websocket | - -Do **not** use `compose_*` / `app.configure` / author `ensure_plugin`. - -Example: `examples/marqdo-blog/`. Design: `doc/design/ext-web-artifact.md`. Historical matrix: `doc/design/web-net-capabilities.md`. - -## ext/quantum (circuits + Q7/Q8) - -Install: `marqdo ext add quantum` (`量子`). Native: `cargo build --release -p marqdo_plugin_quantum`, then re-run `ext add` so view picks up the new `.so`. - -| EN import | ZH import | Core types | -|-----------|-----------|------------| -| `ext/quantum/circuit/index.mq.md` (etc.) | `ext/quantum/量子/电路/索引.mq.md` (etc.) | `# circuit` / `# 电路` · `# gate` / `# 门` · `# density` / `# 密度` + call tools | - -| Area | EN APIs | Notes | -|------|---------|-------| -| Circuit | `h`/`cx`/…, `simulate`, `probabilities`, `run`, `draw`, `noise` | `steps=` GFM table; ≤12 qubits | -| Gate | `matrix`, `matches_matrix`, `draw` | named or `matrix=` custom unitary | -| Density (Q7) | `purity`, `partial_trace`, `eig`, `expect`, `draw` | ≤6 qubits for dense ρ | -| Free (Q7) | `kron`, `schmidt`, `fidelity` | top-level on import bind | -| Draw kinds | `circuit\|probs\|bloch\|hinton\|city\|density\|paulivec\|qsphere\|multibloch` | quote `kind="…"` | -| Themes (Q8) | `theme="dark"\|"light"\|"bw"` (ZH `主题=`) | default **dark**; circuit/probs/bloch themed; SVG `data-theme` | - -Examples: `examples/quantum-bell/`, `examples/quantum-entanglement/`. Design: `doc/design/ext-quantum.md` · Q7: `doc/design/ext-quantum-q7.md` · Q8: `doc/design/ext-quantum-viz-style.md`. - -## Formula + plot (math) - -```markdown ---- -import: - math: lib/math.mq.md ---- - -# main - -`f` = -$$ -x^2 - 2 -$$ - -*_svg = > plot formula=`f` var=x min=-3 max=3* -``` - -Empty RHS assignment + following `$$…$$` binds a formula value. Narrative-only `$$` without binding is display, not assignment. - -## Foreign (Python example) - -```markdown ---- -import: - foreign: lib/foreign.mq.md ---- - -# main - -`hi` = -```python -print("hello-from-python") -``` -``` - -Lines starting with `` ` `` can be code (binding). Keep a blank line before/after fences per comment rules. - -## Function-end details - -| Form | Effect | -|------|--------| -| Lone `---` or `***` (≥3 same chars) at function body top level | End function; no return value | -| `****` or empty bold | Return `None` and end body | -| `**expr**` | Return `expr`; does **not** by itself cut off later sibling statements — still use HR or shallower heading | - -File-leading paired `---` is frontmatter only; body `---` is not frontmatter. - -## Call arguments - -- Named: `> greet who=World` -- Positional: `> greet World` -- Spaces in values: allowed in named forms as in docs (`who=marqdo user`) -- Inline call in statement: `` *`n` = > len value=`s`* `` - -See `doc/design/call-arguments.md`. - -## Identifiers - -- Variables: `` `name` `` -- Comparisons: `==` `>` `<` `>=` `<=` -- Do not use keyword tokens as names - -## Design docs (repo) - -| Doc | Topic | -|-----|--------| -| `doc/design/markdown-mapping.md` | Syntax constitution | -| `doc/design/objects.md` | `#` objects / `##` methods | -| `doc/design/keywords.md` | Builtins / keywords | -| `doc/design/return-hr-and-code-surface.md` | Function end / surfaces | -| `doc/design/stdlib-i18n.md` | EN/ZH lib files | -| `doc/design/stdlib-modules.md` | L1 modules including plugin | -| `doc/design/ext-abi.md` | Native C ABI v1 | -| `doc/design/ext-llm.md` | `ext/llm` | -| `doc/design/ext-agent.md` | `ext/agent` agent **framework** (layout shipped; LLM orchestration roadmap) | -| `doc/design/ext-cli.md` | `marqdo ext list/add/remove` | -| `doc/design/ext-web.md` | `ext/web` dynamic sites (author API) | -| `doc/design/web-net-capabilities.md` | ext/web capability matrix (W0–W7 + P3) | -| `doc/design/ext-quantum.md` | `ext/quantum` circuits | -| `doc/design/ext-quantum-q7.md` | Q7 density linear algebra + advanced SVG | -| `doc/design/ext-quantum-viz-style.md` | Q8 themed SVG (`dark`/`light`/`bw`; circuit/probs/bloch) | -| `doc/design/view-debug.md` | view / debug hosts | +Read [the maintained discovery note](../../../skills/marqdo/reference.md) and its actual mq.md source entries. The [programming guide](../../../doc/library-development.mq.md) is authoritative; source examples and real workflow tests stay together rather than being copied into SKILL reference fences. diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..04ad559 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +# Multipart protocol examples retain required CRLF bytes in every checkout. +examples/web-net-site/components/content/multipart.txt -text whitespace=cr-at-eol +examples/web-net-site-zh/components/content/multipart.txt -text whitespace=cr-at-eol diff --git a/.github/workflows/extension-release.yml b/.github/workflows/extension-release.yml new file mode 100644 index 0000000..21cb812 --- /dev/null +++ b/.github/workflows/extension-release.yml @@ -0,0 +1,64 @@ +# Independent extension sources and native libraries; no CLI/PPA publication. +name: Extension Release + +on: + push: + tags: + - "ext-v*" + +permissions: + contents: write + +jobs: + windows: + runs-on: windows-latest + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: dtolnay/rust-toolchain@stable + - uses: actions/setup-go@v5 + with: + go-version: "1.23.x" + - name: Install cgo toolchain + run: choco install mingw -y + - name: Build the handbook CLI and native capabilities + shell: bash + run: | + set -euo pipefail + export PATH="/c/ProgramData/mingw64/mingw64/bin:/c/ProgramData/chocolatey/lib/mingw/tools/install/mingw64/bin:$PATH" + cargo build --release -p marqdo -p marqdo_plugin_agent -p marqdo_plugin_quantum -p marqdo_plugin_linalg -p marqdo_plugin_llm -p marqdo_plugin_engineering + bash scripts/build-web-plugin.sh + - name: Build and validate the runner's exact pack bytes + shell: pwsh + run: ./target/release/marqdo.exe call skills/marqdo-release/packs.mq.md ci --effects plugin,fs.write,environment.read --fs-root . --require-ok --json + - name: Attach source and Windows native packs without replacement + shell: pwsh + run: ./target/release/marqdo.exe call skills/marqdo-release/packs.mq.md attach_ci --effects plugin,fs.read,environment.read --fs-root . --require-ok --json + + linux: + runs-on: ubuntu-latest + needs: windows + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: dtolnay/rust-toolchain@stable + - uses: actions/setup-go@v5 + with: + go-version: "1.23.x" + - name: Install ZIP and cgo tools + run: sudo apt-get update && sudo apt-get install -y zip gcc libc6-dev + - name: Build the handbook CLI and native capabilities + run: | + set -euo pipefail + cargo build --release -p marqdo -p marqdo_plugin_agent -p marqdo_plugin_quantum -p marqdo_plugin_linalg -p marqdo_plugin_llm -p marqdo_plugin_engineering + bash scripts/build-web-plugin.sh + - name: Build and validate the runner's exact pack bytes + run: target/release/marqdo call skills/marqdo-release/packs.mq.md ci --effects plugin,fs.write,environment.read --fs-root . --require-ok --json + - name: Attach Linux native pack without replacement + run: target/release/marqdo call skills/marqdo-release/packs.mq.md attach_ci --effects plugin,fs.read,environment.read --fs-root . --require-ok --json diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index fbb3de6..236b436 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -38,7 +38,7 @@ jobs: run: | export PATH="/c/ProgramData/mingw64/mingw64/bin:/c/ProgramData/chocolatey/lib/mingw/tools/install/mingw64/bin:$PATH" cargo build --release - cargo build --release -p marqdo_plugin_agent -p marqdo_plugin_quantum -p marqdo_plugin_linalg -p marqdo_plugin_llm + cargo build --release -p marqdo_plugin_agent -p marqdo_plugin_quantum -p marqdo_plugin_linalg -p marqdo_plugin_llm -p marqdo_plugin_engineering bash ./scripts/build-web-plugin.sh - name: Checkout extension sources (branch vscode-extension only) @@ -88,6 +88,7 @@ jobs: Copy-Item target/release/quantum.dll "$stageNative/native/quantum.dll" Copy-Item target/release/linalg.dll "$stageNative/native/linalg.dll" Copy-Item target/release/llm.dll "$stageNative/native/llm.dll" + Copy-Item target/release/engineering.dll "$stageNative/native/engineering.dll" if (Test-Path "dist/$nativeZip") { Remove-Item "dist/$nativeZip" -Force } Compress-Archive -Path "$stageNative/*" -DestinationPath "dist/$nativeZip" -Force $stage = "dist/stage-bundle" @@ -102,6 +103,7 @@ jobs: Copy-Item target/release/quantum.dll "$stage/ext/native/quantum.dll" Copy-Item target/release/linalg.dll "$stage/ext/native/linalg.dll" Copy-Item target/release/llm.dll "$stage/ext/native/llm.dll" + Copy-Item target/release/engineering.dll "$stage/ext/native/engineering.dll" if (Test-Path "dist/$zip") { Remove-Item "dist/$zip" -Force } Compress-Archive -Path "$stage/*" -DestinationPath "dist/$zip" -Force $stageLib = "dist/stage-stdlib" @@ -122,34 +124,7 @@ jobs: - name: Upload release assets uses: softprops/action-gh-release@v2 with: - body: | - ## Marqdo ${{ github.ref_name }} - - ### 亮点 / Highlights - - **2.6.0**:标准库与拓展库成为可执行手册;650 个公开标准库函数,标题下契约、叙述形参与句中调用。 - - **2.6.0**: Executable library handbooks, 650 public standard-library functions, inline actions and source contracts. - - 文件/字节/集合/Result/文档/HTTP/任务/TOML/时区工程能力;Quantum 实验与 Web 递归 Markdown 布局。 - - File, binary, collection, document and task workflows; executable Quantum experiments and recursive Web layouts. - - View 正文读动作,左右侧注看逻辑;空逻辑明确提示;知识区按输入、返回和依据组织。 - - View keeps action text in prose, implementation in margin notes, and readable knowledge facts separate from execution. - - CLI · wasm · ext · VS Code extension: **2.6.0**. Core surface unchanged: **19 constructs**. - - Linux CLI and native plugin zips are required; see CHANGELOG for exact platform/effect boundaries. - - ### Downloads - - | Asset | Contents | - |-------|----------| - | `marqdo-*-windows-msvc.exe` | CLI with **embedded** official stdlib | - | `marqdo-*-windows-msvc.zip` | `marqdo.exe` + `lib/` + `ext/`(含 native DLL) | - | `marqdo-*-native-*.zip` | 预编译 `web`/`agent`/`quantum`/`linalg`/`llm`(Windows DLL + **Linux .so 必出**) | - | `marqdo-*-unknown-linux-gnu.zip` | Linux CLI + `lib/` + `ext/` + native `.so` | - | `marqdo-*-stdlib.zip` | `lib/` only | - | `marqdo-*-ext.zip` | Official `ext/` L1 sources | - | `marqdo-*-source.zip` | Source snapshot (`git archive`) | - | `marqdo-*.vsix` | VS Code / Cursor extension | - | `marqdo-*-public.zip` | Static user docs site | - - Extension workflow: [vscode-extension-commit.md](https://github.com/cflmy/marqdo/blob/main/doc/design/vscode-extension-commit.md) + body_path: doc/releases/${{ github.ref_name }}.md files: | dist/${{ env.EXE }} dist/${{ env.ZIP }} @@ -186,7 +161,7 @@ jobs: run: | set -euo pipefail cargo build --release - cargo build --release -p marqdo_plugin_agent -p marqdo_plugin_quantum -p marqdo_plugin_linalg -p marqdo_plugin_llm + cargo build --release -p marqdo_plugin_agent -p marqdo_plugin_quantum -p marqdo_plugin_linalg -p marqdo_plugin_llm -p marqdo_plugin_engineering bash ./scripts/build-web-plugin.sh - name: Package Linux native zip + CLI bundle @@ -195,7 +170,7 @@ jobs: VER="${GITHUB_REF_NAME#v}" TARGET="x86_64-unknown-linux-gnu" mkdir -p dist/stage-native/native - for lib in libweb.so libagent.so libquantum.so liblinalg.so libllm.so; do + for lib in libweb.so libagent.so libquantum.so liblinalg.so libllm.so libengineering.so; do src="target/release/${lib}" if [[ ! -f "$src" && "$lib" == libweb.so ]]; then src="plugins/web/build/libweb.so" diff --git a/.gitignore b/.gitignore index 242b966..919c8d5 100644 --- a/.gitignore +++ b/.gitignore @@ -42,11 +42,7 @@ spike/.pytest_cache/ *.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/ @@ -61,7 +57,6 @@ plugins/*/tmp/ /examples/web-net-site/data/ /examples/web-net-site-zh/data/ /examples/marqdo-blog/data/ -/examples/anlian-mq/data/ # Quantum draw/SVG runtime outputs (sources & gold .mq.md stay tracked) /tests/ext/quantum-*.svg @@ -109,3 +104,22 @@ tests/ext/_sbx_cow/ tests/ext/_sbx_*/ examples/**/_example_sbx/ .secrets/ + +# Generated runtime resources for callable browser handbook examples +/examples/web-spa-app/static/marqdo_wasm.wasm +/examples/web-spa-app/static/marqdo-bridge.js +/examples/web-collab-doc/static/marqdo_wasm.wasm +/examples/web-collab-doc/static/marqdo-bridge.js + +# Native browser runtime and compiled theme produced by the network-site handbook. +/examples/web-net-site/public/generated/ +/examples/web-net-site-zh/public/generated/ + +# Generated literary-site theme resources (the declarative sources stay tracked). +/examples/web-site/public/generated/ +/examples/web-site-zh/public/generated/ + +# Native browser-effects example generated resources. +/examples/browser-app/static/marqdo_wasm.wasm +/examples/browser-app/static/marqdo-bridge.js +/examples/browser-app/static/theme.css diff --git a/CHANGELOG.md b/CHANGELOG.md index b5b2c27..7615799 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,12 +2,35 @@ ## Unreleased +## v2.7.0 — 2026-11-10 + +### Highlights / 亮点 + +源码手册进入真实开发与用户站点:原生文件操作、可调用开发/发版流程、递归 View 站点及当前请求资源。CLI、WASM、拓展包与编辑器版本统一为 2.7.0。详见 [完整双语发布说明](doc/releases/v2.7.0.md)。 + +Executable source handbooks now drive actual development and user sites: native file operations, callable release tasks, recursive View Documents and current request resources. CLI, WASM, extension packs and editor version are 2.7.0. + +**核心表面 Δ / Core surface Δ**:无增删,仍为 19 个核心构造;沿用既有 Markdown 标记与插件 ABI。 + ### Added +- Native development and release handbooks, bounded engineering plugin boundaries, literal CLI JSON file/stdin arguments and --require-ok failure propagation. +- 原生文档表读取与保留正文的修改;纯 head 资源,以及当前请求的数据查询、表单与会话导航资源。 +- Both-language recursive user sites, source-aware route inspection, retained theme declarations and actual browser acceptance. +- Structured nested list/control records in the official bridge, documented in EN/ZH browser libraries and the callable browser-app. + ### Fixed +- Occlusion receivers, nested and hyphenated-path calls, prose literal defaults and exact CLI argument/session replay semantics. +- 授权站点根下的文件/SQLite 定位;嵌套 Document 与 Endpoint 回调上下文;表单重试 CSRF、成功跳转、管理入口与片段选择。 +- Browser duplicate-item deletion, literal content rendering, Back/Forward history and asynchronous outcome reporting. + ### Changed +- SKILL discovery delegates to executable handbooks; ordinary file IO and orchestration use Marqdo instead of Python release scripts. +- 中英文用户站点保留原始主题、当前文章与管理能力;移除无关的暗恋工程和过时独立浏览器演示,保留底层测试夹具。 +- Native packs include the engineering plugin. Main excludes editor sources; immutable tags, both-platform builds and independent GitHub/CDN/Ubuntu verification remain release obligations. + ## v2.6.0 — 2026-11-08 ### Highlights / 亮点 @@ -1161,6 +1184,8 @@ marqdo run tests/markup-v03/inc-prose.mq.md ### Highlights +历史说明(2026-11-10):本节的 anlian-mq 是当时发布内容记录,现已移出仓库,旧启动命令不适用于当前工作树。当前完整站点见 examples/web-site 与 examples/web-site-zh。 + **Go `libweb` 默认落地(W-G0–W-G14)**:官方网页原生插件改为 Go C ABI;CLI / gold / Release 走 `scripts/build-web-plugin.sh`;Rust 源码归档。另附 **anlian-mq** 验收站与表单插槽 / `MARQDO_EXT` 提示修复。 ```bash diff --git a/Cargo.lock b/Cargo.lock index c1e5446..73d6b66 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -615,7 +615,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" [[package]] name = "marqdo" -version = "2.6.0" +version = "2.7.0" dependencies = [ "anyhow", "assert_cmd", @@ -656,7 +656,7 @@ dependencies = [ [[package]] name = "marqdo-wasm" -version = "2.6.0" +version = "2.7.0" dependencies = [ "marqdo", "serde_json", @@ -679,6 +679,23 @@ dependencies = [ "serde_json", ] +[[package]] +name = "marqdo_plugin_engineering" +version = "0.1.0" +dependencies = [ + "base64", + "chrono", + "flate2", + "hmac", + "libc", + "marqdo", + "marqdo-plugin-sdk", + "serde_json", + "sha2", + "ureq", + "zip", +] + [[package]] name = "marqdo_plugin_linalg" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 833724e..be4169d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "marqdo" -version = "2.6.0" +version = "2.7.0" edition = "2021" license = "Apache-2.0" description = "Marqdo — Markdown markers as an interpreted programming language" @@ -60,6 +60,7 @@ getrandom = { version = "=0.2.17", default-features = false, features = ["custom [workspace] members = [ "plugins/demo", + "plugins/engineering", "plugins/agent", "plugins/llm", "plugins/quantum", diff --git a/README.md b/README.md index f0896f0..07e8022 100644 --- a/README.md +++ b/README.md @@ -288,11 +288,12 @@ marqdo catalog public -o .marqdo --- -## 现状(v2.6.0) +## 现状(v2.7.0) +- **实际工程与可执行 SKILL(v2.7.0)**:中英文用户站点使用递归 View、普通 Markdown、当前数据/表单/会话资源并保留原始主题。开发与发版手册通过 `marqdo call` 执行,固有文件能力负责读写,工程插件承接进程、认证与格式边界。旧独立浏览器演示已收敛到实际可运行的工程;详见 [2.7.0 发布说明](doc/releases/v2.7.0.md)。 - **标准库与拓展库手册(v2.6.0)**:61 份公开标准库、650 个函数;源码内参数/返回契约、叙述形参、句中遮蔽调用与真实工程。新增文件/字节/集合/Result/文档/HTTP/任务/TOML/时区工作流;多文件拓展库以 index 组织。 - **View 可读动作与知识(v2.6.0)**:正文读动作,侧注看实现,运行标注看实际结果;空逻辑明确提示待补。知识说明先看输入、返回、依赖和依据,技术身份按需展开。 -- **Quantum / Web 工程实践(v2.6.0)**:可执行实验、会话句柄与双语门面;网页先递归拆布局,直到叶子可以直接用 Markdown 表达。CLI · wasm · ext · VS Code 扩展同步 **2.6.0**。 +- **Quantum / Web 工程实践(v2.6.0)**:可执行实验、会话句柄与双语门面;网页先递归拆布局,直到叶子可以直接用 Markdown 表达。CLI · wasm · ext · VS Code 扩展同步 **2.7.0**。 - **View 连线与工具栏(v2.5.1)**:真实源码锚点、连续 S 形曲线、错落标注与连线避让;底部工具栏增加文字标签。深浅色配色保持一致。CLI · wasm · ext 同步 **2.5.1**。 @@ -333,7 +334,7 @@ marqdo catalog public -o .marqdo - **`marqdo version --check`**:与 GitHub 最新 release 对比 - 标准库:**内置于二进制**(v0.1.2+);磁盘 `lib/` 或 `MARQDO_LIB` 可覆盖。模块含文本、表、**浏览器效应**、文件、系统、时间、JSON、网络、数学、外联、插件、**自写回**、**子任务**;**中层 Mid M1–M6** + **Mid2 M7–M10**(datetime/url/toml/html/fs++/stats/log.fields 等,见 [stdlib-mid.md](doc/design/stdlib-mid.md) · [stdlib-mid2.md](doc/design/stdlib-mid2.md)) - **官方扩展库 `ext/`**(**非** stdlib,本版收口): - - **`web`**:**Artifact 模型(ADR [0007](doc/adr/0007-web-document-endpoint.md))** — `type: web|endpoint` Document/Endpoint;facade `page`/`route`/`serve`/`render`/`inspect`/`use`;Resource 在 `ext/data` · `ext/security` · `ext/net`;设计 [ext-web-artifact.md](doc/design/ext-web-artifact.md);原生 **Go `libweb`**([ADR 0004](doc/adr/0004-web-plugin-go.md));示例 [marqdo-blog](examples/marqdo-blog/) · [web-client-site](examples/web-client-site/) · [anlian-mq](examples/anlian-mq/) + - **`web`**:**Artifact 模型(ADR [0007](doc/adr/0007-web-document-endpoint.md))** — `type: web|endpoint` Document/Endpoint;facade `page`/`route`/`serve`/`render`/`inspect`/`use`;Resource 在 `ext/data` · `ext/security` · `ext/net`;设计 [ext-web-artifact.md](doc/design/ext-web-artifact.md);原生 **Go `libweb`**([ADR 0004](doc/adr/0004-web-plugin-go.md));示例 [marqdo-blog](examples/marqdo-blog/) · [web-client-site](examples/web-client-site/) · [完整站点](examples/web-site/) · [中文完整站点](examples/web-site-zh/) - **`quantum`**:Q0–Q7 + Q8a/b 主题 SVG;示例 [quantum-entanglement](examples/quantum-entanglement/) - **`linalg`**:L0–L6 + 公式文档面(中缀 / `declare` / 展示化简);示例 [linalg-transpose](examples/linalg-transpose/) · [linalg-svd](examples/linalg-svd/) · [linalg-least-squares](examples/linalg-least-squares/) - **`agent`**:A1–A4 + **MCP Server/Client**(stdio + **Streamable HTTP**)+ Skill Compilation + Adaptive Routing + resume + **Engineering preflight**(`agent.preflight` / `eng_preflight`);宿主缺口见 [ext-hosting.md](doc/roadmap/ext-hosting.md) · [agent-framework-gaps-after-a4.md](doc/research/agent-framework-gaps-after-a4.md) · [engineering-knowledge.md](doc/design/engineering-knowledge.md) @@ -342,10 +343,10 @@ 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,linalg,llm}`(`web` 为 Go;其余为 Rust) - **用户静态站**:`public/` → `view output` → CI 发布 [gh-pages](https://cflmy.github.io/marqdo/) - **VS Code 扩展**:分支 **`vscode-extension`**(`main` 不跟踪源码;见 [vscode-extension-commit.md](doc/design/vscode-extension-commit.md));Release 附带 `.vsix` -- **浏览器 Marqdo(WASM)**:`marqdo wasm build` + 官方 bridge 自启(作者零业务 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)) +- **浏览器 Marqdo(WASM)**:`marqdo wasm build` + 官方 bridge 自启(作者零业务 JS;桥内可含列表/路由/storage/ws/文件/Canvas/音频/Observer/拖放);`lib/browser` + GFM;`web.client_embed`;示例 [browser-app](examples/browser-app/) · [web-spa-app](examples/web-spa-app/) · [web-collab-doc](examples/web-collab-doc/)([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(v2.6.0) +### 如何使用最新 Marqdo(v2.7.0) **安装解释器(任选其一)** @@ -360,7 +361,7 @@ marqdo catalog public -o .marqdo ```bash # 1) 源码安装(跟 tag 或 main) git clone https://github.com/cflmy/marqdo.git && cd marqdo -git checkout v2.6.0 # 或留在 main +git checkout v2.7.0 # 或留在 main cargo build --release export PATH="$PWD/target/release:$PATH" marqdo version @@ -393,15 +394,15 @@ marqdo ext add llm # 或:大模型(.mq.md + 可选 native llm) # 4) 动态站示例(扩展装好后) marqdo run examples/web-site-zh/index.mq.md # 表驱动引言 Demo marqdo run examples/marqdo-blog/serve.mq.md -marqdo run examples/anlian-mq/index.mq.md # W-G14 验收站 +marqdo call examples/web-site/index.mq.md serve --effects plugin,fs.write,network.write --fs-root examples/web-site --json # 浏览器打开终端打印的 listen 地址;/favicon.ico 与 logo 装配见 W8 # 5) 浏览器 WASM(可选) marqdo wasm build -# → dist/wasm/ … 见 examples/browser-hello/ +# → dist/wasm/ … 实际工程见 examples/browser-app/ # 6) Releases:Windows exe/zip/vsix;Linux CLI zip + native `.so` zip -# https://github.com/cflmy/marqdo/releases/tag/v2.6.0 +# https://github.com/cflmy/marqdo/releases/tag/v2.7.0 ``` 开发期也可用 `cargo run -- …` 代替已安装的 `marqdo`: diff --git a/crates/marqdo-wasm/Cargo.toml b/crates/marqdo-wasm/Cargo.toml index 466fd5c..327c5d1 100644 --- a/crates/marqdo-wasm/Cargo.toml +++ b/crates/marqdo-wasm/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "marqdo-wasm" -version = "2.6.0" +version = "2.7.0" edition = "2021" license = "Apache-2.0" description = "Marqdo interpreter as WebAssembly (browser host bridge)" diff --git a/crates/marqdo-wasm/README.md b/crates/marqdo-wasm/README.md index 5a2c001..41cb1aa 100644 --- a/crates/marqdo-wasm/README.md +++ b/crates/marqdo-wasm/README.md @@ -11,7 +11,7 @@ Raw `cdylib` exports — no `wasm-bindgen` CLI required. ```bash # from repo root (C5 size profile) -marqdo wasm build -o examples/browser-hello +marqdo call skills/marqdo-dev/index.mq.md build_browser --effects plugin,process.exec,fs.write --fs-root . --json # or: cargo build -p marqdo-wasm --target wasm32-unknown-unknown --profile release-wasm ``` @@ -19,3 +19,5 @@ cargo build -p marqdo-wasm --target wasm32-unknown-unknown --profile release-was 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). + +Use the maintained [browser-app](../../examples/browser-app/index.mq.md) for a runnable native Document and browser program. The ABI counter fixture lives in tests/wasm/counter.mq.md, with no independent HTML demo host. The former browser-hello and browser-media directories were retired in 2.7.0; their host capabilities remain documented in lib/browser.mq.md. diff --git a/crates/marqdo-wasm/js/marqdo-bridge.js b/crates/marqdo-wasm/js/marqdo-bridge.js index 3a5784a..d24d1c6 100644 --- a/crates/marqdo-wasm/js/marqdo-bridge.js +++ b/crates/marqdo-wasm/js/marqdo-bridge.js @@ -228,28 +228,52 @@ function applyStyle(el, styleVal) { } export function renderListItems(spec) { - const tag = String(spec.tag || "li"); + const rootTag = String(spec.tag || "li"); const items = Array.isArray(spec.items) ? spec.items : []; - return items - .map((it) => { - if (it == null) return ""; - if (typeof it === "string" || typeof it === "number") { - return `<${tag}>${escapeHtml(String(it))}`; - } - if (!isPlainObject(it)) return ""; - const text = it.text != null ? String(it.text) : it.html != null ? null : ""; - const cls = it.class != null ? ` class="${escapeAttr(String(it.class))}"` : ""; - let attrs = ""; - if (isPlainObject(it.attrs)) { - for (const [k, v] of Object.entries(it.attrs)) { - if (v === null || v === false) continue; - attrs += ` ${escapeAttr(k)}="${escapeAttr(String(v))}"`; + let count = 0; + const render = (item, fallbackTag, depth) => { + if (depth > 32 || ++count > 10000) throw new Error("render_list: structural limit exceeded"); + if (item == null) return ""; + if (typeof item !== "string" && typeof item !== "number" && !isPlainObject(item)) return ""; + const record = isPlainObject(item) ? item : { text: String(item) }; + const tag = String(record.tag || fallbackTag); + if (!/^[a-z][a-z0-9-]*$/i.test(tag) || + /^(script|style|iframe|object|embed|link|meta|base)$/i.test(tag)) { + throw new Error("render_list: unsupported element name"); + } + let attrs = record.class != null ? ` class="${escapeAttr(String(record.class))}"` : ""; + if (isPlainObject(record.attrs)) { + for (const [key, value] of Object.entries(record.attrs)) { + if (!/^[a-z_:][a-z0-9_.:-]*$/i.test(key) || /^on/i.test(key)) { + throw new Error("render_list: invalid attribute name"); } + if (value === null || value === false) continue; + if (!["string", "number", "boolean"].includes(typeof value)) throw new Error("render_list: attributes must be scalar"); + if (/^(href|src|action|formaction)$/i.test(key) && + /^[\s\u0000-\u0020]*(javascript|vbscript|data)[\s\u0000-\u0020]*:/i.test(String(value))) { + throw new Error("render_list: unsupported URL"); + } + attrs += ` ${key}="${escapeAttr(String(value))}"`; } - const inner = it.html != null ? String(it.html) : escapeHtml(text ?? ""); - return `<${tag}${cls}${attrs}>${inner}`; - }) - .join(""); + } + let inner; + if (record.children != null) { + if (!Array.isArray(record.children) || record.text != null || record.html != null) { + throw new Error("render_list: children must be an unambiguous record list"); + } + inner = record.children.map(child => render(child, "span", depth + 1)).join(""); + } else { + // Preserve the existing explicit HTML escape hatch. Ordinary business + // values use text/children and never become source or markup. + inner = record.html != null ? String(record.html) : escapeHtml(String(record.text ?? "")); + } + if (/^(input|img|br|hr|area|col|source|wbr)$/i.test(tag)) { + if (inner) throw new Error("render_list: void elements cannot have content"); + return `<${tag}${attrs}>`; + } + return `<${tag}${attrs}>${inner}`; + }; + return items.map(item => render(item, rootTag, 0)).join(""); } function escapeHtml(s) { diff --git a/debian/changelog b/debian/changelog index 13c6093..fddb8d2 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,9 @@ +marqdo (2.7.0-1ppa1) noble; urgency=medium + + * Release 2.7.0; see the reviewed upstream CHANGELOG. + + -- Marqdo Maintainers Tue, 10 Nov 2026 16:40:29 +0800 + marqdo (2.6.0-1ppa1) noble; urgency=medium * Executable standard/extension handbooks and practical file/data/task tools. diff --git a/doc/README.md b/doc/README.md index e7a473d..9dfcacb 100644 --- a/doc/README.md +++ b/doc/README.md @@ -80,7 +80,7 @@ | [design/ext-cdn.md](design/ext-cdn.md) | **扩展 CDN(R2 / ext.marqdo.com)与分开发版** | | [design/ubuntu-ppa.md](design/ubuntu-ppa.md) | **Ubuntu PPA 打包与上传** | | [design/ext-web.md](design/ext-web.md) | **官方扩展 `ext/web`(页面/库表/绑定/后台;ABI + CLI;设计锁定)** | -| [design/ext-web-go-rewrite.md](design/ext-web-go-rewrite.md) | **`plugins/web` Go 全量重写**(多语言 ABI · 网页制备完备 · anlian 验收) | +| [design/ext-web-go-rewrite.md](design/ext-web-go-rewrite.md) | **`plugins/web` Go 全量重写**(多语言 ABI · 网页制备完备 · 独立工作流验收) | | [adr/0004-web-plugin-go.md](adr/0004-web-plugin-go.md) | **Accepted:web 原生插件实现语言为 Go** | | [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、布局…) | diff --git a/doc/adr/0004-web-plugin-go.md b/doc/adr/0004-web-plugin-go.md index cb2f8f1..7e178b4 100644 --- a/doc/adr/0004-web-plugin-go.md +++ b/doc/adr/0004-web-plugin-go.md @@ -1,5 +1,7 @@ # ADR 0004:网络拓展库原生实现改为 Go +历史说明(2026-11-10):下文业务站点仅记录当时决策背景,相关工程已移出本仓库;当前验收使用维护中的完整站点、网络站点及隔离测试,见 [当前工作流](../design/ext-web-go-rewrite.md#8-独立工作流与隔离验收)。 + | | | |---|---| | Status | **Accepted** | diff --git a/doc/design/browser-marqdo-wasm.md b/doc/design/browser-marqdo-wasm.md index 0f1c39e..2bc693b 100644 --- a/doc/design/browser-marqdo-wasm.md +++ b/doc/design/browser-marqdo-wasm.md @@ -1,5 +1,8 @@ # 浏览器 Marqdo(WASM 解释器)设计 +> 2.7.0 维护说明:独立的 browser-hello 与 browser-media 演示已删除。下文保留既有能力设计与宿主边界,当前可运行工程使用 browser-app;底层计数器冒烟夹具位于 tests/wasm/counter.mq.md。Canvas、音频等仍是 lib/browser 的宿主能力,不宣称当前 browser-app 演示包含这些交互。 + + | | | |---|---| | 状态 | **Accepted(设计锁定)** · 实现见路线图 C0–C5 | @@ -124,7 +127,7 @@ source: &str (+ optional import map) | `marqdo`(根) | 核心;feature-gate | | `crates/marqdo-wasm` | `cdylib`:`mq_*` ABI + `js/marqdo-bridge.js` | | `ext/web` 或 `web/browser` | L1:`浏览器.运行` / `交互装配`(C3+) | -| `examples/browser-hello/` | 静态页 + wasm 冒烟 | +| `examples/browser-app/` | 静态页 + wasm 冒烟 | | `tests/browser/` 或金样脚本 | Node/wasmtime 跑 `run_source` 对齐 | 发行:`marqdo wasm build`(C2 CLI 糖)或 `wasm-pack build crates/marqdo-wasm`。 @@ -210,7 +213,7 @@ L1 `浏览器.交互装配`(ext)可后置;C3 以 bridge + 返回 wire 表 Bridge:`applyEffects(exports, value)` — 先 DOM,再调度异步;**不**在 WASM 内阻塞。 -示例见 `examples/browser-hello/fetch.mq.md`。 +示例见 `examples/browser-app/static/app.mq.md`。 --- @@ -251,7 +254,7 @@ marqdo wasm build -o static # marqdo_wasm.wasm + marqdo-bridge.js # app.static dir=static ``` -业务页再 `boot` 自己的 `.mq.md`(见 `examples/browser-hello/`)。 +业务页再 `boot` 自己的 `.mq.md`(见 `examples/browser-app/`)。 --- @@ -261,7 +264,7 @@ marqdo wasm build -o static # marqdo_wasm.wasm + marqdo-bridge.js |----|------| | 单元 | `run_source("…# main\n> print…")` native 与 wasm 同测 | | 金样子集 | `tests/structure/hello.mq.md` 等无 fs/net/plugin 的样例 | -| 浏览器冒烟 | `examples/browser-hello`:按钮点击 → Marqdo 函数 → 改 DOM 文本 | +| 浏览器冒烟 | `examples/browser-app`:按钮点击 → Marqdo 函数 → 改 DOM 文本 | | 回归 | CI:`cargo test` native;另 job `wasm-pack build` / `cargo check --target wasm32-unknown-unknown --no-default-features --features wasm-core` | --- diff --git a/doc/design/ext-cdn.md b/doc/design/ext-cdn.md index 971e012..96c2019 100644 --- a/doc/design/ext-cdn.md +++ b/doc/design/ext-cdn.md @@ -1,66 +1,41 @@ -# Extension CDN (Cloudflare R2 → https://ext.marqdo.com) +# Extension CDN: native publication and byte parity -| | | +This page describes storage. The executable tasks are in [the release entry](../../skills/marqdo-release/index.mq.md), [assets.mq.md](../../skills/marqdo-release/assets.mq.md) and [asset_io.mq.md](../../skills/marqdo-release/asset_io.mq.md). Read the source contracts before calling them. Version, mode and publication authorization come from the user; inspecting an existing release grants no new remote write. + +## Versioned packs + +Extension versions come from ext/VERSION and can advance independently of the interpreter. An extension release uses its own ext-vX.Y.Z tag and three packs. A full release also includes the CLI, source, WASM and editor deliverables listed in model.mq.md. + +| Object | Meaning | |---|---| -| Status | **Accepted** — download prefer CDN; upload via `scripts/upload-ext-r2.py` | -| Date | 2026-09-17 | -| Related | [ext-cli.md](ext-cli.md) · [marqdo-release](../../.cursor/skills/marqdo-release/SKILL.md) | +| vX.Y.Z/marqdo-X.Y.Z-ext.zip | Readable extension sources | +| vX.Y.Z/marqdo-X.Y.Z-native-x86_64-pc-windows-msvc.zip | Windows plugins | +| vX.Y.Z/marqdo-X.Y.Z-native-x86_64-unknown-linux-gnu.zip | Linux plugins | +| vX.Y.Z/VERSION | Version echo for this pack set | +| latest/marqdo-X.Y.Z-*.zip | Identical current pack bytes | +| latest/VERSION | Recommended current extension version | -## Why +Public reads use https://ext.marqdo.com. [src/ext_cli.rs](../../src/ext_cli.rs) is authoritative for client override variables, version resolution and download fallback order. Ordinary installation does not need storage credentials. -CLI (语法解释器) and official **extension packs** (`ext/` L1 + native plugins) update on different cadences. Users behind unstable GitHub links should get packs from a stable object store first. +## Callable publication -## Public URL layout +After GitHub contains every required asset, download to dist/release-X.Y.Z. Validation checks names, GitHub size/SHA256, archive CRCs, versions and native capabilities. Source-declared plugins require matching libraries on both native platforms. Independently valid ZIPs cannot hide a missing DLL or shared library. -Bucket: `marqdo` · Custom domain: **https://ext.marqdo.com** +Run from the checkout root with the version already chosen by the user; use the actual full or ext mode: +```sh +marqdo call skills/marqdo-release/assets.mq.md download 'version="X.Y.Z"' 'mode="ext"' --require-ok --effects plugin,net,fs.write --fs-root . --json +marqdo call skills/marqdo-release/assets.mq.md publish 'version="X.Y.Z"' 'mode="ext"' --require-ok --effects plugin,net,fs.write --fs-root . --json +marqdo call skills/marqdo-release/index.mq.md finish 'version="X.Y.Z"' 'mode="ext"' --require-ok --effects plugin,net,fs.write --fs-root . --json +``` -| Key | Meaning | -|-----|---------| -| `v{VER}/marqdo-{VER}-ext.zip` | L1 sources | -| `v{VER}/marqdo-{VER}-native-{triple}.zip` | Prebuilt plugins | -| `v{VER}/VERSION` | Pack SemVer echo | -| `latest/VERSION` | Recommended pack SemVer (plain text) | -| `latest/marqdo-…zip` | Same assets mirrored for convenience | +Publication rechecks all three packs and their combined capability matrix before the first PUT. All three versioned ZIPs and three latest ZIPs are written before either VERSION pointer. A failed ZIP stops the sequence. Historical versions are retained. -`{VER}` is the **extension pack** version (`ext/VERSION`), which **may differ** from CLI `Cargo.toml` version. +Finish reads both public pointers and compares downloaded versioned/latest bytes with GitHub SHA256 values. HTTP 200 or one sample URL is insufficient. Edge propagation may leave verification incomplete; repeat observation rather than rebuilding unrelated archives or claiming completion from an upload response. -## Client download order (`marqdo ext add`) +## Explicit boundaries -1. `MARQDO_EXT_DOWNLOAD_BASE` (optional override) -2. **CDN** `https://ext.marqdo.com/v{VER}/…` (override host with `MARQDO_EXT_CDN`) -3. GitHub Releases -4. `https://proxy.cflmy.top/github.com/…` +Filesystem operations, hashing, public HTTP downloads, release decisions and upload order are Marqdo code. The engineering extension supplies bounded ZIP inspection and private R2 Signature V4 transport. No Python uploader is part of this path; older standalone scripts remain compatibility utilities. -Pack SemVer resolution (`release_version()`): +The native boundary resolves credentials privately from existing stores or environment. Missing credentials fail explicitly. Never put access keys or secrets in tool parameters, source or reports. A plugin grant has normal OS authority; --fs-root does not sandbox native plugins or child processes. -1. `MARQDO_EXT_VERSION` -2. CDN `GET …/latest/VERSION` (short timeout) -3. Embedded `ext/VERSION` at build time -4. CLI `CARGO_PKG_VERSION` - -## Separate ext release (no CLI bump) - -1. Bump `ext/VERSION` (e.g. `1.0.3`) — leave root `Cargo.toml` alone if CLI unchanged. -2. Build native zips (CI Linux/Windows jobs or local `scripts/build-web-plugin.sh` + cargo plugins). -3. Package `marqdo-{VER}-ext.zip` and `marqdo-{VER}-native-*.zip`. -4. Upload **both**: - - R2: `python3 scripts/upload-ext-r2.py --version VER --from-dir dist/` - - GitHub: attach to a GitHub Release (tag `ext-vVER` **or** reuse latest CLI release assets) -5. Confirm `https://ext.marqdo.com/latest/VERSION` and a sample zip URL return 200. - -## Full product release (CLI + ext) - -Keep `ext/VERSION` equal to (or compatible with) CLI SemVer unless documenting a deliberate skew. CI still publishes GitHub assets; **after** CI green, run `upload-ext-r2.py` so CDN is populated (or add a CI step with R2 secrets). - -## Credentials - -| Where | What | -|-------|------| -| Local | `~/.marqdo/r2.env` (`chmod 600`) — see `.env.r2.example` | -| CI (optional) | GitHub Actions secrets: `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_ENDPOINT`, `R2_BUCKET` | - -**Never** commit Account API tokens or S3 secret keys. If a token was pasted into chat, **rotate** it in the Cloudflare dashboard. - -## Object ACL - -Custom domain public reads require the bucket/objects to be publicly readable (R2 public bucket / r2.dev / custom domain). Uploads use S3 API credentials; downloads by `ext add` are anonymous HTTPS GETs. +Isolated loopback tests use fake credentials to verify ZIP-before-VERSION ordering and failure stops. Read-only verification of the published 2.6.0 release has also exercised the actual GitHub/CDN parity path without republishing its assets. diff --git a/doc/design/ext-web-artifact.md b/doc/design/ext-web-artifact.md index 01cb5f7..ed49056 100644 --- a/doc/design/ext-web-artifact.md +++ b/doc/design/ext-web-artifact.md @@ -98,7 +98,9 @@ Welcome to the executable web. | title | title | Marqdo | | title | ``` -2026-11-08:View 已支持 row/column 容器与 markdown 叶子,容器值保持子表;显式 `view: main` Document 通过普通函数装配。完整工程见[布局实践](ext-web-layout-paradigm.md),实现边界见[优化说明](ext-web-handbook.md)。 +2026-11-08:View 已支持 row/column 容器与 markdown 叶子,容器值保持子表;显式 `view: main` Document 通过普通函数装配。 + +2026-11-10:同一五列 View 可放置具型 Resource 节点;结构仍只在启动时装配,数据查询、已挂载表单与会话导航在请求期间解析。无新增 frontmatter 或核心标记;见 [请求资源](web-view-resources.md)。普通离线渲染缺少请求上下文时明确报错,不伪造动态内容。完整工程见[布局实践](ext-web-layout-paradigm.md),实现边界见[优化说明](ext-web-handbook.md)。 `page.render nodes=` 是**唯一**主装配路径。禁止 `compose_main` / `compose_intro` 等碎片 DSL。 diff --git a/doc/design/ext-web-go-rewrite.md b/doc/design/ext-web-go-rewrite.md index 03d2e44..d5d1902 100644 --- a/doc/design/ext-web-go-rewrite.md +++ b/doc/design/ext-web-go-rewrite.md @@ -7,13 +7,15 @@ | 相关 | [ext-web.md](ext-web.md) · [ext-web-net.md](ext-web-net.md) · [web-net-capabilities.md](web-net-capabilities.md) · [ext-web-drivers.md](ext-web-drivers.md) · [web-assets-and-images.md](web-assets-and-images.md) · [ext-hosting-fill.md](ext-hosting-fill.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [web-asgi-servers-and-marqdo.md](web-asgi-servers-and-marqdo.md) | | 实现目录 | `plugins/web/`(**Go module**;产物仍为 `libweb.so` / `web.dll` / `libweb.dylib`) | | 作者面 | `ext/web/web.mq.md` · `ext/web/网页.mq.md`(**ABI 名与方法面保持兼容**;非另起一套 API) | -| 验收应用 | 工作区 `anlian`(暗恋见君):用 Marqdo 前后端脚本完整重写;**PostgreSQL + Redis 外接** | +| 当前验收 | 仓库内独立示例与临时夹具;完整站点、网络站点、浏览器与数据资源分别验证 | + +本文件记录 Go 原生层重写时期的 ABI 与实施背景。2026-11-10 起不再以外部业务工程作为仓库交付项;当前作者规范与可调用入口以 [Web Artifact 设计](ext-web-artifact.md)、[网页手册](../../ext/web/index.mq.md)和[编程规范](../library-development.mq.md)为准。下方旧 compose/类链清单是历史对照,不能当作当前推荐 API。 --- ## 0. 一句话 -用 **Go** 重写官方网络拓展库原生层(`plugins/web`),在 **C ABI v2 全量兼容** 前提下提供「网页制备」所需的全部服务端能力;`ext/web` 继续用 GFM 表 + `#` 类做作者面;应用(含暗恋见君)的前后端脚本全部用 Marqdo 书写。此举同时验证 **多语言 ABI 插件生态**(首个非 Rust 官方插件)。 +用 **Go** 重写官方网络拓展库原生层(`plugins/web`),在 **C ABI v2 全量兼容** 前提下提供「网页制备」所需的全部服务端能力;`ext/web` 继续用 GFM 表 + `#` 类做作者面;应用的前后端脚本全部用 Marqdo 书写。此举同时验证 **多语言 ABI 插件生态**(首个非 Rust 官方插件)。 **不是**最小 hello 插件;**不是**在旧 Rust 代码上打补丁(对齐 [ext-web.md](ext-web.md) **C5**)。 @@ -36,7 +38,7 @@ 2. **作者面可用**:现有 `ext/web` 示例与 `tests/ext/web-*`(含 live-server)在换 Go `.so` 后通过;无需作者改业务脚本(除非文档标明的 **G 增强**)。 3. **网页制备完备**:单站点可完成页面装配、样式/头/图、库表、表单、路由、中间件、鉴权/RBAC、上传下载、SEO/RSS/sitemap、WS、缓存、对象存储、反代、invoke——即 W0–W8 + P3 + C0–C4 + H1/H2 能力面。 4. **驱动外接**:`postgres://`、`redis://`、`s3://` 为正式一等能力(与 [ext-web-drivers.md](ext-web-drivers.md) 一致);SQLite / memory / file 仍支持本地与测试。 -5. **暗恋见君可写完**:用 Marqdo 后端脚本 + 浏览器 WASM 前端脚本重写 anlian 核心模块(见 §8);运行时仅依赖 `marqdo` + `libweb` + **外接 PostgreSQL + Redis**(可选 S3/RustFS)。 +5. **通用工作流可验证**:使用仓库内独立站点和临时夹具覆盖数据、鉴权、表单与实时能力(见 §8);SQLite 提供本地验收,PostgreSQL、Redis 和对象存储按各自可用环境另行验证。 6. **安装路径不变**:`marqdo ext add web`、`plugin.native_path name=web`、`MARQDO_WEB_PLUGIN`、产物文件名 `libweb.so` 等与 [ext-cli.md](ext-cli.md) 兼容。 ### 1.3 非目标 @@ -56,7 +58,7 @@ ```text ┌──────────────────────────────────────────────────────────────────┐ -│ 应用(anlian / 任意站点) │ +│ 应用(独立业务站点) │ │ · 后端 .mq.md:路由、业务、装配、invoke 处理函数 │ │ · 前端 .mq.md:WASM + lib/browser(作者零业务 JS) │ └────────────────────────────┬─────────────────────────────────────┘ @@ -284,41 +286,36 @@ Where 语义:等值 map、filter 表、OR / IN / BETWEEN、分页 offset/limit --- -## 7. G 增强(完备网页制备 + anlian;兼容之上增量) +## 7. G 增强(完备网页制备;兼容之上增量) > 以下为 **新增能力**,不替代 §5。作者面用新方法/新 configure 键;旧脚本不受影响。 | ID | 能力 | 动机 | 作者面草案 | |----|------|------|------------| -| **G-WS1** | **命名房间** WS:`join`/`leave`/`publish`;组名 ASCII(如 `chat.room.{id}`) | anlian 公聊/私聊 | `app.route_ws` 增 `mode=room` + `room_key`;或 `ws.room_*` ABI | +| **G-WS1** | **命名房间** WS:`join`/`leave`/`publish`;组名 ASCII(如 `chat.room.{id}`) | 独立聊天室 | `app.route_ws` 增 `mode=room` + `room_key`;或 `ws.room_*` ABI | | **G-WS2** | 房间消息钩子:先 `invoke`/落库再广播 | 「先写 PG 再推送」 | configure 或 route 表 `on_message=lib.member` | | **G-SESS1** | Session 后端可选 `redis://` | 多进程/多实例 | `web_session_new` url 或 auth 配置 `session=redis://` | | **G-CACHE1** | Redis pub/sub 可选作 WS 扇出后端 | 多进程 WS | `configure ws_backend=redis` | -| **G-API1** | Bearer API Key 校验原语(hash+pepper+scopes) | anlian `apikeys` | `web_api_key_check` + `# auth` 或独立小类;**业务 scopes 仍在 .mq.md** | -| **G-MAIL0** | (可选后续)SMTP 发送原语 | 邮箱验证码 | 不阻塞首版对等;列入 anlian 二期 | +| **G-API1** | Bearer API Key 校验原语(hash+pepper+scopes) | API 密钥资源 | `web_api_key_check` + `# auth` 或独立小类;**业务 scopes 仍在 .mq.md** | +| **G-MAIL0** | (可选后续)SMTP 发送原语 | 邮箱验证码 | 不阻塞首版对等;另列后续能力 | **明确仍属应用层(不进插件)**:反垃圾策略、草稿定时发布约定、好友关系、专题 `topic_bundles` 静态交互内容(静态挂载 + 前端 Marqdo/既有 JS 资产)。 --- -## 8. 暗恋见君验收矩阵(检测「能不能写完」) +## 8. 独立工作流与隔离验收 -外部依赖(允许):**PostgreSQL**、**Redis**;可选对象存储。 +仓库交付不依赖某个外部业务工程的源码或个人数据库。各能力保留在原生实现与领域资源中,通过维护中的独立示例验证;移出业务工程不构成删除通用功能的理由。 -| 模块 | Marqdo 后端 | Marqdo 前端 | 插件依赖 | 验收 | -|------|-------------|-------------|----------|------| -| 站点壳 / 首页 | `# page` + db | 局部刷新可选 WASM | listen、static、cache | 首页可开 | -| posts 帖子/评论/板块 | route + form + db | 发帖表单 WASM 可选 | CRUD、CSRF、upload | CRUD+列表详情 | -| news | 同上 | 同上 | 同上 | 列表详情 | -| accounts | auth + session +(二期 mail) | 登录表单 | argon2、session、gate | 注册登录 | -| profiles | db + storage | 头像上传 | storage/upload | 资料页 | -| search | db.search 或 PG 查询 + cache | — | db/cache | 关键词搜索 | -| chat | route_ws + G-WS1/2 + db | WS 客户端脚本 | Redis + WS rooms | 公聊+私聊实时 | -| apikeys | G-API1 + db | 管理页 | — | Bearer 调 API | -| webmaster | sitemap/robots | — | 已有 ABI | `/sitemap.xml` | -| topics | `app.static` → bundles | 既有静态交互 | static | 专题可访问 | +| 工作流 | 当前来源 | 实际核对 | +|---|---|---| +| 完整动态站点 | examples/web-site、examples/web-site-zh | 原主题规则、摘要与详情、当前记录、表单重试、会话导航及后台门禁 | +| 网络资源 | examples/web-net-site、examples/web-net-site-zh | Cookie/multipart、WebSocket 回显、真实表单与后台 | +| 客户端状态 | examples/web-spa-app、examples/web-collab-doc | 当前 WASM、历史记录、编辑、多标签实时协作 | +| 数据与租户 | tests/example_databases.rs、tests/web_handbook.rs | 独占临时数据库、已有记录保留、租户条件 | +| 原生插件 | plugins/web 内部测试 | 独立夹具下验证数据库、会话、运输、资源及渲染边界 | -**「写完」定义**:上述模块在 Marqdo 仓库或 `anlian` 旁路目录有可运行 `.mq.md` 站点;gold/手工脚本能走通主路径;不依赖 Django/Channels/Daphne/gunicorn。 +开发与验收由 skills/marqdo-dev/index.mq.md 编排,使用 marqdo call。完整示例的浏览器用例和 HTTP 用例不能替代 Postgres、Redis、OIDC 或外部服务的真实环境证据;未运行的边界仍需明确保留为未验证。 --- @@ -400,7 +397,7 @@ scripts/build-web-plugin.sh # go build -buildmode=c-shared -o …/libweb.so | **W-G11** | 定制 C2–C4 shell/layout/style/nav | ✅ `web-c2`–`c4` | | **W-G12** | G 增强 WS rooms + Redis session/pubsub + API key 原语 | ✅ 单测 + `web-g12-api-key-smoke` | | **W-G13** | 默认切换 Go `libweb`;归档 Rust;更新发版与 ext CLI | ✅ 离线+live gold(7 个 `*_live`)对 Go 全绿;`ext add`/`gold`/`release` 走 `scripts/build-web-plugin.sh`;Rust 移出 workspace;gold 强制 `MARQDO_WEB_PLUGIN` 避免 `~/.marqdo` 旧 so | -| **W-G14** | anlian Marqdo 重写主路径(可分仓或 `examples/anlian-mq/`) | ✅ `examples/anlian-mq/`(本地 SQLite + 粉玻璃主题 + 主路由/登录/片段;外接 PG/Redis 仍为增强路径) | +| **W-G14** | 历史业务站点主路径演示 | 历史演示工程已移出仓库;当前独立验收见 §8 | 每波次:**先补 Go 实现 → 跑对应 gold → 再进入下一波**。禁止跨波次留下「注册了但返回 stub 错误」的 ABI(除 W-G0 明确的未实现探测)。 @@ -414,7 +411,7 @@ scripts/build-web-plugin.sh # go build -buildmode=c-shared -o …/libweb.so | 金样例 | 现有 `tests/ext/web-*.mq.md`;构建脚本产出 `libweb.so` 后跑 | | Live | 现有 `*-live-server.mq.md` + curl | | 回归门禁 | CI:安装 Go → `scripts/build-web-plugin.sh` → `cargo test` 相关 web 项 | -| anlian | 独立 smoke:登录、发帖、WS 发言、API key | +| 独立站点 | 登录、表单、WebSocket 与 API 使用可控夹具分别验收 | --- @@ -450,6 +447,6 @@ scripts/build-web-plugin.sh # go build -buildmode=c-shared -o …/libweb.so 1. **全量重写** `plugins/web` 为 Go,**不是**最小闭环。 2. **既有网络拓展能力(§5)重写后必须仍可用**;作者面默认兼容。 3. **PostgreSQL / Redis 外接** 为一等公民;Marqdo 承担应用前后端脚本。 -4. **暗恋见君** 为完备性验收,不是缩小插件范围的借口。 +4. 完备性通过独立工作流和原生测试验证,不以外部业务工程缩小插件能力范围。 5. **多语言 ABI 生态** 以本插件为样板(G7)。 6. 开发严格按 **§10 波次** 推进;本文件为唯一施工图。 diff --git a/doc/design/ext-web-handbook.md b/doc/design/ext-web-handbook.md index 9910f0c..85f09dc 100644 --- a/doc/design/ext-web-handbook.md +++ b/doc/design/ext-web-handbook.md @@ -66,6 +66,6 @@ node tests/web/layout.browser.cjs /absolute/path/to/preview.html 它测量 1440px 下的外层与内层双栏、390px 下的两层纵向折叠,并检查无横向溢出。无需外部资源或业务 JavaScript。Go 单元测试覆盖递归 Markdown、顺序、带类型列式表、错误形状与 Document 显式执行边界。 -既有 Anlian 渲染测试已从硬编码个人数据库改为临时目录建表并注入已知数据,使完整 Go 套件无需个人站点状态。 +通用数据文档渲染测试已从硬编码个人数据库改为临时目录建表并注入已知数据,使完整 Go 套件无需个人站点状态。 Web 提交时,全库 Rust 为 436 通过、25 项既有策略/回放失败,基线失败集合相同。后续已单独修复 Rust→Lean 命令缺字段的问题:所有操作发送完整的 op、steps、value,进程错误保留退出码与 stderr。原 25 项失败全部消除,新增诊断回归后库级测试为 462 通过、0 失败。策略判定仍由 Lean 执行。 diff --git a/doc/design/ubuntu-ppa.md b/doc/design/ubuntu-ppa.md index 0a699b0..74db6a1 100644 --- a/doc/design/ubuntu-ppa.md +++ b/doc/design/ubuntu-ppa.md @@ -1,85 +1,49 @@ -# Ubuntu PPA packaging (Marqdo) +# Ubuntu PPA: executable packaging and publication -| | | +The maintained entry is [the release handbook](../../skills/marqdo-release/index.mq.md). [ubuntu.mq.md](../../skills/marqdo-release/ubuntu.mq.md) provides publication and observation tasks; [package.mq.md](../../skills/marqdo-release/package.mq.md) owns native metadata and staged file preparation. Their source contracts replace a separate command playbook. + +The PPA is ppa:cflmy/marqdo. Apt installs the interpreter; extensions remain independently installed by marqdo ext add. Upload acceptance alone is incomplete: the exact source must be published, its amd64 build must succeed and apt must expose the same Debian version. + +## Exact version and artifact + +| Value | Meaning | |---|---| -| Status | **Active** — `ppa:cflmy/marqdo`; noble builds need bundled Rust (Cargo.lock v4) | -| Maintainer | cflmy \ | -| GPG | `505943294D04C803` (fingerprint `52A1…C803`) | -| PPA | `ppa:cflmy/marqdo` | +| X.Y.Z | Cargo package.version and the authorized upstream | +| 1ppaN | Reviewed debian/changelog packaging revision | +| ~SERIES | Explicit Ubuntu target, normally noble | +| marqdo_X.Y.Z-1ppaN~SERIES_source.changes | Exact signed source artifact | +| ext/VERSION | Independent extension-pack version | -## Goal +Native upstream and debian_version tasks parse the actual files. The latter retains the reviewed revision, removes its old series suffix and selects the current upstream/target series. A packaging-only reupload needs an explicit changelog revision edit. Upload selects the exact computed filename, never the newest unrelated package from a previous release or another series. -Users install with: +## Callable workflow -```bash -sudo add-apt-repository ppa:cflmy/marqdo -sudo apt update -sudo apt install marqdo +Run from the checkout root after the user has authorized this CLI/full release. Replace X.Y.Z with that version: +```sh +marqdo call skills/marqdo-release/ubuntu.mq.md ship 'version="X.Y.Z"' 'series="noble"' --require-ok --effects plugin,fs.read --fs-root . --json +marqdo call skills/marqdo-release/ubuntu.mq.md status 'version="X.Y.Z"' 'series="noble"' --require-ok --effects plugin,net --fs-root . --json +marqdo call skills/marqdo-release/index.mq.md finish 'version="X.Y.Z"' 'mode="full"' --require-ok --effects plugin,net,fs.write --fs-root . --json ``` -CLI and extension packs stay independent: the `.deb` ships the **interpreter**; `marqdo ext add …` still pulls from **https://ext.marqdo.com** (then GitHub / proxy). +Status is observational: inspect complete as well as Result.ok. Finish turns incomplete publication into a failed Result, allowing --require-ok to stop automation while keeping evidence. A green GitHub run does not establish Launchpad completion or apt availability. -## Why bundled Rust? +## Native files and existing tools -Ubuntu **noble** ships cargo/rustc **1.75**, which cannot parse **Cargo.lock version 4** (`lock file version 4 requires -Znext-lockfile-bump`). Launchpad builders also have **no network**, so `ppa-build-source.sh` vendors crates **and** installs a modern toolchain into `third_party/rust` inside the `.orig.tar.xz`. `debian/rules` prefers that toolchain over distro cargo. +Marqdo reads version metadata and writes the staged Cargo configuration, Debian changelog and vendor-checksum repairs. Native filesystem, TOML and JSON functions carry the data. No generated Python reader or writer is used. Vendor repair removes backup entries that Debian cleaning would delete while retaining package digests and ordinary source hashes. -## One-time Launchpad setup +The existing Debian boundary uses Cargo vendor, tar/xz, the configured Rust installation, debuild, GPG and dput. The source archive includes vendored crates and the selected Rust toolchain for an offline build. Its script chooses a fixed default toolchain and exposes the existing override; it does not assume the build host compiler is sufficient. -1. Create PPA: https://launchpad.net/~cflmy/+activate-ppa → name e.g. `marqdo` -2. OpenPGP key already on Launchpad (done) -3. Sign Ubuntu Code of Conduct if Launchpad asks -4. Enable the Ubuntu **series** you upload for (e.g. noble) under PPA → Change details -5. On the build machine: +A new upstream may create an orig archive. Once Launchpad accepts that upstream, reuse the identical bytes and upload only the Debian revision. Never rebuild an accepted orig archive to work around a checksum rejection. A failed stage remains available for inspection. -```bash -sudo apt install build-essential debhelper devscripts dput lintian \ - dpkg-dev quilt cargo rustc pkg-config curl xz-utils -``` +## Recovery evidence -## Package layout +| Failure | Required action | +|---|---| +| sudo/GPG interaction unavailable | Complete the same concrete Debian boundary in the user's terminal, keeping version and series | +| Complete package version already used | Review and increment the Debian revision before another authorized upload | +| orig bytes differ | Retrieve and reuse the previously accepted archive | +| Offline vendor checksum failure | Inspect sanitize_vendor evidence and the retained staged tree | +| Source accepted, build pending/failed | Inspect the actual Launchpad build | +| Build green, apt metadata stale | Repeat apt observation for the exact version | -| File | Role | -|------|------| -| `debian/control` | Metadata (amd64; no distro cargo BD) | -| `debian/changelog` | Upload revisions (`1ppaN`) | -| `debian/rules` | `dh` + bundled/system cargo build | -| `scripts/ppa-build-source.sh` | Vendor + bundle Rust + `debuild -S` | -| `scripts/ppa-ship.sh` | apt deps + build + `dput` | - -## Versioning - -- Upstream SemVer: `Cargo.toml` / git tag `vX.Y.Z` -- Debian revision: `X.Y.Z-1ppaN~SERIES` (SERIES = `noble`, …) — bump `1ppaN` on packaging-only reuploads -- **Ext pack** SemVer (`ext/VERSION`) is **not** the deb version - -## One-shot (recommended) - -```bash -cd ~/work/marqdo -./scripts/ppa-ship.sh noble # tools → debuild -S → dput -./scripts/ppa-ship.sh noble -n # build only -``` - -If automation cannot enter sudo/GPG, tell the user these commands (do not invent alternatives): - -```bash -./scripts/ppa-build-source.sh noble -dput ppa:cflmy/marqdo ../build-area/marqdo_*~noble_source.changes -``` - -Watch: https://launchpad.net/~cflmy/+archive/ubuntu/marqdo/+builds - -## Failure notes - -| Symptom | Fix | -|---------|-----| -| `lock file version 4 requires -Znext-lockfile-bump` | Rebuild with current `ppa-build-source.sh` (bundles Rust); bump `1ppaN` | -| `failed to calculate checksum of: …/vendor/…/Cargo.toml.orig` | `dh_clean` purged `*.orig`; fixed via `dh_clean -Xvendor/` (+ strip `.orig` only when **creating a new** orig); bump `1ppaN` with **`-sd`** | -| `orig.tar.xz already exists … different contents` | Never rewrite an uploaded upstream `.orig`; reuse PPA file (`ppa-build-source.sh` downloads it) and `debuild -S -sd` | -| Same version rejected by Launchpad | Bump `debian/changelog` (`1ppa2`, …) | -| Wrong series | Enable series on PPA; rebuild with that series name | - -## Out of scope (v1 deb) - -- Shipping `ext/native/*.so` inside the deb (use CDN `ext add`) -- WASM / VSIX / non-amd64 +Public apt observation reads Packages.gz with native HTTP bytes and the bounded gzip boundary, then inspects actual package records. Isolated fixtures cover metadata selection, configuration writing and vendor-checksum preservation without uploading to a PPA. diff --git a/doc/design/web-view-resources.md b/doc/design/web-view-resources.md new file mode 100644 index 0000000..7ca13e4 --- /dev/null +++ b/doc/design/web-view-resources.md @@ -0,0 +1,25 @@ +# View 中的请求资源 + +状态:请求资源已实现,后续旧站点迁移继续进行。遵循 ADR 0007;沿用五列 View、普通表值与 Resource,不增加 Markdown 标记或 frontmatter 方言。 + +view: main 仍只在启动时执行一次。它返回的结构保留为 View 节点,服务器在每次请求准备会话、路由参数和 CSRF 后渲染。普通 Markdown、控件和布局没有额外业务执行;只有 type=resource 的节点把 value 中的已声明 Resource 交给对应原生处理器。 + +Resource 的职责明确分开:data_query 查询当前应用数据库;form_ref 引用显式挂载的表单;view_navigation 根据当前会话筛选导航。document_head 是纯文档资源,只贡献 SEO 与原生资源链接,不需要请求上下文。它们不接受任意页面属性,不恢复 compose_*、页面变异链或 app.configure。结构和文字继续递归拆成组件及 Markdown 叶子。 + +启动阶段检查节点和资源契约,不查询数据库、不提交表单。请求渲染失败保留真实诊断。离线纯渲染遇到查询、表单与会话导航时明确要求上下文,不伪造空列表、登录状态或表单提交成功。纯页头资源与普通内容可以直接预览。 + +数据查询使用原有数据库资源与条件格式,路由参数来自实际请求。表单通过原有系统路由处理,字段、规则和提交资源保持一致,并传递真实 CSRF 与返回地址。导航的可见性不能替代服务端鉴权。资源绑定和监听仍是独立步骤。 + +验收覆盖启动无数据查询、请求间新增数据可见、完整正文与摘要区分、动态路由条件、登录前后导航、表单校验与提交、CSRF、未知资源失败,以及原有静态布局和浏览器用例。 + + +已完成的实际证据:web-net-site 与 web-net-site-zh 使用这些资源完整迁移;web_handbook 在两个启动后端中验证请求期间的数据更新、表单错误重试、工具页与后台鉴权。原生 Go 测试验证结构装配不查询缺失数据库、未知资源失败、路径条件不污染保留定义、CSRF 拒绝与错误重试。browser_handbook.mjs 使用当前 WASM 验证连续回显、Enter 与空输入、实际提交与管理后台、窄屏布局。 + +入口与边界:component.resource(中文组件为“请求资源”,保留原“资源”作为脚本/样式引用)、data/view.query、form.reference 与 form.mount、component.navigation。表单挂载可显式保护实际系统提交路径,不能只保护展示页面。服务器回调继承授予的文件根,所选站点根只能收窄该范围;嵌套页面按统一站点根读取共享叶子,Endpoint 同样保留该上下文。 + + +片段沿用 /_part/{slot}:递归选择唯一具名区域,在当前请求上下文中解析其资源;不会把源码当作片段返回。未声明 main 槽时保留整组节点作为 main 的兼容回退,其他未知槽返回 404,重复槽保留歧义诊断。容器遍历与完整渲染共享同一类型表,不进入资源私有数据。 + +检视的 registered 范围复用真实监听的注册过程,捕获处理器路径但不执行处理器;不会初始化数据库、重置会话或调用页面。metadata 范围仅扫描文件声明与运行时模板。两者明确区分,不能把目录扫描当成资源绑定已经完成的证据。监听前使用同一注册校验,冲突以诊断返回。系统和声明清单均去重并稳定排序。 + +页头资源保留现有五列 View:组件只安放 `_type=document_head` 的具型值,原生渲染在离线和真实页面中收集到 head,不在正文或片段中渲染占位。它只有 meta 与 links 两个领域字段,不接受任意页面属性、HTML 壳或应用配置。元数据沿用 key/value 表与原生 SEO 行为,链接复用普通 Document 的资源表及双语字段。相同链接按完整定义去重,同名元数据冲突在启动前报错。元数据按键稳定输出,保证同一结构的预览与服务一致。URL 只允许站内绝对路径与 http(s),不读取或下载地址。charset、viewport、csrf-token 属于运行时,作者不能重声明。对应手册为 ext/web/head.mq.md 与 ext/web/页头.mq.md。 diff --git a/doc/library-development.mq.md b/doc/library-development.mq.md index 69b3889..99b885a 100644 --- a/doc/library-development.mq.md +++ b/doc/library-development.mq.md @@ -1,6 +1,6 @@ --- markup: occlusion -title: 库开发指南:源码即手册,手册即 SKILL,函数即工具 +title: Marqdo 编程规范:源码即手册,手册即 SKILL,函数即工具 description: 标准库与拓展库的叙述式开发规范,包含可以直接调用的真实示例。 import: 文件: lib/文件.mq.md @@ -8,7 +8,7 @@ import: 库开发指南:让说明、调用和实现长在同一份源码里。 -本文件供人和 AI 开发标准库、拓展库时直接阅读。目标是把库文件交给一个没有读过 +本文件供人和 AI 编写 Marqdo 程序、标准库、拓展库以及可执行 SKILL 时直接阅读。目标是把库文件交给一个没有读过 完整语法手册的模型,它仍能判断何时使用、提供哪些输入、如何调用、如何消费结果, 以及遇到失败时怎么办。完成这些任务所需的信息必须在库文件中,不依赖聊天历史、 隐藏提示词、另一份签名清单或模型猜测。修改实现所需的最少标记也在本文就地示范。 @@ -65,6 +65,10 @@ ext/sample/ 二、标题下面立即交代参数与返回。 +普通网页正文、内容叶子与静态文档可以继续使用内容标题;它们没有调用契约,不能为了 +满足函数格式而插入虚假的参数或返回值表。需要执行任务的 SKILL 应把操作写入 mq.md, +SKILL.md 只保留发现入口、适用范围和必要约束,避免两份独立维护的长命令清单。 + 每个真正可调用的函数使用函数标题。紧接标题先写参数表,再写返回表;没有参数时直接 放返回表。表格必须位于第一条执行语句之前。正文中的普通小节使用说明段和分隔线, 不要把“安装说明”“注意事项”等叙述标题误做成空函数。 @@ -142,6 +146,13 @@ ext/sample/ 调用产生的值先计算并命名,再在单元格中引用,不能假定表格里任意一段函数文本会执行。 普通值用列表和记录传递;读取集合使用 access,不能把描述标签误当作集合键。 +命令参数也作为数据写入表格:`"-p"`、`"--offline"` 等文本必须带引号; +裸写 `-p` 会被当成表达式而不是命令选项。已计算的路径使用反引号引用变量, +不要再拼接整段 shell 源码。需要同时被 call 与 View 使用的过程用普通函数标题, +例如 `## main`;`# main` 是对象入口,不能假定两者具有相同的调用语义。 +整数除法会保留整数语义;计算平均值优先使用统计库的 mean,或明确采用浮点输入, +并在非整除样例中验证结果,避免演示数据恰好整除掩盖精度问题。 + 不可变更新要保存返回的新值。少量动态键用表库的具名助手;解析与序列化才使用 JSON。 不要用长串 json.set/json.append 来拼原本一张表就能读懂的数据,也不要为每个数字或 单个字段创建层层转发的空壳函数。只有当一段逻辑需要解释、复用或独立验证时才提取职责。 @@ -159,6 +170,13 @@ ext/sample/ 六、把运行边界和工程验收写在开发者找得到的位置。 +实际开发也使用这些能力:读取、搜索、撰写和原子修订通过固有文件库完成;JSON、表格、 +散列和网络读取优先组合标准库。不要为已有能力再生成 Python 或 shell 程序。缺少能力时, +把可复用的边界补成拓展插件,或者通过明确参数数组外联已有工具;决策、条件和重试仍在 +mq.md 中表达。开发与发版入口分别位于 skills/marqdo-dev 和 skills/marqdo-release,操作用 +marqdo call 执行。大段源码通过 --args-json 文件或标准输入传输,保留换行、引号和字面数据。 +外部自动化可以加 --require-ok,让失败 Result 产生非零退出码,避免继续执行依赖步骤。 + 有副作用的能力写明授权、根目录、平台、超时、资源上限以及重试与清理责任。 返回可恢复结果时先检查其中的 ok,再读取 value 或 error;CLI 外层的 ok 只说明调用 是否完成,不替代函数结果、HTTP 状态或子进程退出码的判断。未知副作用不能声称为纯函数。 @@ -177,8 +195,8 @@ ext/sample/ 默认参数、结构化返回以及可恢复读取;修改库时还应运行该库本身相关的回归。 ```sh -marqdo check doc/library-development.mq.md --narrative-ratio -cargo test --test stdlib_tasks library_development_guide_examples_match_their_contracts +marqdo call skills/marqdo-dev/index.mq.md check 'path="doc/library-development.mq.md"' --require-ok --effects plugin --fs-root . --json +marqdo call skills/marqdo-dev/index.mq.md test 'targets=["stdlib_tasks"]' 'filter="library_development_guide_examples_match_their_contracts"' --require-ok --effects plugin --fs-root . --json ``` 现有能力可直接参考 [文件库](../lib/文件.mq.md)、[表库](../lib/表.mq.md)、 diff --git a/doc/releases/v2.7.0.md b/doc/releases/v2.7.0.md new file mode 100644 index 0000000..eb3e4f4 --- /dev/null +++ b/doc/releases/v2.7.0.md @@ -0,0 +1,48 @@ +# Marqdo 2.7.0 + +本次 full 发布把源码手册落到实际开发与用户站点:文件操作、开发检查、构建与发版阶段可通过 marqdo call 执行;站点以递归组件、普通 Markdown 和明确的原生资源表达页面与行为。 + +This full release makes executable source handbooks practical for development and user sites. Native file tools and callable development/release tasks replace generated orchestration programs. Recursive View components preserve ordinary Markdown content and explicit runtime resources. + +## 亮点 / Highlights + +- 开发与发版 SKILL 路由到可执行 .mq.md 手册;文件读取、审阅、摘要校验和写入使用固有标准库。工程插件承担有界进程、私密认证、压缩格式和实际编译器检查边界,流程不依赖 Python 编排。 +- Literal JSON file/stdin CLI arguments preserve quotes, newlines and dollar-prefixed text. --require-ok makes a failed Result stop external automation; saved call sessions retain literal argument semantics. +- 中英文网络站点与完整用户站点改为递归 View 布局、Markdown 内容、当前数据查询、表单、真实会话导航与鉴权资源。原有配色、字体、布局、文章详情和管理功能保留。 +- Pure document_head resources carry SEO and resource links into the actual head. Request-time query/form/navigation resources preserve the existing five-column View schema, source context and explicit effect boundaries. Prepared-app inspection follows the real registrar without executing handlers. +- 原生 SQLite 初始化按实际站点授权根定位,保留已有业务记录;嵌套 Document 与 Endpoint 使用一致的站点根。修复表单校验重试中的 CSRF、成功跳转以及嵌套片段选择与路由检查。 +- The browser bridge supports typed nested list/control records. The maintained browser-app demonstrates duplicate-safe identities, literal text, truthful storage/network feedback, real history and local WebSocket echo with no authored business JavaScript. +- 移除与语言仓库无关的暗恋工程及过时的独立浏览器演示;底层 WASM 冒烟夹具与公共回归保留。维护入口收敛到实际可运行的工程。 + +## 核心表面与兼容边界 / Core surface and boundaries + +核心构造仍为 19 个,没有新增 Markdown 标记。改动集中在已有标记解析、CLI 参数传送、Runtime / Document 资源及工程工具;原生插件仍具有调用用户的操作系统权限,--fs-root 不把外部进程变成沙箱。显式 raw HTML 兼容出口不等同于不可信内容清理。编译检查与叙述比例检查不能单独证明运行或视觉正确。 + +The core surface remains 19 constructs. Native-only filesystem, process and authenticated service capabilities do not become browser WASM capabilities. Atomic file replacement is not a multi-file transaction, and digest preflight is not a kernel compare-and-swap. Deployment credentials remain in private stores. + +## 下载 / Downloads + +| 产物 / Asset | 内容 / Contents | +|---|---| +| marqdo-2.7.0-x86_64-pc-windows-msvc.exe | Windows CLI,内嵌标准库 / CLI with embedded standard library | +| marqdo-2.7.0-x86_64-pc-windows-msvc.zip | Windows CLI、标准库、拓展源码与原生插件 / complete Windows bundle | +| marqdo-2.7.0-x86_64-unknown-linux-gnu.zip | Linux CLI、标准库、拓展源码与原生插件 / complete Linux bundle | +| marqdo-2.7.0-stdlib.zip | 可读标准库源码 / readable standard-library sources | +| marqdo-2.7.0-ext.zip | 官方拓展库源码 / official extension sources | +| marqdo-2.7.0-native-x86_64-pc-windows-msvc.zip | Windows web、agent、quantum、linalg、llm、engineering 插件 | +| marqdo-2.7.0-native-x86_64-unknown-linux-gnu.zip | Linux web、agent、quantum、linalg、llm、engineering 插件 | +| marqdo-2.7.0-source.zip | 本标签的源码快照 / tagged source snapshot | +| marqdo-2.7.0.vsix | VS Code / Cursor 扩展,源码独立分支 / separate editor-source branch | +| marqdo-2.7.0-public.zip | 由实际 .mq.md 导出的静态用户站点 / exported public documentation | + +## 安装与使用 / Installation and use + +下载对应平台的完整 ZIP,解压后使用其中的 CLI 与 lib/ext。已有 CLI 可通过 marqdo ext add 安装官方拓展;具体调用从标准库单文件或拓展库 index.mq.md 的参数与返回表开始。Linux 用户也可使用项目现有 Ubuntu noble PPA 安装路径;实际 apt 可用性以发布验证结果为准。 + +Download and unpack the matching platform bundle. Start from each standard-library source or extension index.mq.md. Development tools live in skills/marqdo-dev/index.mq.md; release tasks live in skills/marqdo-release/index.mq.md. A callable task preserves actual failures and grants only its declared effects. See README for the maintained install routes. + +## 验证 / Validation + +本地全量 Rust 验收为 1031 通过、0 失败、2 个原有模型实验忽略项;Go 网络插件完整测试通过。清理后重跑的 21 项 CLI/发版/WASM 测试以及 7 项真实浏览器用例通过,实际用户文档成功导出 102 页。源码审查单独检查标题下契约与超过一半的叙述;普通测试、人工夹具和历史兼容样例保留既有用途。 + +Windows and Linux release builds run in CI for this exact source tag. Final release verification separately checks those jobs, all artifact contents and hashes, GitHub/R2 byte parity and VERSION ordering, and Ubuntu source/build/apt publication. A local Linux test is not evidence of Windows execution or completed package publication. Public documentation export is packaged here; gh-pages deployment is separate. diff --git a/doc/roadmap/browser-wasm-f.md b/doc/roadmap/browser-wasm-f.md index b6e9877..3872edd 100644 --- a/doc/roadmap/browser-wasm-f.md +++ b/doc/roadmap/browser-wasm-f.md @@ -1,5 +1,8 @@ # 路线图:浏览器 Marqdo 路线 F(进阶宿主能力) +> 2.7.0 维护说明:独立的 browser-hello 与 browser-media 演示已删除。下文保留既有能力设计与宿主边界,当前可运行工程使用 browser-app;底层计数器冒烟夹具位于 tests/wasm/counter.mq.md。Canvas、音频等仍是 lib/browser 的宿主能力,不宣称当前 browser-app 演示包含这些交互。 + + | | | |---|---| | 状态 | **Completed**(F1–F5;F6 Service Worker 可选未做) | @@ -23,4 +26,4 @@ | **F5** | drag/drop wire + `data-drag` / `drop_text` | **done** | | **F6** | Service Worker / 离线缓存 | optional / skipped | -示例:[examples/browser-media/](../../examples/browser-media/) · 助手:`lib/browser.mq.md`。 +示例:[examples/browser-app/](../../examples/browser-app/) · 助手:`lib/browser.mq.md`。 diff --git a/doc/roadmap/browser-wasm.md b/doc/roadmap/browser-wasm.md index 1caf137..2b63066 100644 --- a/doc/roadmap/browser-wasm.md +++ b/doc/roadmap/browser-wasm.md @@ -1,5 +1,8 @@ # 路线图:浏览器 Marqdo(WASM) +> 2.7.0 维护说明:独立的 browser-hello 与 browser-media 演示已删除。下文保留既有能力设计与宿主边界,当前可运行工程使用 browser-app;底层计数器冒烟夹具位于 tests/wasm/counter.mq.md。Canvas、音频等仍是 lib/browser 的宿主能力,不宣称当前 browser-app 演示包含这些交互。 + + | | | |---|---| | 状态 | **Completed**(路线 C 首版功能完备;续作见 [browser-wasm-d.md](browser-wasm-d.md)) | @@ -23,7 +26,7 @@ | ABI crate | `crates/marqdo-wasm` | | 官方 bridge | `crates/marqdo-wasm/js/marqdo-bridge.js` | | CLI | `marqdo wasm build -o DIR` | -| 示例 | `examples/browser-hello/` | +| 示例 | `examples/browser-app/` | | 冒烟 | `tests/wasm/smoke.mjs` · `tests/wasm_smoke.rs` | | L1 | `web.client_embed` / `网页.客户端挂载` | diff --git a/examples/agent-okf-flywheel/index.mq.md b/examples/agent-okf-flywheel/index.mq.md index 3e965e2..116f6ce 100644 --- a/examples/agent-okf-flywheel/index.mq.md +++ b/examples/agent-okf-flywheel/index.mq.md @@ -13,50 +13,58 @@ import: # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + +This is an offline knowledge-reuse workflow, not a request to an external model. It loads the agent plugin, promotes the visible workbook for one exact goal and asks the same agent goal again. The expected hit comes from the promoted knowledge base. The dummy key only satisfies model setup; it is not a credential or evidence that a model call succeeded. + +The example uses its own named files under .marqdo and replaces that example knowledge base on rerun. Grant the actual plugin and filesystem effects in a disposable example root. Promotion and execution are separate outcomes: inspect promoted first, then cache, match and the returned result. A hit marker alone does not prove that an unrelated new goal is safe to reuse. + OKF flywheel offline: promote → plan same goal → `cache=hit` (no live LLM required for the hit path). -**p = > plugin.native_path name="agent"** +We first **p = [Compute p](plugin.native_path(name="agent"))** for the next step. 1. `p` - > plugin.load path=`p` + We now **[Call plugin.load](> plugin.load path=`p`)**. 2. * - > print text=no-agent-plugin - > sys.exit code=1 + We now **[Display this step's result](> print text="no-agent-plugin")**. + We now **[Call sys.exit](> 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"** +We now **[Call sys.env set](> sys.env_set name="OPENAI_API_KEY" value="offline-okf-dummy")**. +We first **model = [Compute model](llm.llm())** for the next step. +We first **tools = [Compute tools](json.parse(text="[]"))** for the next step. +We first **助手 = [Compute 助手](agent.agent(model=`model`, tools=`tools`, standing="offline okf flywheel"))** for the next step. -**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"** +We first **kb = ".marqdo/agent-kb-example-flywheel"** for the next step. +We first **wb = ".marqdo/agent-runs/example-pong-solid.mq.md"** for the next step. +We first **goal = "Reply with exactly the word pong and nothing else."** for the next step. +We first **body = "---\ntitle: okf pong\n---\n\n# main\n\n*msg = \"pong\"*\n\n**msg**\n"** for the next step. 1. > fs.exists path=`kb` - > fs.remove path=`kb` + We now **[Call fs.remove](> fs.remove path=`kb`)**. 2. * --- -> fs.write_text path=`wb` text=`body` +We now **[Call fs.write text](> 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"** +We first **prom = [Compute prom](agent_kb_promote(kb_dir=`kb`, goal=`goal`, workbook=`wb`))** for the next step. +We first **okp = [Compute okp](json.get(value=`prom`, key="promoted"))** for the next step. 1. `okp` - > print text=promoted + We now **[Display this step's result](> print text="promoted")**. 2. * - > print text=promote-fail - > sys.exit code=1 + We now **[Display this step's result](> print text="promote-fail")**. + We now **[Call sys.exit](> 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` +We first **out = [Compute out](> `助手`.plan goal=`goal` max_rounds=2 writeback=False kb_dir=`kb` explore_n=0 promote=False)** for the next step. +We first **cache = [Compute cache](json.get(value=`out`, key="cache"))** for the next step. +We now **[Display this step's result](> print text=`cache`)**. +We first **match = [Compute match](json.get(value=`out`, key="match"))** for the next step. +We now **[Display this step's result](> print text=`match`)**. +We first **val = [Compute val](json.get(value=`out`, key="result"))** for the next step. +We now **[Display this step's result](> print text=`val`)**. 1. `cache` == "hit" - > print text=flywheel-ok + We now **[Display this step's result](> print text="flywheel-ok")**. 2. * - > print text=flywheel-miss - > sys.exit code=1 + We now **[Display this step's result](> print text="flywheel-miss")**. + We now **[Call sys.exit](> sys.exit code=1)**. diff --git a/examples/agent-pong/index.mq.md b/examples/agent-pong/index.mq.md index 35c6be7..4706c92 100644 --- a/examples/agent-pong/index.mq.md +++ b/examples/agent-pong/index.mq.md @@ -15,21 +15,33 @@ import: ## 获取时间 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | The value explicitly returned below; conditional returns follow the selected branch | + Return today's date string (tool visible in source to the model). -**u = > time.now_unix** -*> time.format unix=`u` pattern="%Y-%m-%d"* +We first **u = [Compute u](time.now_unix())** for the next step. +After these steps, return *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 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | -> llm.load_env path="../../.env" +This entry first verifies what the agent can read about its own call site. It assembles a step context and checks for the call-site section, source section and the actual time-tool name before considering an optional live step. The tool table points to the real local function; it is not an independently maintained tool description detached from the source. + +Normal demonstration stops at context evidence and does not require a paid model response. AGENT_LIVE and an available key together opt into the separate live branch. Context markers establish prompt content, not the correctness of a future model answer. Keep the tool result and returned status visible when exercising that branch; never replace a missing credential with a fixed successful response. + +We first **p = [Compute p](plugin.native_path(name="agent"))** for the next step. +1. `p` + We now **[Call plugin.load](> plugin.load path=`p`)**. +2. * + We now **[Display this step's result](> print text="no-agent-plugin")**. + We now **[Call sys.exit](> sys.exit code=1)**. + +We now **[Call llm.load env](> llm.load_env path="../../.env")**. `工具表` = @@ -37,55 +49,55 @@ Return today's date string (tool visible in source to the model). |------| | 获取时间 | -**model = > llm.llm** -**助手 = > agent.agent model=`model` tools=`工具表` standing="You are a Marqdo agent. Prefer CALL:获取时间 when the task needs today's date."** +We first **model = [Compute model](llm.llm())** for the next step. +We first **助手 = [Compute 助手](agent.agent(model=`model`, tools=`工具表`, standing="You are a Marqdo agent. Prefer CALL:获取时间 when the task needs today's date."))** for the next step. 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."** +We first **ctx = [Compute ctx](agent.build_step_context(agent=`助手`, task="What is today's date? Use the tool in this runbook."))** for the next step. -**parts = > split value=`ctx` sep="--- call site ---"** -**n = > len value=`parts`** +We first **parts = [Compute parts](split(value=`ctx`, sep="--- call site ---"))** for the next step. +We first **n = [Compute n](len(value=`parts`))** for the next step. 1. `n` > 1 - > print text=call-site-ok + We now **[Display this step's result](> print text="call-site-ok")**. 2. * - > print text=call-site-missing - > sys.exit code=1 + We now **[Display this step's result](> print text="call-site-missing")**. + We now **[Call sys.exit](> sys.exit code=1)**. -**parts2 = > split value=`ctx` sep="--- source (.mq.md) ---"** -**n2 = > len value=`parts2`** +We first **parts2 = [Compute parts2](split(value=`ctx`, sep="--- source (.mq.md) ---"))** for the next step. +We first **n2 = [Compute n2](len(value=`parts2`))** for the next step. 1. `n2` > 1 - > print text=source-ok + We now **[Display this step's result](> print text="source-ok")**. 2. * - > print text=source-missing - > sys.exit code=1 + We now **[Display this step's result](> print text="source-missing")**. + We now **[Call sys.exit](> sys.exit code=1)**. -**parts3 = > split value=`ctx` sep="获取时间"** -**n3 = > len value=`parts3`** +We first **parts3 = [Compute parts3](split(value=`ctx`, sep="获取时间"))** for the next step. +We first **n3 = [Compute n3](len(value=`parts3`))** for the next step. 1. `n3` > 1 - > print text=tool-in-source-ok + We now **[Display this step's result](> print text="tool-in-source-ok")**. 2. * - > print text=tool-in-source-missing - > sys.exit code=1 + We now **[Display this step's result](> print text="tool-in-source-missing")**. + We now **[Call sys.exit](> sys.exit code=1)**. -**site = > agent_call_site** -**fn = > json.get value=`site` key="function"** -> print text=`fn` +We first **site = [Compute site](agent_call_site())** for the next step. +We first **fn = [Compute fn](json.get(value=`site`, key="function"))** for the next step. +We now **[Display this step's result](> 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"** +We first **live = [Compute live](sys.env_get(name="AGENT_LIVE"))** for the next step. +We first **key = [Compute key](sys.env_get(name="OPENAI_API_KEY"))** for the next step. 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` + We first **out = [Compute out](> `助手`.step task="请调用获取时间工具,然后只回复日期字符串。" writeback=False)** for the next step. + We first **status = [Compute status](json.get(value=`out`, key="status"))** for the next step. + We now **[Display this step's result](> print text=`status`)**. + We first **tool = [Compute tool](json.get(value=`out`, key="tool"))** for the next step. + We now **[Display this step's result](> print text=`tool`)**. + We first **result = [Compute result](json.get(value=`out`, key="result"))** for the next step. + We now **[Display this step's result](> print text=`result`)**. 2. * - > print text=live-skipped-no-key + We now **[Display this step's result](> print text="live-skipped-no-key")**. 2. * - > print text=live-skipped + We now **[Display this step's result](> print text="live-skipped")**. diff --git a/examples/agent-sandbox-okf/index.mq.md b/examples/agent-sandbox-okf/index.mq.md index 744c1dd..7640988 100644 --- a/examples/agent-sandbox-okf/index.mq.md +++ b/examples/agent-sandbox-okf/index.mq.md @@ -10,52 +10,60 @@ import: # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + +The two trials intentionally differ only in commit. First inspect a successful dry trial and verify that note.txt has not appeared in the host directory. Then run the committed trial, read the host file and compare its actual content. This separates an observed proposal from an observed filesystem change; neither ok alone nor a proposed path establishes that a commit happened. + +Use a disposable filesystem root: the example replaces its named _example_sbx directory and leaves the committed evidence there for inspection. It does not promise to roll back a committed external effect. Read the returned profile as part of the trial evidence, and keep failures visible rather than manufacturing a success marker when the expected file is absent. + Short demo: write via `agent.trial`, prove the host is clean until commit. -**had = fs.exists path="_example_sbx"** +We first **had = [Compute had](fs.exists(path="_example_sbx"))** for the next step. 1. `had` - > fs.remove path="_example_sbx" + We now **[Call fs.remove](> fs.remove path="_example_sbx")**. 2. * - **_ = 0** + We first **_ = 0** for the next step. -> fs.make_dir path="_example_sbx" +We now **[Call fs.make dir](> fs.make_dir path="_example_sbx")**. -**dry = agent.trial root="_example_sbx" write_path="note.txt" text=sandbox-okf commit=False** -**dry_ok = [ok](access(dry, "ok"))** -**dry_committed = [committed](access(dry, "committed"))** +We first **dry = [Compute dry](agent.trial(root="_example_sbx", write_path="note.txt", text="sandbox-okf", commit=False))** for the next step. +We first **dry_ok = [ok](access(`dry`, "ok"))** for the next step. +We first **dry_committed = [committed](access(`dry`, "committed"))** for the next step. 1. `dry_ok` 1. not `dry_committed` - > print text=dry-ok + We now **[Display this step's result](> print text="dry-ok")**. 2. * - > print text=dry-bad-commit + We now **[Display this step's result](> print text="dry-bad-commit")**. 2. * - > print text=dry-fail + We now **[Display this step's result](> print text="dry-fail")**. -**leaked = fs.exists path="_example_sbx/note.txt"** +We first **leaked = [Compute leaked](fs.exists(path="_example_sbx/note.txt"))** for the next step. 1. `leaked` - > print text=host-leaked + We now **[Display this step's result](> print text="host-leaked")**. 2. * - > print text=host-clean + We now **[Display this step's result](> print text="host-clean")**. -**wet = agent.trial root="_example_sbx" write_path="note.txt" text=sandbox-okf commit=True** -**wet_ok = [ok](access(wet, "ok"))** -**wet_committed = [committed](access(wet, "committed"))** +We first **wet = [Compute wet](agent.trial(root="_example_sbx", write_path="note.txt", text="sandbox-okf", commit=True))** for the next step. +We first **wet_ok = [ok](access(`wet`, "ok"))** for the next step. +We first **wet_committed = [committed](access(`wet`, "committed"))** for the next step. 1. `wet_ok` 1. `wet_committed` - > print text=wet-ok + We now **[Display this step's result](> print text="wet-ok")**. 2. * - > print text=wet-no-commit + We now **[Display this step's result](> print text="wet-no-commit")**. 2. * - > print text=wet-fail + We now **[Display this step's result](> print text="wet-fail")**. -**body = fs.read_text path="_example_sbx/note.txt"** +We first **body = [Compute body](fs.read_text(path="_example_sbx/note.txt"))** for the next step. 1. `body` == "sandbox-okf" - > print text=proof-visible + We now **[Display this step's result](> print text="proof-visible")**. 2. * - > print text=proof-missing + We now **[Display this step's result](> print text="proof-missing")**. -**pname = [name](access([profile](access(wet, "profile")), "name"))** +We first **pname = [name](access([profile](access(`wet`, "profile")), "name"))** for the next step. 1. `pname` == "default" - > print text=profile-default + We now **[Display this step's result](> print text="profile-default")**. 2. * - > print text=profile-other + We now **[Display this step's result](> print text="profile-other")**. diff --git a/examples/anlian-mq/README.md b/examples/anlian-mq/README.md deleted file mode 100644 index b096bd7..0000000 --- a/examples/anlian-mq/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# 暗恋见君 · Marqdo 重写 - -用 **Marqdo + `ext/web`(Go `libweb`)** 对齐 Django [anlian](../../../anlian/) 的主浏览路径与视觉:原站 CSS/JS、首页四段、列表/详情、发帖门禁、聊天室、专题、搜索入口、API 指南。 - -默认 **SQLite**(`data/anlian-mq.db`);生产可换 `postgres://` + Redis。 - -## 设计约定 - -| 做 | 不做 | -|----|------| -| GFM 表装配库表/种子/表单/门禁/头资源 | `json.set` 链拼页面 | -| 原站 `public/css|js|img` + DOM class 对齐 | 另起一套模板糊弄验收 | -| `页面.壳HTML` 挂 Django 级导航/页脚 | 业务写进 Go 插件 | -| 缺能力时改 `ext/web` / `libweb` | 在应用层堆不可读胶水 | - -## 路径(对齐原站) - -| 路径 | 能力 | -|------|------| -| `/` | Hero + 公告 + 新闻时间线 + 论坛板块栏/卡片 | -| `/post`、`/post/{slug}` | 帖子列表 / 详情 | -| `/news`、`/news/{slug}` | 新闻列表 / 详情 | -| `/post/public` | 发帖(需登录) | -| `/post/ten`、`/news/five` | 首页 AJAX 片段 | -| `/chat`、`/chat/lobby`、`/chat/casual` | 房间列表 + 公聊 WS | -| `/topics` | 专题书架 | -| `/search` | 搜索入口 | -| `/guide/automation-api` | API 指南 | -| `/accounts/login` | 粉玻璃登录 | -| `/sitemap.xml`、`/robots.txt` | 站长 | - -## 运行 - -```bash -export PATH="$HOME/.local/go/bin:$PATH" -./scripts/build-web-plugin.sh -export MARQDO_WEB_PLUGIN=$PWD/plugins/web/build/libweb.so -rm -f examples/anlian-mq/data/anlian-mq.db* # 首次或改 schema 后 -./target/debug/marqdo run examples/anlian-mq/index.mq.md -# → http://127.0.0.1:18180/ - -bash examples/anlian-mq/smoke.sh -``` - -默认账号:`admin` / `anlian`。 diff --git a/examples/anlian-mq/components/chrome.mq.md b/examples/anlian-mq/components/chrome.mq.md deleted file mode 100644 index 75768bc..0000000 --- a/examples/anlian-mq/components/chrome.mq.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -markup: occlusion -title: components/chrome -description: 暗恋见君壳层 — head 资源表、导航 HTML、页脚 HTML(对齐 Django base / site_footer)。 ---- - -## 头资源 - -首页与浏览页共用的 CSS / JS 链接表(挂到 `页面.头装配`)。路径对齐 `public/` 静态树。 - -`头` = - -| 关系 | 地址 | 推迟 | -|------|------|------| -| stylesheet | "/static/vendor/bootstrap-anlian.min.css" | | -| stylesheet | "/static/css/base.css" | | -| stylesheet | "/static/css/navbar_search.css" | | -| stylesheet | "/static/css/footer.css" | | -| stylesheet | "/static/css/icons.css" | | -| stylesheet | "/static/css/feed_common.css" | | -| stylesheet | "/static/css/feed_list.css" | | -| stylesheet | "/static/css/index.css" | | -| stylesheet | "/static/css/index/hero.css" | | -| stylesheet | "/static/css/index/notice.css" | | -| stylesheet | "/static/css/index/home_news_timeline.css" | | -| stylesheet | "/static/css/index/home_posts.css" | | -| stylesheet | "/static/css/anlian_forms.css" | | -| stylesheet | "/static/css/login.css" | | -| stylesheet | "/static/css/rich_content.css" | | -| stylesheet | "/static/css/detail_reading.css" | | -| stylesheet | "/static/css/search.css" | | -| stylesheet | "/static/css/chat.css" | | -| stylesheet | "/static/css/topic_index.css" | | -| script | "/static/vendor/bootstrap.bundle.min.js" | 真 | -| script | "/static/js/anlian_partial.js" | 真 | -| script | "/static/js/feed_board.js" | 真 | -| script | "/static/js/index.js" | 真 | - -*`头`* - -## 导航HTML - -对齐 Django `front/base.html` 顶栏:品牌「暗恋见君论坛」、主导航、搜索、登录/退出(`nav-when-guest` / `nav-when-auth` 由 CSS/JS 切换)。 - -**""** - -## 页脚HTML - -对齐 `site_footer`:站点列 + 作者列;标语、版权、API 指南、作者 cflmy。 - -**"
"** diff --git a/examples/anlian-mq/components/feed.mq.md b/examples/anlian-mq/components/feed.mq.md deleted file mode 100644 index ef4c821..0000000 --- a/examples/anlian-mq/components/feed.mq.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -markup: occlusion -title: components/feed -description: 帖子列表 / 新闻时间线 / 板块栏 HTML 片段(对齐 Django feed 与 home 局部模板)。 -import: - table: lib/table.mq.md - text: lib/text.mq.md ---- - -## 帖子列表HTML - + `行` - -给定帖子行记录列表,输出 `ul.home-posts-list` 标记(首页与列表页共用)。 - -**段 = None** -- [帖](遍历 行 为 帖) - **板 = [board](access(帖, "board"))** - **题 = [title](access(帖, "title"))** - **链 = [slug](access(帖, "slug"))** - **作 = [author](access(帖, "author"))** - **评 = [comments_count](access(帖, "comments_count"))** - **时 = [created_at](access(帖, "created_at"))** - 1. not 作 - **作 = "匿名"** - 2. * - 1. not 评 - **评 = 0** - 2. * - 1. not 时 - **时 = ""** - 2. * - **一项 = "
  • "** - **段 = > table.append list=段 item=一项** -1. 段 - **内 = > text.str_join xs=段 sep=""** - *"
      " + 内 + "
    "* -2. * - *""* - -## 新闻时间线HTML - + `行` - -给定新闻行记录列表,输出 `.news-timeline` 标记。 - -**段 = None** -- [讯](遍历 行 为 讯) - **题 = [title](access(讯, "title"))** - **链 = [slug](access(讯, "slug"))** - **板 = [board](access(讯, "board"))** - **时 = [created_at](access(讯, "created_at"))** - 1. not 板 - **板 = ""** - 2. * - 1. not 时 - **时 = ""** - 2. * - **一项 = "
  • "** - **段 = > table.append list=段 item=一项** -1. 段 - **内 = > text.str_join xs=段 sep=""** - *"
      " + 内 + "
    "* -2. * - *"
    1. 暂无新闻

    "* - -## 板块栏HTML - + `板块` - + `前缀` - + `查询键` - + `全部类` - -板块 Tab 栏。`前缀` 如 `/post/ten/`;`查询键` 为 `board_id` 或 `news_board_id`;`全部类` 为 Tab 共用 class(含 js hook)。 - -**数据属 = "data-board"** -**全标签 = "全部"** -1. 查询键 == "news_board_id" - **数据属 = "data-news-board"** - **全标签 = "所有板块"** -2. * - -**段 = None** -**全链 = 前缀 + "?" + 查询键 + "=0"** -**全项 = "" + 全标签 + ""** -**段 = > table.append list=段 item=全项** -- [板](遍历 板块 为 板) - **名 = [name](access(板, "name"))** - **号 = [id](access(板, "id"))** - **链 = 前缀 + "?" + 查询键 + "=" + 号** - **项 = "" + 名 + ""** - **段 = > table.append list=段 item=项** -1. 查询键 == "news_board_id" - **更多 = "全部新闻"** - **段 = > table.append list=段 item=更多** -2. * -**内 = > text.str_join xs=段 sep=""** -**栏类 = "home-posts-board-bar"** -1. 查询键 == "news_board_id" - **栏类 = "home-posts-board-bar home-news-board-bar"** -2. * -*"
    " + 内 + "
    "* diff --git a/examples/anlian-mq/components/foot.mq.md b/examples/anlian-mq/components/foot.mq.md deleted file mode 100644 index 866e7e7..0000000 --- a/examples/anlian-mq/components/foot.mq.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -markup: occlusion ---- - -## 页脚 - -站点信息与站长链接(毛玻璃底由壳样式绘制)。 - -`页脚` = - -| 属性 | 值 | -|------|-----| -| 暗恋见君 · 期待人们能够继续相信爱情 | / | -| 帖子 | /posts | -| 新闻 | /news | -| 公聊 | /chat | -| sitemap | /sitemap.xml | - -*`页脚`* diff --git a/examples/anlian-mq/components/fragments.mq.md b/examples/anlian-mq/components/fragments.mq.md deleted file mode 100644 index d91ae0a..0000000 --- a/examples/anlian-mq/components/fragments.mq.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -markup: occlusion -title: components/fragments -description: AJAX 片段 — /post/ten、/news/five。 -导入: - 网页: ext/web/网页.mq.md - db: ../db/index.mq.md - feed: feed.mq.md ---- - -## 帖子十 - + `board_id`="0" - -**store = > db.打开** -**行 = > store.查询 表="posts" 上限=10 排序="-created_at"** -*> feed.帖子列表HTML 行=`行`* - -## 新闻五 - + `news_board_id`="0" - -**store = > db.打开** -**行 = > store.查询 表="news" 上限=5 排序="-created_at"** -*> feed.新闻时间线HTML 行=`行`* diff --git a/examples/anlian-mq/components/hero.mq.md b/examples/anlian-mq/components/hero.mq.md deleted file mode 100644 index 1c21f38..0000000 --- a/examples/anlian-mq/components/hero.mq.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -markup: occlusion ---- - -## 首页引言 - -英雄区 HTML(品牌标语 + CTA + 漂浮主图)。样式在 `styles/shell` 的 Hero / 动效表。 - -**"

    \"\"暗恋见君

    期待人们能够继续相信爱情

    粉玻璃、呼吸 Logo、漂浮主图——用 Marqdo 表格装配的社区站点,验收「代码即文档」能否撑起真实前端。

    浏览帖子新闻公聊

    \"暗恋见君\"

    最新帖子

    来自粉玻璃卡片流

    "** diff --git a/examples/anlian-mq/components/home_body.mq.md b/examples/anlian-mq/components/home_body.mq.md deleted file mode 100644 index 6c5090d..0000000 --- a/examples/anlian-mq/components/home_body.mq.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -markup: occlusion -title: components/home_body -description: 首页主体 HTML — hero + 公告 + 新闻时间线 + 论坛帖子(对齐 Django home.html,无外层导航)。 -导入: - 网页: ext/web/网页.mq.md - table: lib/table.mq.md - text: lib/text.mq.md - feed: feed.mq.md ---- - -## 装配 - + `库` - -查询 notices / boards / news_boards / news(5) / posts(10),拼装首页四段 HTML(不含导航与页脚)。调用方传入已打开的 store。 - -**公告行 = > 库.查询 表="notices" 上限=20 排序="-created_at"** -**板块行 = > 库.查询 表="boards" 上限=50** -**新闻板块行 = > 库.查询 表="news_boards" 上限=50** -**新闻行 = > 库.查询 表="news" 上限=5 排序="-created_at"** -**帖子行 = > 库.查询 表="posts" 上限=10 排序="-created_at"** - -**公告段 = None** -- [告](遍历 公告行 为 告) - **文 = [content](access(告, "content"))** - **时 = [created_at](access(告, "created_at"))** - **一项 = "
    " + 文 + "

    " + 时 + "

    "** - **公告段 = > table.append list=公告段 item=一项** -1. 公告段 - **公告内 = > text.str_join xs=公告段 sep=""** -2. * - **公告内 = "

    暂无公告

    "** - -**新闻栏 = > feed.板块栏HTML 板块=新闻板块行 前缀="/news/five" 查询键="news_board_id" 全部类="home-posts-tab js-home-news-tab"** -**新闻板 = > feed.新闻时间线HTML 行=新闻行** -**帖子栏 = > feed.板块栏HTML 板块=板块行 前缀="/post/ten" 查询键="board_id" 全部类="home-posts-tab js-home-post-tab"** -**帖子表 = > feed.帖子列表HTML 行=帖子行** - -**段 = None** -**英雄 = "
    \"logo\"暗恋见君

    期待人们能够继续相信爱情

    粉玻璃社区 · 匿名与实名同在

    \"首页展示图\"
    "** -**段 = > table.append list=段 item=英雄** -**公告区 = "

    公告信息

    " + 公告内 + "
    "** -**段 = > table.append list=段 item=公告区** -**新闻区 = "

    新闻动态

    " + 新闻栏 + "
    " + 新闻板 + "
    "** -**段 = > table.append list=段 item=新闻区** -**更多 = "查看更多帖子"** -**帖子区 = "

    论坛交流

    " + 帖子栏 + "
    " + 帖子表 + 更多 + "
    "** -**段 = > table.append list=段 item=帖子区** -*> text.str_join xs=段 sep=""* diff --git a/examples/anlian-mq/components/nav.mq.md b/examples/anlian-mq/components/nav.mq.md deleted file mode 100644 index bc5c50c..0000000 --- a/examples/anlian-mq/components/nav.mq.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -markup: occlusion ---- - -## 导航 - -顶栏:首页、帖子、新闻、搜索、聊天、发帖(登录后)、后台。 - -`导航` = - -| 属性 | 值 | 样式 | 媒体 | 当 | -|------|-----|------|------|-----| -| 暗恋见君 | / | | | | -| 帖子 | /posts | | | | -| 新闻 | /news | | | | -| 搜索 | /search | | | | -| 聊天 | /chat | | | | -| 发帖 | /write | | | auth | -| 登录 | /admin/login | | | guest | -| 后台 | /admin | | | auth | - -*`导航`* diff --git a/examples/anlian-mq/components/page.mq.md b/examples/anlian-mq/components/page.mq.md deleted file mode 100644 index aed9915..0000000 --- a/examples/anlian-mq/components/page.mq.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -markup: occlusion -title: components/page -description: 用原站 chrome 包一层完整 HTML 引言(bare 布局)。 -import: - text: lib/text.mq.md - chrome: chrome.mq.md ---- - -## 包装 - + `正文` - + `体类`="" - -导航 + 正文 + 页脚;体类如 `page-home`。 - -**顶 = > chrome.导航HTML** -**底 = > chrome.页脚HTML** -**鉴权脚本 = ""** -**鉴权样式 = ""** -*鉴权样式 + 顶 + "
    " + 正文 + "
    " + 底 + 鉴权脚本* diff --git a/examples/anlian-mq/db/index.mq.md b/examples/anlian-mq/db/index.mq.md deleted file mode 100644 index ae4b665..0000000 --- a/examples/anlian-mq/db/index.mq.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -markup: occlusion -title: db/index -description: 打开库、建全表、幂等种子、帖子全文索引。 -导入: - 网页: ext/web/网页.mq.md - schema: schema.mq.md - seed: seed.mq.md ---- - -## 打开 - -打开 sqlite:data/anlian-mq.db,初始化全部表;帖子建 FTS;若 posts 为空则写入种子。返回 store。 - -**store = > 网页.数据库 地址="sqlite:data/anlian-mq.db"** -**帖子字段 = > schema.posts** -**新闻字段 = > schema.news** -**板块字段 = > schema.boards** -**新闻板块字段 = > schema.news_boards** -**公告字段 = > schema.notices** -**评论字段 = > schema.comments** -**房间字段 = > schema.chat_rooms** -**专题字段 = > schema.topics** -**密钥字段 = > schema.api_keys** -> `store`.初始化 名=posts 字段=`帖子字段` -> `store`.初始化 名=news 字段=`新闻字段` -> `store`.初始化 名=boards 字段=`板块字段` -> `store`.初始化 名=news_boards 字段=`新闻板块字段` -> `store`.初始化 名=notices 字段=`公告字段` -> `store`.初始化 名=comments 字段=`评论字段` -> `store`.初始化 名=chat_rooms 字段=`房间字段` -> `store`.初始化 名=topics 字段=`专题字段` -> `store`.初始化 名=api_keys 字段=`密钥字段` - -`全文列` = - -| 列 | -|----| -| title | -| summary | -| body | - -> `store`.全文 表=posts 列=`全文列` 名=posts_fts - -**已有 = > store.查询 表="posts" 上限=1** -1. `已有` - *store* -2. * - **板块 = > seed.boards** - **新闻板块 = > seed.news_boards** - **帖子 = > seed.posts** - **新闻 = > seed.news** - **公告 = > seed.notices** - **评论 = > seed.comments** - **房间 = > seed.chat_rooms** - **专题 = > seed.topics** - > `store`.插入 表=boards 行=`板块` - > `store`.插入 表=news_boards 行=`新闻板块` - > `store`.插入 表=posts 行=`帖子` - > `store`.插入 表=news 行=`新闻` - > `store`.插入 表=notices 行=`公告` - > `store`.插入 表=comments 行=`评论` - > `store`.插入 表=chat_rooms 行=`房间` - > `store`.插入 表=topics 行=`专题` - *store* diff --git a/examples/anlian-mq/db/schema.mq.md b/examples/anlian-mq/db/schema.mq.md deleted file mode 100644 index b4b6f5b..0000000 --- a/examples/anlian-mq/db/schema.mq.md +++ /dev/null @@ -1,150 +0,0 @@ ---- -markup: occlusion ---- - -## posts - -帖子主表。`slug` 用于详情路径;`board` 为板块显示名,`board_id` 关联 `boards`。 - -`posts` = - -| 字段 | 类型 | 可空 | 索引 | -|------|------|------|------| -| id | integer | false | | -| title | text | false | | -| slug | text | false | 是 | -| summary | text | true | | -| body | text | true | | -| board | text | true | | -| board_id | integer | true | | -| author | text | true | | -| comments_count | integer | true | | -| views | integer | true | | -| created_at | timestamp | true | | -| updated_at | timestamp | true | | - -*`posts`* - -## news - -新闻主表。`board_id` 关联 `news_boards`;`board` 为板块显示名。 - -`news` = - -| 字段 | 类型 | 可空 | 索引 | -|------|------|------|------| -| id | integer | false | | -| title | text | false | | -| slug | text | false | 是 | -| summary | text | true | | -| body | text | true | | -| board | text | true | | -| board_id | integer | true | | -| created_at | timestamp | true | | -| updated_at | timestamp | true | | - -*`news`* - -## boards - -帖子板块。 - -`boards` = - -| 字段 | 类型 | 可空 | 索引 | -|------|------|------|------| -| id | integer | false | | -| name | text | false | | -| slug | text | false | 是 | - -*`boards`* - -## news_boards - -新闻板块。 - -`news_boards` = - -| 字段 | 类型 | 可空 | 索引 | -|------|------|------|------| -| id | integer | false | | -| name | text | false | | -| slug | text | false | 是 | - -*`news_boards`* - -## notices - -首页公告。 - -`notices` = - -| 字段 | 类型 | 可空 | -|------|------|------| -| id | integer | false | -| content | text | false | -| created_at | timestamp | true | - -*`notices`* - -## comments - -评论(按目标类型 + slug 挂接)。 - -`comments` = - -| 字段 | 类型 | 可空 | -|------|------|------| -| id | integer | false | -| target_type | text | false | -| target_slug | text | false | -| body | text | false | -| author | text | true | -| created_at | timestamp | true | - -*`comments`* - -## chat_rooms - -公聊房间。 - -`chat_rooms` = - -| 字段 | 类型 | 可空 | 索引 | -|------|------|------|------| -| id | integer | false | | -| slug | text | false | 是 | -| name | text | false | | -| summary | text | true | | - -*`chat_rooms`* - -## topics - -专题占位。 - -`topics` = - -| 字段 | 类型 | 可空 | 索引 | -|------|------|------|------| -| id | integer | false | | -| slug | text | false | 是 | -| title | text | false | | -| summary | text | true | | - -*`topics`* - -## api_keys - -API Key 校验用哈希表(应用层 scopes)。 - -`api_keys` = - -| 字段 | 类型 | 可空 | -|------|------|------| -| id | integer | false | -| name | text | false | -| hash | text | false | -| scopes | text | true | - -*`api_keys`* diff --git a/examples/anlian-mq/db/seed.mq.md b/examples/anlian-mq/db/seed.mq.md deleted file mode 100644 index af9ad39..0000000 --- a/examples/anlian-mq/db/seed.mq.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -markup: occlusion ---- - -## boards - -帖子板块:日常 / 开发 / 聊天。 - -`boards` = - -| @ | name | slug | -|---|------|------| -| 1 | 日常 | daily | -| 2 | 开发 | develop | -| 3 | 聊天 | chat | - -*`boards`* - -## news_boards - -新闻板块:站务 / 技术。 - -`news_boards` = - -| @ | name | slug | -|---|------|------| -| 1 | 站务 | site | -| 2 | 技术 | tech | - -*`news_boards`* - -## posts - -种子帖子(标题/短链与原 anlian-mq 一致)。 - -`posts` = - -| @ | title | slug | summary | body | board | board_id | author | comments_count | views | -|---|-------|------|---------|------|-------|----------|--------|----------------|-------| -| 1 | 欢迎来到暗恋见君 | welcome | 期待人们能够继续相信爱情。 | 这是用 Marqdo 重写的验收站点。页面、库表与门禁都用 GFM 表格装配——代码即文档。 | 日常 | 1 | 站务 | 2 | 42 | -| 2 | 如何用表格写论坛 | tables-for-forums | 导航、表单、种子数据都是可读表格。 | 若某功能逼你写一长串 json.set,请先审视 ext/web 是否缺命名方法。 | 开发 | 2 | 站务 | 0 | 18 | -| 3 | 公聊室已开放 | chat-open | WebSocket 广播房间。 | 打开 /chat,连上 /chat/ws,消息会扇出给同房间所有人。 | 聊天 | 3 | 站务 | 0 | 9 | - -*`posts`* - -## news - -种子新闻。 - -`news` = - -| @ | title | slug | summary | body | board | board_id | -|---|-------|------|---------|------|-------|----------| -| 1 | 站点迁往 Marqdo | migrate-to-marqdo | 原生层换 Go libweb,作者面保持表格。 | 暗恋见君的验收目标:登录、发帖、列表详情、聊天与站长工具都能用 .mq.md 写完。 | 站务 | 1 | -| 2 | 外接 PostgreSQL / Redis | pg-redis | 生产可用外接驱动。 | 本示例默认 sqlite:;把数据库地址换成 postgres:// 即可。 | 技术 | 2 | - -*`news`* - -## notices - -首页公告(2–3 条)。 - -`notices` = - -| @ | content | created_at | -|---|---------|------------| -| 1 | 欢迎来到暗恋见君论坛。本站支持匿名与实名交流,请友善发言。 | 2026-09-01 10:00:00 | -| 2 | 站点正用 Marqdo 表格重写验收:导航、首页四段、列表与公聊对齐原站 DOM。 | 2026-09-08 14:30:00 | -| 3 | 发帖与评论请遵守社区规范;站务公告将在此置顶。 | 2026-09-10 09:00:00 | - -*`notices`* - -## comments - -欢迎帖下的评论。 - -`comments` = - -| @ | target_type | target_slug | body | author | created_at | -|---|-------------|-------------|------|--------|------------| -| 1 | post | welcome | 终于等到用表格写论坛的一天。 | 路人甲 | 2026-09-10 11:00:00 | -| 2 | post | welcome | 期待人们能够继续相信爱情。 | 见君 | 2026-09-10 12:15:00 | - -*`comments`* - -## chat_rooms - -公聊:大厅 + 闲聊。 - -`chat_rooms` = - -| @ | slug | name | summary | -|---|------|------|---------| -| 1 | lobby | 大厅 | 全站公共聊天室。 | -| 2 | casual | 闲聊 | 轻松闲聊,勿刷屏。 | - -*`chat_rooms`* - -## topics - -专题占位条目。 - -`topics` = - -| @ | slug | title | summary | -|---|------|-------|---------| -| 1 | glass-ui | 粉玻璃界面 | 首页与列表的毛玻璃视觉专题(占位)。 | -| 2 | tables-as-code | 表格即代码 | Marqdo GFM 表装配专题(占位)。 | - -*`topics`* diff --git a/examples/anlian-mq/index.mq.md b/examples/anlian-mq/index.mq.md deleted file mode 100644 index df66b49..0000000 --- a/examples/anlian-mq/index.mq.md +++ /dev/null @@ -1,212 +0,0 @@ ---- -markup: occlusion -title: 暗恋见君 · Marqdo -description: 对齐 Django 暗恋见君:原站 CSS/DOM、首页四段、列表详情、发帖门禁、聊天室、专题、搜索、API 指南。 -导入: - 网页: ext/web/网页.mq.md - table: lib/table.mq.md - text: lib/text.mq.md - chrome: components/chrome.mq.md - page: components/page.mq.md - home: components/home_body.mq.md - feed: components/feed.mq.md - fragments: components/fragments.mq.md - db: db/index.mq.md ---- - -# main - -路径对齐原站:`/post`、`/news`、`/post/public`、`/chat`、`/topics`、`/search`、`/accounts/login`。 - -`用户表` = - -| 行 | 用户名 | 密码 | 角色 | -|----|--------|------|------| -| 1 | admin | anlian | admin | - -`发帖字段` = - -| 字段 | 标签 | 类型 | 必填 | -|------|------|------|------| -| title | 标题 | text | true | -| slug | 短链 | text | true | -| summary | 摘要 | text | false | -| body | 正文 | textarea | true | -| board | 板块 | text | false | -| board_id | 板块ID | number | false | -| author | 署名 | text | false | - -`发帖规则` = - -| 字段 | 规则 | 消息 | -|------|------|------| -| title | required | 标题不能为空 | -| slug | required | 需要短链 | -| body | required | 正文不能为空 | - -`帖子详情` = - -| 属性 | 值 | 样式 | -|------|-----|------| -| title | posts.title | | -| meta | posts.author | | -| body | posts.body | | - -`新闻详情` = - -| 属性 | 值 | 样式 | -|------|-----|------| -| title | news.title | | -| body | news.body | | - -`帖子条件` = - -| 字段 | 操作 | 值 | -|------|------|-----| -| slug | = | {slug} | - -`新闻条件` = - -| 字段 | 操作 | 值 | -|------|------|-----| -| slug | = | {slug} | - -`地图项` = - -| loc | 更新 | -|-----|------| -| / | 2026-09-10 | -| /post | 2026-09-10 | -| /news | 2026-09-10 | -| /chat | 2026-09-10 | -| /topics | 2026-09-10 | -| /search | 2026-09-10 | -| /guide/automation-api | 2026-09-10 | - -`图标` = - -| 路径 | 关系 | 类型 | 尺寸 | 地址 | -|------|------|------|------|------| -| "public/img/favicon-32.png" | icon | "image/png" | 32x32 | "/favicon.ico" | - -**store = > db.打开** -**头 = > chrome.头资源** -**顶 = > chrome.导航HTML** -**底 = > chrome.页脚HTML** -**鉴权补丁 = ""** - -**主页体 = > home.装配 库=`store`** -**主页文 = > page.包装 正文=`主页体` 体类="page-home"** -**首页 = > 网页.页面 标题="暗恋见君论坛" 引言=`主页文` 壳样式="off" 布局="bare"** -**首页 = > 首页.头装配 表=`头`** - -**板块行 = > store.查询 表="boards" 上限=50** -**帖子行 = > store.查询 表="posts" 上限=50 排序="-created_at"** -**帖子栏 = > feed.板块栏HTML 板块=板块行 前缀="/post" 查询键="board_id" 全部类="feed-tab"** -**帖子表 = > feed.帖子列表HTML 行=帖子行** -**帖子列表体 = "

    论坛交流

    " + 帖子栏 + 帖子表 + "

    发布帖子

    "** -**帖子列表文 = > page.包装 正文=`帖子列表体` 体类="page-post-list"** -**帖子列表 = > 网页.页面 标题="帖子 · 暗恋见君" 引言=`帖子列表文` 壳样式="off" 布局="bare"** -**帖子列表 = > 帖子列表.头装配 表=`头`** - -**新闻板块行 = > store.查询 表="news_boards" 上限=50** -**新闻行 = > store.查询 表="news" 上限=50 排序="-created_at"** -**新闻栏 = > feed.板块栏HTML 板块=新闻板块行 前缀="/news" 查询键="news_board_id" 全部类="feed-tab"** -**新闻表 = > feed.新闻时间线HTML 行=新闻行** -**新闻列表体 = "

    新闻动态

    " + 新闻栏 + 新闻表 + "
    "** -**新闻列表文 = > page.包装 正文=`新闻列表体` 体类="page-news-list"** -**新闻列表 = > 网页.页面 标题="新闻 · 暗恋见君" 引言=`新闻列表文` 壳样式="off" 布局="bare"** -**新闻列表 = > 新闻列表.头装配 表=`头`** - -**帖子页 = > 网页.页面 标题="帖子详情" 引言=`鉴权补丁` 壳样式="off" 布局="stacked"** -**帖子页 = > 帖子页.头装配 表=`头`** -**帖子页 = > 帖子页.壳HTML 导航=`顶` 页脚=`底` 体类="page-post-detail"** -**帖子页 = > 帖子页.主体装配 主体=`帖子详情`** -**帖子页 = > 帖子页.查询条件 条件=`帖子条件`** -**帖子页 = > 帖子页.详情 详情=True** - -**新闻页 = > 网页.页面 标题="新闻详情" 引言=`鉴权补丁` 壳样式="off" 布局="stacked"** -**新闻页 = > 新闻页.头装配 表=`头`** -**新闻页 = > 新闻页.壳HTML 导航=`顶` 页脚=`底` 体类="page-news-detail"** -**新闻页 = > 新闻页.主体装配 主体=`新闻详情`** -**新闻页 = > 新闻页.查询条件 条件=`新闻条件`** -**新闻页 = > 新闻页.详情 详情=True** - -**发帖表 = > 网页.表单 表="posts" 动作="插入"** -**发帖表 = > 发帖表.字段 字段=`发帖字段`** -**发帖表 = > 发帖表.规则 规则=`发帖规则`** -**发帖引言 = > page.包装 正文="

    发布帖子

    需登录(admin / anlian)

    " 体类="page-post-public"** -**发帖页 = > 网页.页面 标题="发帖 · 暗恋见君" 引言=`发帖引言` 壳样式="off" 布局="bare"** -**发帖页 = > 发帖页.头装配 表=`头`** -**发帖页 = > 发帖页.表单装配 id="post" 表单=`发帖表`** - -**房间行 = > store.查询 表="chat_rooms" 上限=50** -**房间段 = None** -- [房](遍历 房间行 为 房) - **名 = [name](access(房, "name"))** - **链 = [slug](access(房, "slug"))** - **摘 = [summary](access(房, "summary"))** - **项 = ""** - **房间段 = > table.append list=房间段 item=项** -**房间内 = > text.str_join xs=房间段 sep=""** -**聊天列表体 = "

    聊天室

    " + 房间内 + "
    "** -**聊天列表文 = > page.包装 正文=`聊天列表体` 体类="page-chat"** -**聊天列表 = > 网页.页面 标题="聊天 · 暗恋见君" 引言=`聊天列表文` 壳样式="off" 布局="bare"** -**聊天列表 = > 聊天列表.头装配 表=`头`** - -**大厅体 = "

    大厅

    "** -**大厅文 = > page.包装 正文=`大厅体` 体类="page-chat-room"** -**大厅页 = > 网页.页面 标题="大厅 · 暗恋见君" 引言=`大厅文` 壳样式="off" 布局="bare"** -**大厅页 = > 大厅页.头装配 表=`头`** - -**闲聊体 = "

    闲聊

    "** -**闲聊文 = > page.包装 正文=`闲聊体` 体类="page-chat-room"** -**闲聊页 = > 网页.页面 标题="闲聊 · 暗恋见君" 引言=`闲聊文` 壳样式="off" 布局="bare"** -**闲聊页 = > 闲聊页.头装配 表=`头`** - -**专题行 = > store.查询 表="topics" 上限=50** -**专题段 = None** -- [题](遍历 专题行 为 题) - **题名 = [title](access(题, "title"))** - **链 = [slug](access(题, "slug"))** - **摘 = [summary](access(题, "summary"))** - **项 = "

    " + 题名 + "

    " + 摘 + "

    slug: " + 链 + "

    "** - **专题段 = > table.append list=专题段 item=项** -**专题内 = > text.str_join xs=专题段 sep=""** -**专题体 = "

    专题书架

    " + 专题内 + "
    "** -**专题文 = > page.包装 正文=`专题体` 体类="page-topics"** -**专题页 = > 网页.页面 标题="专题 · 暗恋见君" 引言=`专题文` 壳样式="off" 布局="bare"** -**专题页 = > 专题页.头装配 表=`头`** - -**搜索体 = "

    搜索

    全文检索走 SQLite FTS(posts_fts);结果面板后续可按 q 扩展。

    "** -**搜索文 = > page.包装 正文=`搜索体` 体类="page-search"** -**搜索页 = > 网页.页面 标题="搜索 · 暗恋见君" 引言=`搜索文` 壳样式="off" 布局="bare"** -**搜索页 = > 搜索页.头装配 表=`头`** - -**指南体 = "

    API 自动化指南

    使用 Bearer / X-Api-Key 调用自动化接口。本验收切片提供 api_keys 表与 web_api_key_check 原语;业务 scopes 写在 .mq.md。

    Authorization: Bearer <token>
    "** -**指南文 = > page.包装 正文=`指南体` 体类="page-guide"** -**指南页 = > 网页.页面 标题="API 指南 · 暗恋见君" 引言=`指南文` 壳样式="off" 布局="bare"** -**指南页 = > 指南页.头装配 表=`头`** - -**应用 = > 网页.应用 页面=`首页` 数据库=`store` 后台=True 主机="127.0.0.1" 端口=18180** -**应用 = > 应用.路由 路径="/post" 页面=`帖子列表`** -**应用 = > 应用.路由 路径="/post/public" 页面=`发帖页`** -**应用 = > 应用.路由 路径="/post/{slug}" 页面=`帖子页`** -**应用 = > 应用.路由 路径="/news" 页面=`新闻列表`** -**应用 = > 应用.路由 路径="/news/{slug}" 页面=`新闻页`** -**应用 = > 应用.路由 路径="/chat" 页面=`聊天列表`** -**应用 = > 应用.路由 路径="/chat/lobby" 页面=`大厅页`** -**应用 = > 应用.路由 路径="/chat/casual" 页面=`闲聊页`** -**应用 = > 应用.路由 路径="/topics" 页面=`专题页`** -**应用 = > 应用.路由 路径="/search" 页面=`搜索页`** -**应用 = > 应用.路由 路径="/guide/automation-api" 页面=`指南页`** -**应用 = > 应用.静态 目录="public" 挂载="/static"** -**应用 = > 应用.图标 表=`图标`** -**应用 = > 应用.鉴权 用户表=`用户表` 会话时长=7200 登录路径="/accounts/login" 登录回跳="/post/public" 登出回跳="/"** -**应用 = > 应用.门禁 路径="/post/public" 角色="admin" 匹配="prefix" 拒绝="redirect" 排除="/accounts/login"** -**应用 = > 应用.路由实时 路径="/chat/ws" 模式="broadcast"** -**应用 = > 应用.调用 路径="/post/ten" 方法="GET" 函数="fragments.帖子十" 正文="query" 返回="html"** -**应用 = > 应用.调用 路径="/news/five" 方法="GET" 函数="fragments.新闻五" 正文="query" 返回="html"** -**应用 = > 应用.站点地图 路径="/sitemap.xml" 基址="http://127.0.0.1:18180" 条目=`地图项`** -**应用 = > 应用.爬虫协议 站点地图="http://127.0.0.1:18180/sitemap.xml"** -> `应用`.监听 diff --git a/examples/anlian-mq/offline-smoke.mq.md b/examples/anlian-mq/offline-smoke.mq.md deleted file mode 100644 index 220de64..0000000 --- a/examples/anlian-mq/offline-smoke.mq.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -markup: occlusion -title: anlian-mq offline smoke -description: 不 listen:装配库表/页面/门禁/WS 路由袋,验证可读路径可构造。 -导入: - 网页: ext/web/网页.mq.md - shell: styles/shell.mq.md - nav: components/nav.mq.md - foot: components/foot.mq.md - db: db/index.mq.md - sys: lib/sys.mq.md ---- - -# main - -`壳` = - -| 组件 | 样式 | -|------|------| -| nav.`导航` | | -| foot.`页脚` | | - -`帖子卡片` = - -| 属性 | 值 | -|------|-----| -| title | posts.title | -| body | posts.summary | -| href | posts.slug | - -`用户表` = - -| 行 | 用户名 | 密码 | 角色 | -|----|--------|------|------| -| 1 | admin | anlian | admin | - -**store = > db.打开** -**壳CSS = > shell.全局** -**首页 = > 网页.页面 标题="暗恋见君" 引言="

    ok

    "** -**首页 = > 首页.组件装配 组件=`壳`** -**首页 = > 首页.主体装配 主体=`帖子卡片`** -**首页 = > 首页.样式 样式=`壳CSS`** - -**应用 = > 网页.应用 页面=`首页` 数据库=`store` 后台=True 主机="127.0.0.1" 端口=18180** -**应用 = > 应用.鉴权 用户表=`用户表`** -**应用 = > 应用.门禁 路径="/write" 角色="admin" 匹配="prefix" 拒绝="redirect"** -**应用 = > 应用.路由实时 路径="/chat/ws" 模式="broadcast"** - -**gates = [gates](access(应用, "gates"))** -**n = > len value=`gates`** -1. `n` >= 2 - > print text=gates-ok -2. * - > print text=gates-fail - > sys.exit code=1 - -**ws = [ws_routes](access(应用, "ws_routes"))** -**room = [/chat/ws](access(ws, "/chat/ws"))** -**mode = [mode](access(room, "mode"))** -1. `mode` == "broadcast" - > print text=ws-ok -2. * - > print text=ws-fail - > sys.exit code=1 - -**list = > store.查询 表="posts" 上限=10** -**nr = > len value=`list`** -1. `nr` >= 1 - > print text=seed-ok -2. * - > print text=seed-fail - > sys.exit code=1 - -> print text=anlian-offline-ok diff --git a/examples/anlian-mq/public/bg-body-960.webp b/examples/anlian-mq/public/bg-body-960.webp deleted file mode 100644 index b3c6603..0000000 Binary files a/examples/anlian-mq/public/bg-body-960.webp and /dev/null differ diff --git a/examples/anlian-mq/public/bg-hero-640.webp b/examples/anlian-mq/public/bg-hero-640.webp deleted file mode 100644 index 491e199..0000000 Binary files a/examples/anlian-mq/public/bg-hero-640.webp and /dev/null differ diff --git a/examples/anlian-mq/public/chat.js b/examples/anlian-mq/public/chat.js deleted file mode 100644 index 2386f47..0000000 --- a/examples/anlian-mq/public/chat.js +++ /dev/null @@ -1,37 +0,0 @@ -/* 公聊客户端:保持极薄;业务配置仍在 .mq.md 表格里。 */ -(function () { - var log = document.getElementById("chat-log"); - var input = document.getElementById("chat-msg"); - var send = document.getElementById("chat-send"); - if (!log || !input || !send) return; - - var proto = location.protocol === "https:" ? "wss:" : "ws:"; - var ws = new WebSocket(proto + "//" + location.host + "/chat/ws"); - - function line(text) { - log.textContent += text + "\n"; - log.scrollTop = log.scrollHeight; - } - - ws.onopen = function () { - line("[已连接公聊室]"); - }; - ws.onclose = function () { - line("[连接关闭]"); - }; - ws.onmessage = function (ev) { - line(String(ev.data)); - }; - - function publish() { - var t = (input.value || "").trim(); - if (!t || ws.readyState !== 1) return; - ws.send(t); - input.value = ""; - } - - send.addEventListener("click", publish); - input.addEventListener("keydown", function (e) { - if (e.key === "Enter") publish(); - }); -})(); diff --git a/examples/anlian-mq/public/css/anlian_forms.css b/examples/anlian-mq/public/css/anlian_forms.css deleted file mode 100644 index 47dd2b4..0000000 --- a/examples/anlian-mq/public/css/anlian_forms.css +++ /dev/null @@ -1,454 +0,0 @@ -/** - * 暗恋见君 — 登录/注册/发帖/评论 共用表单样式(粉色毛玻璃主题) - */ - -:root { - --anlian-accent: #fdbbdb; - --anlian-accent-deep: #f0a8c4; - --anlian-accent-text: #a85878; - --anlian-accent-muted: #c97a96; - --anlian-glass-bg: rgba(255, 255, 255, 0.38); - --anlian-glass-border: rgba(255, 255, 255, 0.52); - --anlian-text: #222; - --anlian-text-muted: #666; - --anlian-radius: 14px; - --anlian-radius-pill: 999px; - --anlian-transition: 0.2s ease; -} - -/* ---------- 页面布局 ---------- */ -.anlian-page { - display: flex; - flex-direction: column; - align-items: center; - width: 100%; - max-width: 520px; - margin: 0 auto; - padding: 1.5rem 1rem 2.5rem; - box-sizing: border-box; -} - -.anlian-page-wide { - max-width: 800px; -} - -.anlian-page-title { - margin: 0 0 1.25rem; - font-size: 1.75rem; - font-weight: 700; - color: var(--anlian-text); - text-align: center; -} - -.anlian-page-lead { - margin: -0.5rem 0 1.25rem; - font-size: 0.9rem; - color: var(--anlian-text-muted); - text-align: center; - line-height: 1.5; -} - -/* ---------- 表单卡片 ---------- */ -.anlian-form-card { - width: 100%; - padding: 2rem 1.75rem; - border-radius: 24px; - background: var(--anlian-glass-bg); - backdrop-filter: blur(18px); - -webkit-backdrop-filter: blur(18px); - border: 1px solid var(--anlian-glass-border); - box-shadow: 0 12px 40px rgba(253, 189, 219, 0.15); - box-sizing: border-box; -} - -.anlian-form-card .form-group, -.anlian-form-card .anlian-field { - margin-bottom: 1.25rem; -} - -.anlian-form-card .anlian-field:last-child, -.anlian-form-card .form-group:last-of-type { - margin-bottom: 0; -} - -/* ---------- 标签与输入框 ---------- */ -.anlian-field-label, -.anlian-form-card label:not(.anlian-pill-label):not(.anlian-switch) { - display: block; - margin-bottom: 0.45rem; - font-size: 0.875rem; - font-weight: 600; - color: var(--anlian-accent-text); -} - -.anlian-form-card input[type="text"], -.anlian-form-card input[type="email"], -.anlian-form-card input[type="password"], -.anlian-form-card input[type="search"], -.anlian-form-card input[type="number"], -.anlian-form-card input.anlian-input, -.anlian-form-card .form-control, -.anlian-form-card textarea, -.anlian-form-card select { - display: block; - width: 100%; - box-sizing: border-box; - padding: 0.7rem 0.95rem; - font-size: 1rem; - line-height: 1.4; - color: var(--anlian-text); - background: rgba(255, 255, 255, 0.55); - border: 1px solid rgba(253, 189, 219, 0.35); - border-radius: 12px; - transition: border-color var(--anlian-transition), box-shadow var(--anlian-transition), - background var(--anlian-transition); -} - -.anlian-form-card input::placeholder, -.anlian-form-card textarea::placeholder { - color: #999; -} - -.anlian-form-card input:focus, -.anlian-form-card textarea:focus, -.anlian-form-card select:focus { - outline: none; - border-color: var(--anlian-accent-deep); - background: rgba(255, 255, 255, 0.72); - box-shadow: 0 0 0 3px rgba(253, 189, 219, 0.28); -} - -.anlian-form-card select { - cursor: pointer; - appearance: none; - background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'%3E%3Cpath fill='%23a85878' d='M6 8 0 0h12z'/%3E%3C/svg%3E"); - background-repeat: no-repeat; - background-position: right 0.95rem center; - padding-right: 2.25rem; -} - -.anlian-form-card textarea { - min-height: 100px; - resize: vertical; -} - -/* ---------- 记住我(自定义勾选,替代原生 checkbox) ---------- */ -.anlian-field-remember { - margin-bottom: 1.25rem; -} - -.anlian-switch { - display: inline-flex; - align-items: center; - gap: 0.65rem; - cursor: pointer; - user-select: none; -} - -.anlian-switch-input { - position: absolute; - width: 1px; - height: 1px; - padding: 0; - margin: -1px; - overflow: hidden; - clip: rect(0, 0, 0, 0); - white-space: nowrap; - border: 0; -} - -.anlian-switch-box { - position: relative; - flex-shrink: 0; - width: 1.35rem; - height: 1.35rem; - border-radius: 8px; - background: rgba(255, 255, 255, 0.5); - border: 1px solid rgba(253, 189, 219, 0.5); - box-shadow: inset 0 1px 2px rgba(255, 255, 255, 0.4); - transition: background var(--anlian-transition), border-color var(--anlian-transition), - box-shadow var(--anlian-transition); -} - -.anlian-switch-box::after { - content: ''; - position: absolute; - left: 50%; - top: 45%; - width: 0.3rem; - height: 0.55rem; - margin-left: -0.2rem; - margin-top: -0.38rem; - border: solid #fff; - border-width: 0 2px 2px 0; - transform: rotate(45deg) scale(0); - opacity: 0; - transition: transform 0.15s ease, opacity 0.15s ease; -} - -.anlian-switch-input:checked + .anlian-switch-box { - background: linear-gradient(135deg, rgba(253, 189, 219, 0.85), rgba(240, 168, 196, 0.9)); - border-color: rgba(240, 168, 196, 0.85); - box-shadow: 0 2px 8px rgba(253, 189, 219, 0.35); -} - -.anlian-switch-input:checked + .anlian-switch-box::after { - transform: rotate(45deg) scale(1); - opacity: 1; -} - -.anlian-switch-input:focus-visible + .anlian-switch-box { - outline: none; - box-shadow: 0 0 0 3px rgba(253, 189, 219, 0.35); -} - -.anlian-switch-text { - font-size: 0.875rem; - font-weight: 500; - color: var(--anlian-accent-text); - line-height: 1.3; -} - -.anlian-switch:hover .anlian-switch-box { - border-color: var(--anlian-accent-deep); - background: rgba(255, 255, 255, 0.62); -} - -.anlian-switch:hover .anlian-switch-input:checked + .anlian-switch-box { - background: linear-gradient(135deg, rgba(253, 189, 219, 0.95), rgba(240, 168, 196, 0.95)); -} - -/* ---------- 匿名:分段切换 ---------- */ -.anlian-field-anon { - margin-top: 0.25rem; -} - -.anlian-pill-toggle { - position: relative; -} - -.anlian-pill-input { - position: absolute; - width: 1px; - height: 1px; - padding: 0; - margin: -1px; - overflow: hidden; - clip: rect(0, 0, 0, 0); - white-space: nowrap; - border: 0; -} - -.anlian-pill-label { - position: relative; - display: grid; - grid-template-columns: 1fr 1fr; - align-items: center; - min-height: 2.5rem; - padding: 4px; - border-radius: var(--anlian-radius-pill); - background: rgba(255, 255, 255, 0.32); - border: 1px solid rgba(253, 189, 219, 0.45); - cursor: pointer; - user-select: none; - overflow: hidden; -} - -.anlian-pill-thumb { - position: absolute; - top: 4px; - left: 4px; - width: calc(50% - 4px); - height: calc(100% - 8px); - border-radius: var(--anlian-radius-pill); - background: linear-gradient(135deg, rgba(253, 189, 219, 0.65), rgba(240, 168, 196, 0.75)); - box-shadow: 0 2px 10px rgba(253, 189, 219, 0.25); - transition: transform 0.28s cubic-bezier(0.34, 1.2, 0.64, 1); - pointer-events: none; -} - -.anlian-pill-input:checked + .anlian-pill-label .anlian-pill-thumb { - transform: translateX(100%); -} - -.anlian-pill-option { - position: relative; - z-index: 1; - text-align: center; - font-size: 0.8125rem; - font-weight: 600; - color: var(--anlian-text-muted); - padding: 0.35rem 0.5rem; - transition: color var(--anlian-transition); -} - -.anlian-pill-input:not(:checked) + .anlian-pill-label .anlian-pill-option:first-child, -.anlian-pill-input:checked + .anlian-pill-label .anlian-pill-option:last-child { - color: var(--anlian-accent-text); -} - -.anlian-field-hint { - margin: 0.4rem 0 0; - font-size: 0.75rem; - color: var(--anlian-text-muted); - line-height: 1.4; -} - -/* ---------- 验证码行 ---------- */ -.anlian-code-row { - display: flex; - gap: 0.5rem; - align-items: stretch; -} - -.anlian-code-row input { - flex: 1; - min-width: 0; -} - -.anlian-btn-send-code { - flex-shrink: 0; - align-self: stretch; - padding: 0 1rem; - border: 1px solid rgba(253, 189, 219, 0.5); - border-radius: 12px; - background: rgba(253, 189, 219, 0.32); - color: var(--anlian-accent-text); - font-size: 0.8125rem; - font-weight: 600; - cursor: pointer; - white-space: nowrap; - transition: background var(--anlian-transition), transform var(--anlian-transition); -} - -.anlian-btn-send-code:hover:not(:disabled) { - background: rgba(253, 189, 219, 0.48); -} - -.anlian-btn-send-code:disabled { - opacity: 0.55; - cursor: not-allowed; -} - -/* ---------- 主按钮 ---------- */ -.anlian-btn-primary, -.anlian-form-card .anlian-btn-submit, -.anlian-form-card #login-btn, -.anlian-form-card #submit-btn, -.anlian-form-card #submit-comment-btn { - display: block; - width: 100%; - margin-top: 1.25rem; - padding: 0.75rem 1.25rem; - font-size: 1rem; - font-weight: 600; - color: var(--anlian-accent-text); - background: linear-gradient(135deg, rgba(253, 189, 219, 0.55), rgba(240, 168, 196, 0.65)); - border: 1px solid rgba(240, 168, 196, 0.75); - border-radius: var(--anlian-radius-pill); - cursor: pointer; - transition: transform var(--anlian-transition), box-shadow var(--anlian-transition), - background var(--anlian-transition); - box-shadow: 0 4px 16px rgba(253, 189, 219, 0.22); -} - -.anlian-btn-primary:hover, -.anlian-form-card .anlian-btn-submit:hover, -.anlian-form-card #login-btn:hover, -.anlian-form-card #submit-btn:hover, -.anlian-form-card #submit-comment-btn:hover { - background: linear-gradient(135deg, rgba(253, 189, 219, 0.68), rgba(240, 168, 196, 0.78)); - box-shadow: 0 6px 22px rgba(253, 189, 219, 0.32); - transform: translateY(-1px); -} - -/* ---------- 提示与链接 ---------- */ -.anlian-alert { - padding: 0.85rem 1rem; - margin-bottom: 1rem; - border-radius: 12px; - font-size: 0.875rem; - line-height: 1.45; -} - -.anlian-alert-danger { - background: rgba(220, 80, 100, 0.12); - border: 1px solid rgba(220, 80, 100, 0.28); - color: #9e3a4a; -} - -.anlian-alert p { - margin: 0; -} - -.anlian-field-error { - display: block; - margin-top: 0.35rem; - font-size: 0.8125rem; - color: #b33a4d; -} - -.anlian-form-links { - display: flex; - justify-content: center; - gap: 1rem; - margin-top: 1.25rem; - flex-wrap: wrap; -} - -.anlian-form-links a { - font-size: 0.875rem; - font-weight: 500; - color: var(--anlian-accent-text); - text-decoration: none; -} - -.anlian-form-links a:hover { - text-decoration: underline; -} - -/* ---------- 富文本编辑器 ---------- */ -.anlian-editor-wrap { - border-radius: 12px; - overflow: hidden; - border: 1px solid rgba(253, 189, 219, 0.35); - background: rgba(255, 255, 255, 0.45); -} - -.anlian-editor-wrap #editor { - min-height: 360px; -} - -.anlian-editor-wrap .w-e-toolbar { - background: rgba(255, 255, 255, 0.65) !important; - border-bottom: 1px solid rgba(253, 189, 219, 0.3) !important; -} - -.anlian-editor-wrap .w-e-text-container { - background: rgba(255, 255, 255, 0.35) !important; -} - -/* ---------- 评论表单区块 ---------- */ -.anlian-comment-form.anlian-form-card { - margin-bottom: 2rem; -} - -@media (max-width: 576px) { - .anlian-form-card { - padding: 1.35rem 1.15rem; - border-radius: 18px; - } - - .anlian-page-title { - font-size: 1.5rem; - } - - .anlian-code-row { - flex-direction: column; - } - - .anlian-btn-send-code { - width: 100%; - padding: 0.65rem; - } -} diff --git a/examples/anlian-mq/public/css/api_guide.css b/examples/anlian-mq/public/css/api_guide.css deleted file mode 100644 index d69bfa7..0000000 --- a/examples/anlian-mq/public/css/api_guide.css +++ /dev/null @@ -1,199 +0,0 @@ -/* API 自动化指南页 */ -.api-guide-page { - max-width: 52rem; - align-items: stretch; - text-align: left; - padding-bottom: 3rem; -} - -.api-guide-hero { - margin-bottom: 1.25rem; -} - -.api-guide-hero .api-guide-title { - margin-top: 0; - text-align: left; -} - -.api-guide-hero .anlian-page-lead { - margin-bottom: 0; - text-align: left; - max-width: none; -} - -.api-guide-toc { - margin-bottom: 1.25rem; -} - -.api-guide-toc-title { - margin: 0 0 0.65rem; - font-size: 0.875rem; - font-weight: 700; - color: var(--anlian-text-muted); - text-transform: uppercase; - letter-spacing: 0.04em; -} - -.api-guide-toc ol { - margin: 0; - padding-left: 1.25rem; - line-height: 1.85; -} - -.api-guide-toc a { - color: var(--anlian-accent-text); - text-decoration: none; - font-weight: 500; -} - -.api-guide-toc a:hover { - text-decoration: underline; -} - -.api-guide-section { - margin-bottom: 1.25rem; -} - -.api-guide-section h2 { - margin: 0 0 0.85rem; - font-size: 1.25rem; - font-weight: 700; - color: var(--anlian-text); - border-bottom: 1px solid rgba(253, 189, 219, 0.45); - padding-bottom: 0.4rem; -} - -.api-guide-section h3 { - margin: 1.1rem 0 0.5rem; - font-size: 1rem; - font-weight: 600; - color: var(--anlian-text); -} - -.api-guide-section p, -.api-guide-section li { - font-size: 0.9375rem; - line-height: 1.65; - color: var(--anlian-text); -} - -.api-guide-steps { - margin: 0 0 1rem; - padding-left: 1.35rem; -} - -.api-guide-steps li { - margin-bottom: 0.35rem; -} - -.api-guide-list { - margin: 0; - padding-left: 1.25rem; -} - -.api-guide-list li { - margin-bottom: 0.4rem; -} - -.api-guide-note { - margin: 0.75rem 0 0; - padding: 0.65rem 0.85rem; - font-size: 0.8125rem; - color: var(--anlian-text-muted); - background: rgba(255, 255, 255, 0.35); - border-radius: 10px; - border-left: 3px solid var(--anlian-accent); -} - -.api-guide-warn { - margin: 0.75rem 0 0; - font-size: 0.875rem; - color: #a85858; - font-weight: 500; -} - -.api-guide-code { - margin: 0.5rem 0 1rem; - padding: 0.85rem 1rem; - overflow-x: auto; - font-size: 0.8125rem; - line-height: 1.55; - background: rgba(30, 30, 40, 0.06); - border: 1px solid rgba(0, 0, 0, 0.06); - border-radius: 10px; -} - -.api-guide-code code { - font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; - color: #333; - white-space: pre; -} - -.api-guide-table { - width: 100%; - margin: 0.75rem 0 1rem; - border-collapse: collapse; - font-size: 0.8125rem; -} - -.api-guide-table th, -.api-guide-table td { - padding: 0.5rem 0.65rem; - border: 1px solid rgba(0, 0, 0, 0.08); - text-align: left; - vertical-align: top; -} - -.api-guide-table th { - background: rgba(253, 189, 219, 0.2); - font-weight: 600; -} - -.api-guide-table code { - font-size: 0.75rem; - word-break: break-all; -} - -.api-guide-section a:not(.api-guide-btn) { - color: var(--anlian-accent-text); - font-weight: 500; -} - -.api-guide-btn { - display: inline-block; - margin-top: 0.75rem; - padding: 0.45rem 1rem; - font-size: 0.875rem; - font-weight: 600; - color: #fff !important; - text-decoration: none !important; - background: var(--anlian-accent-text); - border-radius: var(--anlian-radius-pill); -} - -.api-guide-btn:hover { - opacity: 0.9; -} - -.api-guide-back { - margin: 0.5rem 0 0; - text-align: center; - font-size: 0.875rem; -} - -.api-guide-back a { - color: var(--anlian-text-muted); - text-decoration: none; -} - -.api-guide-back a:hover { - color: var(--anlian-accent-text); - text-decoration: underline; -} - -@media (max-width: 575.98px) { - .api-guide-table { - display: block; - overflow-x: auto; - } -} diff --git a/examples/anlian-mq/public/css/base.css b/examples/anlian-mq/public/css/base.css deleted file mode 100644 index 642c6ea..0000000 --- a/examples/anlian-mq/public/css/base.css +++ /dev/null @@ -1,393 +0,0 @@ -/* - * @File: base.css - * @Description: 网站全局基础样式文件,本次更新重点优化了导航栏的布局和美观度。 - * @Author: Your Name - * @Date: 2023-10-27 - * @Update: 2023-10-28 - 优化导航栏颜色方案,并为Logo添加动画效果;新增左右留白容器的响应式样式;修复导航栏与主内容容器重叠问题。 - */ - -/* --- 1. 全局盒模型与颜色变量设置 --- */ -* { - box-sizing: border-box; - padding: 0; - margin: 0; -} - -:root { - --custom-primary: #ffffff; /* 主色调:柔和的蓝色 */ - --custom-primary-rgb: 93, 127, 229; /* 主色调的RGB值,用于透明度 */ - --custom-bg: rgba(255, 255, 255, 0.2); /* 导航栏背景色:半透明白色 */ - --custom-text: #333333; /* 主要文字颜色:深灰色,保证可读性 */ - --custom-link-hover: #fdbbdb; /* 链接悬停颜色:柔和的紫色 */ - --custom-btn-hover-bg: #fdbbdb; /* 按钮悬停背景色:柔和的蓝色 */ - /* 新增:宽屏时左右留白的宽度(可根据需求调整) */ - --side-gap-width: 120px; -} - -/* --- 2. 页面主体样式 --- */ -body { - /* ========== 背景图:960w 优化版,避免全尺寸 1232px 浪费带宽 ========== */ - background-image: url("/static/img/bg-body-960.webp"); - background-repeat: no-repeat; - background-size: cover; - background-position: center center; - background-attachment: fixed; - background-color: #f8f9fa; - - /* ========== 核心修改:重构布局流 ========== */ - /* 从row改为column,让导航栏+内容区垂直排列 */ - display: flex; - flex-direction: column; /* 关键修改1:垂直布局 */ - overflow-x: hidden; - overflow-y: auto; - min-height: 100vh; - margin: 0; - position: relative; - z-index: 1; - width: 100vw; -} - -/* ========== 毛玻璃效果遮罩层(保留) ========== */ -/* body::before { - content: ""; - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; - /* backdrop-filter: blur(1px); */ - /*background-color: rgba(255, 255, 255, 0.2); - z-index: -1; - background-attachment: fixed; -} */ - -/* --- 3. 导航栏 (Navbar) 核心美化 --- */ -.navbar { - background-color: var(--custom-bg) !important; - backdrop-filter: blur(24px); - border: 1px solid rgba(255, 255, 255, 0.2); - box-shadow: inset 0 0 5px rgba(255, 255, 255, 0.1); - padding-top: 0.75rem; - padding-bottom: 0.75rem; - position: relative; - z-index: 1000; - width: 100%; -} - -.navbar-shell { - display: flex; - flex-wrap: wrap; - align-items: center; - width: 100%; - padding-left: 0.5rem; - padding-right: 0.75rem; -} - -.navbar-start { - display: flex; - align-items: center; - flex-shrink: 0; -} - -.navbar .navbar-collapse { - flex-grow: 1; -} - -@media (min-width: 992px) { - .navbar .navbar-collapse { - display: flex !important; - flex-wrap: nowrap; - align-items: center; - justify-content: space-between; - gap: 1rem; - } -} - -.navbar-nav-main { - flex-wrap: wrap; -} - -.navbar-end { - display: flex; - flex-direction: column; - align-items: stretch; - gap: 0.75rem; - width: 100%; -} - -@media (min-width: 992px) { - .navbar-end { - flex-direction: row; - align-items: center; - flex-shrink: 0; - width: auto; - margin-left: auto; - gap: 0.75rem; - } -} - -.navbar-search { - gap: 0.5rem; - align-items: center; -} - -.navbar-search .form-control { - min-width: 120px; - max-width: 180px; -} - -.navbar-auth { - flex-direction: row; - align-items: center; - gap: 0.25rem; - flex-wrap: nowrap; -} - -.navbar-auth .nav-link-auth, -.navbar-auth .nav-link-btn { - padding: 0.35rem 0.85rem !important; - border-radius: 999px; - border: 1px solid rgba(var(--custom-primary-rgb), 0.45); - background: rgba(var(--custom-primary-rgb), 0.12); - font-weight: 600; -} - -.navbar-auth .nav-link-auth:hover, -.navbar-auth .nav-link-btn:hover { - background: rgba(var(--custom-primary-rgb), 0.22); - transform: none; -} - -.navbar-brand { - color: var(--custom-primary) !important; - font-weight: 700; - margin-right: 2rem; -} - -@keyframes pulse { - 0% { transform: scale(1); } - 50% { transform: scale(1.05); } - 100% { transform: scale(1); } -} - -.navbar-logo { - padding-top: 0.3125rem; - padding-bottom: 0.3125rem; - padding-left: 0.75rem; - padding-right: 0.25rem; - animation: pulse 3s ease-in-out infinite; -} - -.navbar-dark .nav-link { - color: var(--custom-text) !important; - margin-left: 0.5rem; - margin-right: 0.5rem; - transition: color 0.2s ease-in-out, transform 0.2s ease-in-out; -} - -.navbar-dark .nav-link:hover { - color: var(--custom-link-hover) !important; - transform: translateY(-2px); -} - -.navbar-search .form-control { - padding-top: 0.5rem; - padding-bottom: 0.5rem; - border-radius: 0.375rem; - outline: none; - transition: box-shadow 0.2s ease-in-out, border-color 0.2s ease-in-out; -} - -.navbar-search .form-control:focus { - border-color: rgba(var(--custom-primary-rgb), 0.5); - box-shadow: 0 0 0 0.2rem rgba(var(--custom-primary-rgb), 0.25); -} - -.navbar-search .btn-outline-success { - color: var(--custom-primary); - border-color: var(--custom-primary); - padding-top: 0.5rem; - padding-bottom: 0.5rem; - white-space: nowrap; - transition: all 0.2s ease-in-out; -} - -.navbar-search .btn-outline-success:hover { - background-color: var(--custom-btn-hover-bg); - border-color: var(--custom-btn-hover-bg); - color: #fff; -} - -@media (max-width: 991.98px) { - .navbar-search { - width: 100%; - } - - .navbar-search .form-control { - flex: 1; - max-width: none; - } - - .navbar-auth { - justify-content: flex-start; - padding-top: 0.25rem; - } -} - -/* --- 6. 主要内容区域样式 --- */ -/* .main-container { - /* 调整:主内容容器在横向flex中占剩余空间 */ - /*flex: 1; - /* 关键修改3:移除多余的padding-top,因为导航栏已回归文档流,无需遮挡补偿 */ - /*padding-bottom: 4rem; - /* 限制主内容最大宽度,保证阅读体验 */ - /*max-width: 1200px;*/ - /* 让主内容在content-wrapper中居中(配合左右留白) */ - /*margin: 0 auto; - /* 左右内边距,适配窄屏 */ - /* padding-left: 1rem; - padding-right: 1rem; - /* 毛玻璃效果(保留) */ - /* background-color: rgba(255, 255, 255, 0.1); - backdrop-filter: blur(0px); - border: 1px solid rgba(255, 255, 255, 0.2); - box-shadow: inset 0 0 5px rgba(255, 255, 255, 0.1); - border-radius: 4px; - padding: 50px 100px; */ - /* 新增:给主内容容器添加顶部外边距,增加与导航栏的间距 */ - /*margin-top: 2rem; */ -/*} */ - -/* --- 7. 左右留白容器样式 (核心需求,适配新布局) --- -.left-container, .right-container { - /* 窄屏时宽度为0,不显示留白 */ - /*width: 0; - /* 不占用空间 */ - /*flex-shrink: 0; - /* 背景色和页面主体一致,视觉上是留白 */ - /*background-color: transparent; -} */ - -/* 宽屏断点(和Bootstrap lg断点一致:992px) */ -/* @media (min-width: 992px) { - /* 宽屏时显示左右留白 */ - /* .left-container, .right-container { - /* 使用自定义变量设置留白宽度,可灵活调整 */ - /*width: var(--side-gap-width); - background-color: transparent; - /* 可选:添加轻微阴影,增强层次感 */ - /*box-shadow: inset 0 0 8px rgba(0, 0, 0, 0.02);*/ - /*} */ - - /* 可选:超宽屏(比如1600px以上)时,限制留白最大宽度 */ - /*@media (min-width: 1600px) { - .left-container, .right-container { - width: calc((100vw - 1200px) / 2); - max-width: 200px; - background-color: transparent; - } - } -} */ - -/* 2. 主体容器样式:确保和footer分隔 */ -.main-container { - /* 主体容器宽度自适应,可根据需求调整最大宽度 */ - width: 100%; - /* 居中显示(可选) */ - margin: 0 auto; - /* 关键:给主体底部加间距,和footer分开 */ - margin-bottom: 1rem; - /* 主体内边距,防止内容贴边 */ - padding: 1rem; -} - -/* --- 页脚 (Footer) 样式 - 毛玻璃效果 + 适配新增内容 --- */ -.footer { - /* 核心毛玻璃效果 */ - background-color: rgba(255, 255, 255, 0.3); - backdrop-filter: blur(12px); - -webkit-backdrop-filter: blur(12px); /* 兼容webkit内核浏览器 */ - border: 1px solid rgba(255, 255, 255, 0.1); /* 浅白色边框增强质感 */ - box-shadow: inset 0 0 10px rgba(255, 255, 255, 0.05); /* 内阴影提升层次 */ - - /* 布局样式 - 回归文档流,不脱离 */ - position: static; - width: 100%; - padding: 1.5rem 1rem; /* 上下内边距充足,容纳多行内容 */ - margin-top: 2rem; /* 与上方内容分隔 */ - height: auto; /* 高度自适应内容,不挤压 */ - - /* 内容排版 - 垂直分布,居中对齐 */ - display: flex; - flex-direction: column; - align-items: center; - gap: 0.75rem; /* 各子元素之间的间距 */ - - /* 文字基础样式 */ - color: #ffffff !important; - font-size: 14px; -} - -/* footer logo样式 */ -.footer-logo { - margin-bottom: 0.25rem; /* 与版权信息轻微分隔 */ -} - -.footer-logo img { - border-radius: 50%; /* logo圆形化(可选) */ - transition: transform 0.2s ease-in-out; -} - -.footer-logo img:hover { - transform: scale(1.1); /* logo悬浮轻微放大 */ -} - -/* 版权信息容器 */ -.footer-container { - text-align: center; - color: rgba(255, 255, 255, 0.9); /* 文字半透,更柔和 */ -} - -/* 联系我们链接 */ -.footer-contact a { - color: rgba(255, 255, 255, 0.9) !important; - text-decoration: none; - padding: 0.25rem 0.75rem; - border-radius: 4px; - transition: all 0.2s ease-in-out; -} - -.footer-contact a:hover { - color: #ffffff !important; - background-color: rgba(255, 255, 255, 0.15); - text-decoration: underline; -} - -/* 作者信息样式 */ -.footer-author { - color: rgba(255, 255, 255, 0.7); /* 作者信息稍淡,突出层级 */ - font-size: 13px; -} - -.footer-author a { - color: rgba(255, 255, 255, 0.85) !important; - text-decoration: none; - transition: color 0.2s ease-in-out; -} - -.footer-author a:hover { - color: #ffffff !important; - text-decoration: underline; -} - -/* 响应式适配 - 小屏幕优化 */ -@media (max-width: 575.98px) { - .footer { - padding: 1rem 0.5rem; - gap: 0.5rem; - } - - .footer-author { - font-size: 12px; - } -} \ No newline at end of file diff --git a/examples/anlian-mq/public/css/chat.css b/examples/anlian-mq/public/css/chat.css deleted file mode 100644 index bd991fe..0000000 --- a/examples/anlian-mq/public/css/chat.css +++ /dev/null @@ -1,670 +0,0 @@ -/** - * 聊天模块 — 与论坛 feed 粉色毛玻璃主题统一 - */ - -.chat-page { - --chat-accent: #fdbbdb; - --chat-accent-text: #a85878; - --chat-accent-muted: #c97a96; - --chat-text: #333; - --chat-text-muted: #666; - --chat-glass: rgba(255, 255, 255, 0.32); - --chat-glass-border: rgba(255, 255, 255, 0.45); - --chat-shadow: 0 4px 16px rgba(253, 189, 219, 0.08); -} - -.chat-page .section-wrap.chat-stage { - padding: 2rem 2.5rem 2.5rem; -} - -.chat-page .section-wrap.chat-stage-narrow { - max-width: 640px; - margin-left: auto; - margin-right: auto; -} - -.feed-list-title.chat-room-title { - margin-bottom: 0; - text-align: left; - border-bottom: none; - padding-bottom: 0; - flex: 1; - min-width: 0; -} - -.chat-page-lead { - margin: 0.75rem 0 1rem; - font-size: 0.9375rem; - line-height: 1.65; - color: var(--chat-text-muted); - text-align: center; -} - -.chat-room-desc { - text-align: left; - margin-bottom: 0.75rem; -} - -.chat-breadcrumb { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 0.35rem; - margin-bottom: 1rem; - font-size: 0.8125rem; - color: var(--chat-text-muted); -} - -.chat-breadcrumb a { - color: var(--chat-accent-muted); - text-decoration: none; -} - -.chat-breadcrumb a:hover { - color: var(--chat-accent-text); -} - -.chat-breadcrumb-sep { - opacity: 0.45; -} - -.chat-breadcrumb-current { - color: var(--chat-text); - font-weight: 500; -} - -.chat-room-header { - display: flex; - flex-wrap: wrap; - align-items: center; - justify-content: space-between; - gap: 0.75rem; - margin-bottom: 0.5rem; - padding-bottom: 0.75rem; - border-bottom: 1px solid rgba(255, 255, 255, 0.45); -} - -.chat-room-meta { - margin: 0 0 1.25rem; - font-size: 0.8125rem; - color: var(--chat-text-muted); -} - -.chat-room-meta a { - color: var(--chat-accent-text); - text-decoration: none; - font-weight: 600; -} - -.chat-room-meta a:hover { - text-decoration: underline; -} - -.chat-actions { - display: flex; - flex-wrap: wrap; - gap: 0.75rem; - justify-content: center; - margin-bottom: 1.25rem; -} - -.chat-room-search { - display: flex; - flex-wrap: wrap; - gap: 0.65rem; - margin-bottom: 1.25rem; -} - -.chat-room-search-input { - flex: 1; - min-width: 0; - min-height: 42px; - padding: 0.55rem 0.9rem; - border: 1px solid rgba(253, 189, 219, 0.45); - border-radius: 999px; - background: rgba(255, 255, 255, 0.72); - color: var(--chat-text); - font-size: 0.9375rem; -} - -.chat-room-search-input:focus { - outline: none; - border-color: rgba(253, 189, 219, 0.75); - box-shadow: 0 0 0 3px rgba(253, 189, 219, 0.22); -} - -.chat-room-search-input::placeholder { - color: #aaa; -} - -.chat-room-search-btn { - flex-shrink: 0; - padding: 0.55rem 1.1rem; - border: 1px solid rgba(253, 189, 219, 0.55); - border-radius: 999px; - background: rgba(253, 189, 219, 0.35); - color: var(--chat-accent-text); - font-size: 0.875rem; - font-weight: 600; - cursor: pointer; - transition: background 0.2s ease; -} - -.chat-room-search-btn:hover { - background: rgba(253, 189, 219, 0.5); -} - -.chat-list-footer { - display: flex; - justify-content: center; - margin-top: 1.5rem; - padding-top: 1.25rem; - border-top: 1px solid rgba(255, 255, 255, 0.45); -} - -.chat-create-room-btn { - display: inline-flex; - align-items: center; - justify-content: center; - gap: 0.65rem; - width: min(100%, 320px); - padding: 0.85rem 1.35rem; - border-radius: 999px; - text-decoration: none; - color: #fff; - font-size: 0.9375rem; - font-weight: 600; - border: 1px solid rgba(255, 255, 255, 0.35); - background: linear-gradient(135deg, #f0a8c4 0%, #a85878 100%); - box-shadow: - 0 6px 20px rgba(168, 88, 120, 0.28), - inset 0 1px 0 rgba(255, 255, 255, 0.25); - transition: transform 0.15s ease, box-shadow 0.15s ease, filter 0.15s ease; -} - -.chat-create-room-btn:hover { - color: #fff; - text-decoration: none; - transform: translateY(-1px); - box-shadow: - 0 8px 24px rgba(168, 88, 120, 0.34), - inset 0 1px 0 rgba(255, 255, 255, 0.3); - filter: brightness(1.03); -} - -.chat-create-room-btn:active { - transform: translateY(0); -} - -.chat-create-room-btn__icon { - display: inline-flex; - align-items: center; - justify-content: center; - width: 1.75rem; - height: 1.75rem; - border-radius: 50%; - font-size: 0.8125rem; - background: rgba(255, 255, 255, 0.22); -} - -.chat-search-empty { - margin-top: 0.5rem; -} - -.chat-action-link { - display: inline-flex; - align-items: center; -} - -.chat-ws-status { - flex-shrink: 0; - font-size: 0.75rem; - font-weight: 500; - padding: 0.2rem 0.65rem; - border-radius: 999px; - color: var(--chat-accent-muted); - background: rgba(255, 255, 255, 0.35); - border: 1px solid rgba(253, 189, 219, 0.35); -} - -.chat-ws-status-ok { - color: #3d7a52; - background: rgba(144, 238, 144, 0.2); - border-color: rgba(144, 238, 144, 0.45); -} - -.chat-ws-status-error { - color: #a85858; - background: rgba(255, 182, 193, 0.25); - border-color: rgba(255, 160, 160, 0.45); -} - -.chat-ws-errors { - margin: 0.5rem 0 0; - color: #a85858; - font-size: 0.875rem; -} - -/* ---------- 消息区 ---------- */ - -.chat-messages { - display: flex; - flex-direction: column; - gap: 0.85rem; - margin-bottom: 1.25rem; - padding: 1rem; - border-radius: 14px; - background: var(--chat-glass); - backdrop-filter: blur(12px); - -webkit-backdrop-filter: blur(12px); - border: 1px solid var(--chat-glass-border); - box-shadow: var(--chat-shadow); - min-height: 240px; - max-height: min(60vh, 520px); - overflow-y: auto; -} - -.chat-message { - display: flex; - gap: 0.75rem; - align-items: flex-start; -} - -.chat-message-mine { - flex-direction: row-reverse; -} - -.chat-message-mine .chat-message-body { - text-align: right; -} - -.chat-avatar { - width: 40px; - height: 40px; - border-radius: 50%; - object-fit: cover; - flex-shrink: 0; - border: 2px solid rgba(255, 255, 255, 0.65); - box-shadow: 0 2px 8px rgba(253, 189, 219, 0.15); -} - -.chat-message-body { - flex: 1; - min-width: 0; - padding: 0.6rem 0.75rem; - border: 1px solid rgba(253, 189, 219, 0.4); - border-radius: 10px; - background: rgba(255, 255, 255, 0.35); -} - -.chat-message-mine .chat-message-body { - border-color: rgba(240, 168, 196, 0.55); - background: rgba(253, 189, 219, 0.22); -} - -.chat-message-meta { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 0.5rem; - font-size: 0.75rem; - color: var(--chat-text-muted); - margin-bottom: 0.35rem; -} - -.chat-message-mine .chat-message-meta { - justify-content: flex-end; -} - -.chat-author { - color: var(--chat-text); - font-weight: 600; -} - -.chat-profile-link { - color: var(--chat-accent-text); - text-decoration: none; - font-weight: 500; -} - -.chat-profile-link:hover { - text-decoration: underline; -} - -.chat-content { - margin: 0; - white-space: pre-wrap; - word-break: break-word; - font-size: 0.9375rem; - line-height: 1.55; - color: var(--chat-text); -} - -.chat-compose { - margin-top: 0.5rem; -} - -/* ---------- 列表 / 分页 ---------- */ - -.chat-room-grid { - display: grid; - grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); - gap: 1rem; -} - -.chat-room-card { - display: block; - padding: 1.15rem; - border-radius: 14px; - background: var(--chat-glass); - backdrop-filter: blur(10px); - -webkit-backdrop-filter: blur(10px); - border: 1px solid rgba(253, 189, 219, 0.35); - color: inherit; - text-decoration: none; - transition: transform 0.15s ease, box-shadow 0.15s ease; -} - -.chat-room-card:hover { - transform: translateY(-2px); - box-shadow: 0 4px 14px rgba(253, 189, 219, 0.2); - color: inherit; -} - -.chat-room-card h2 { - margin: 0 0 0.5rem; - font-size: 1.05rem; - color: var(--chat-text); -} - -.chat-room-card p { - margin: 0; - color: var(--chat-text-muted); - font-size: 0.875rem; -} - -.chat-pagination { - display: flex; - justify-content: center; - align-items: center; - flex-wrap: wrap; - gap: 0.75rem; - margin-bottom: 1rem; - font-size: 0.875rem; -} - -.chat-pagination-link { - padding: 0.35rem 0.85rem; - border-radius: 999px; - text-decoration: none; - color: var(--chat-accent-text); - background: rgba(253, 189, 219, 0.25); - border: 1px solid rgba(253, 189, 219, 0.4); -} - -.chat-pagination-link:hover { - background: rgba(253, 189, 219, 0.4); - color: var(--chat-accent-text); -} - -.chat-pagination-info { - color: var(--chat-text-muted); -} - -/* ---------- 私聊收件箱 ---------- */ - -.feed-list-title.chat-inbox-title { - margin-bottom: 0; - text-align: left; - border-bottom: none; - padding-bottom: 0; -} - -.chat-inbox-header { - display: flex; - flex-wrap: wrap; - align-items: center; - justify-content: space-between; - gap: 0.75rem; - margin-bottom: 1.25rem; - padding-bottom: 0.75rem; - border-bottom: 1px solid rgba(255, 255, 255, 0.45); -} - -.chat-inbox-new-btn { - display: inline-flex; - align-items: center; - gap: 0.45rem; - padding: 0.5rem 1rem; - border-radius: 999px; - font-size: 0.8125rem; - font-weight: 600; - text-decoration: none; - color: var(--chat-accent-text); - background: rgba(253, 189, 219, 0.28); - border: 1px solid rgba(253, 189, 219, 0.45); - transition: background 0.2s ease, box-shadow 0.2s ease; -} - -.chat-inbox-new-btn:hover { - color: var(--chat-accent-text); - background: rgba(253, 189, 219, 0.42); - box-shadow: 0 4px 12px rgba(253, 189, 219, 0.2); -} - -.chat-inbox-panel { - padding: 0.85rem; - border-radius: 14px; - background: var(--chat-glass); - backdrop-filter: blur(12px); - -webkit-backdrop-filter: blur(12px); - border: 1px solid var(--chat-glass-border); - box-shadow: var(--chat-shadow); -} - -.chat-inbox-panel--compact { - padding: 0.65rem; -} - -.chat-inbox-list { - list-style: none; - margin: 0; - padding: 0; -} - -.chat-inbox-list li + li { - margin-top: 0.5rem; -} - -.chat-inbox-item { - display: flex; - align-items: center; - gap: 0.75rem; - padding: 0.75rem 0.85rem; - border-radius: 12px; - text-decoration: none; - color: var(--chat-text); - background: rgba(255, 255, 255, 0.28); - border: 1px solid rgba(253, 189, 219, 0.22); - transition: background 0.15s ease, border-color 0.15s ease; -} - -.chat-inbox-item:hover { - background: rgba(253, 189, 219, 0.18); - border-color: rgba(253, 189, 219, 0.38); - color: var(--chat-text); -} - -.chat-inbox-avatar { - flex-shrink: 0; - width: 44px; - height: 44px; - border-radius: 50%; - object-fit: cover; - border: 2px solid rgba(255, 255, 255, 0.7); - box-shadow: 0 2px 8px rgba(253, 189, 219, 0.15); -} - -.chat-inbox-body { - flex: 1; - min-width: 0; - display: flex; - flex-direction: column; - gap: 0.2rem; -} - -.chat-inbox-top { - display: flex; - align-items: baseline; - justify-content: space-between; - gap: 0.5rem; -} - -.chat-inbox-name { - font-size: 0.9375rem; - font-weight: 600; - color: var(--chat-accent-text); -} - -.chat-inbox-time { - flex-shrink: 0; - font-size: 0.75rem; - color: var(--chat-text-muted); -} - -.chat-inbox-preview { - display: block; - font-size: 0.8125rem; - line-height: 1.45; - color: var(--chat-text-muted); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; -} - -.chat-inbox-arrow { - flex-shrink: 0; - font-size: 0.75rem; - color: var(--chat-accent-muted); - opacity: 0.75; -} - -.chat-inbox-empty { - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - gap: 0.65rem; - padding: 2.5rem 1.25rem; - text-align: center; -} - -.chat-inbox-empty-icon { - display: inline-flex; - align-items: center; - justify-content: center; - width: 3.25rem; - height: 3.25rem; - border-radius: 50%; - font-size: 1.25rem; - color: var(--chat-accent-muted); - background: rgba(253, 189, 219, 0.22); - border: 1px solid rgba(253, 189, 219, 0.35); -} - -.chat-inbox-empty-title { - margin: 0; - font-size: 1rem; - font-weight: 600; - color: var(--chat-text); -} - -.chat-inbox-empty-lead { - margin: 0; - max-width: 18rem; - font-size: 0.875rem; - line-height: 1.55; - color: var(--chat-text-muted); -} - -.chat-inbox-empty-btn { - display: inline-flex; - align-items: center; - gap: 0.45rem; - margin-top: 0.35rem; - padding: 0.65rem 1.25rem; - border-radius: 999px; - font-size: 0.875rem; - font-weight: 600; - text-decoration: none; - color: #fff; - background: linear-gradient(135deg, #f0a8c4 0%, #a85878 100%); - border: 1px solid rgba(255, 255, 255, 0.3); - box-shadow: 0 4px 14px rgba(168, 88, 120, 0.25); - transition: transform 0.15s ease, box-shadow 0.15s ease; -} - -.chat-inbox-empty-btn:hover { - color: #fff; - transform: translateY(-1px); - box-shadow: 0 6px 18px rgba(168, 88, 120, 0.32); -} - -.chat-thread-list { - list-style: none; - padding: 0; - margin: 0; -} - -.chat-thread-list li + li { - margin-top: 0.5rem; -} - -.chat-thread-list a { - display: flex; - justify-content: space-between; - align-items: center; - padding: 0.85rem 1rem; - border-radius: 12px; - background: var(--chat-glass); - border: 1px solid rgba(253, 189, 219, 0.3); - color: var(--chat-text); - text-decoration: none; -} - -.chat-thread-list a:hover { - background: rgba(253, 189, 219, 0.2); -} - -.chat-thread-time { - font-size: 0.8125rem; - color: var(--chat-text-muted); -} - -.chat-empty, -.chat-login-hint { - color: var(--chat-text-muted); - text-align: center; -} - -.chat-empty a, -.chat-login-hint a { - color: var(--chat-accent-text); - font-weight: 600; -} - -@media (max-width: 768px) { - .chat-page .section-wrap.chat-stage { - padding: 1.5rem 1.25rem 2rem; - } - - .feed-list-title.chat-room-title { - font-size: 1.25rem; - } -} - -@media (max-width: 640px) { - .chat-messages { - max-height: none; - } -} diff --git a/examples/anlian-mq/public/css/detail_reading.css b/examples/anlian-mq/public/css/detail_reading.css deleted file mode 100644 index 6671036..0000000 --- a/examples/anlian-mq/public/css/detail_reading.css +++ /dev/null @@ -1,212 +0,0 @@ -/* 详情页:箭头上一篇/下一篇 + 推荐阅读轮播 */ - -.detail-reading-extras { - margin-bottom: 2rem; - display: flex; - flex-direction: column; - gap: 1.25rem; -} - -.detail-adjacent-nav, -.detail-recommend { - padding: 1rem 1.25rem !important; - margin: 0 !important; -} - -/* --- 上一篇 / 下一篇:左右箭头 --- */ -.detail-adjacent-bar { - display: flex; - align-items: stretch; - justify-content: space-between; - gap: 0.75rem; -} - -.detail-adjacent-side { - display: flex; - align-items: center; - gap: 0.5rem; - min-width: 0; - flex: 1; -} - -.detail-adjacent-side-prev { - justify-content: flex-start; -} - -.detail-adjacent-side-next { - justify-content: flex-end; - text-align: right; -} - -.detail-arrow-btn { - flex-shrink: 0; - display: inline-flex; - align-items: center; - justify-content: center; - width: 2.25rem; - height: 2.25rem; - border-radius: 50%; - background: linear-gradient(145deg, #fdbbdb, #f0a8c4); - color: #fff; - text-decoration: none; - box-shadow: 0 2px 8px rgba(168, 88, 120, 0.25); - transition: transform 0.2s ease, box-shadow 0.2s ease; -} - -.detail-arrow-btn:hover { - transform: scale(1.06); - box-shadow: 0 4px 12px rgba(168, 88, 120, 0.35); - color: #fff; -} - -.detail-arrow-btn.is-disabled { - background: rgba(0, 0, 0, 0.08); - color: #bbb; - box-shadow: none; - cursor: default; - pointer-events: none; -} - -.detail-adjacent-title { - color: #333; - text-decoration: none; - font-weight: 600; - font-size: 0.9rem; - line-height: 1.4; - overflow: hidden; - text-overflow: ellipsis; - display: -webkit-box; - -webkit-line-clamp: 2; - -webkit-box-orient: vertical; -} - -.detail-adjacent-title:hover { - color: #a85878; -} - -/* --- 推荐阅读轮播 --- */ -.detail-recommend-heading { - margin: 0 0 0.85rem; - font-size: 0.95rem; - font-weight: 700; - color: #a85878; - letter-spacing: 0.02em; -} - -.detail-recommend-viewport { - overflow: hidden; - border-radius: 12px; -} - -.detail-recommend-track { - display: flex; - align-items: stretch; - transition: transform 0.45s cubic-bezier(0.4, 0, 0.2, 1); - will-change: transform; -} - -.detail-recommend-slide { - flex: 0 0 100%; - box-sizing: border-box; - padding: 0 0.15rem; - display: flex; - align-items: stretch; -} - -.detail-recommend-card { - display: flex; - flex-direction: column; - flex: 1; - width: 100%; - gap: 0.35rem; - padding: 1rem 1.1rem; - border-radius: 12px; - background: rgba(255, 255, 255, 0.55); - border: 1px solid rgba(255, 255, 255, 0.65); - text-decoration: none; - transition: background 0.2s ease, border-color 0.2s ease; -} - -.detail-recommend-card:hover { - background: rgba(255, 255, 255, 0.82); - border-color: rgba(253, 187, 219, 0.8); -} - -.detail-recommend-card-title { - flex: 1 1 auto; - color: #222; - font-weight: 600; - font-size: 0.95rem; - line-height: 1.45; - /* 固定两行高度,短标题与长标题卡片等高 */ - min-height: calc(0.95rem * 1.45 * 2); - overflow: hidden; - text-overflow: ellipsis; - display: -webkit-box; - -webkit-line-clamp: 2; - -webkit-box-orient: vertical; -} - -.detail-recommend-card-meta { - flex-shrink: 0; - margin-top: auto; - font-size: 0.78rem; - color: #888; -} - -.detail-recommend-dots { - display: flex; - justify-content: center; - align-items: center; - gap: 0.45rem; - margin-top: 0.85rem; - padding-bottom: 0.15rem; -} - -.detail-recommend-dot { - width: 0.45rem; - height: 0.45rem; - padding: 0; - border: none; - border-radius: 50%; - background: rgba(168, 88, 120, 0.25); - cursor: pointer; - transition: transform 0.2s ease, background 0.2s ease; -} - -.detail-recommend-dot:hover { - background: rgba(168, 88, 120, 0.45); -} - -.detail-recommend-dot.is-active { - background: #a85878; - transform: scale(1.25); -} - -@media (min-width: 768px) { - .detail-recommend-slide { - flex: 0 0 50%; - } - - .detail-adjacent-title { - font-size: 0.92rem; - -webkit-line-clamp: 1; - } -} - -@media (max-width: 767.98px) { - .detail-adjacent-bar { - flex-direction: column; - gap: 0.65rem; - } - - .detail-adjacent-side-next { - text-align: left; - justify-content: flex-start; - flex-direction: row-reverse; - } - - .detail-adjacent-side-prev { - flex-direction: row; - } -} diff --git a/examples/anlian-mq/public/css/feed_common.css b/examples/anlian-mq/public/css/feed_common.css deleted file mode 100644 index 07167e8..0000000 --- a/examples/anlian-mq/public/css/feed_common.css +++ /dev/null @@ -1,459 +0,0 @@ -/** - * 帖子/新闻列表共用:粉色毛玻璃分段板块 + 横向卡片 - * 用于首页 .home-posts 与独立列表页 .feed-list-page - */ - -.home-posts, -.feed-list-page { - --post-accent: #fdbbdb; - --post-accent-deep: #f0a8c4; - --post-accent-text: #a85878; - --post-accent-muted: #c97a96; - --post-accent-bg: rgba(253, 189, 219, 0.48); -} - -/* ---------- 板块栏(强制单行:左箭头 | 可滚动 Tab | 右箭头) ---------- */ -.home-posts-board-bar, -.feed-list-page .feed-board-bar { - display: flex; - flex-direction: row; - flex-wrap: nowrap; - align-items: center; - justify-content: flex-start; - gap: 0.5rem; - margin-bottom: 1.25rem; - width: 100%; - max-width: 100%; - min-width: 0; - box-sizing: border-box; -} - -.home-posts-segment-outer, -.feed-list-page .feed-segment-outer { - flex: 1 1 0%; - min-width: 0; - width: 0; - display: block; - overflow: hidden; -} - -.home-posts-segment, -.feed-list-page .feed-segment { - position: relative; - display: flex; - width: 100%; - max-width: 100%; - min-width: 0; - box-sizing: border-box; - padding: 4px; - border-radius: 999px; - background: rgba(255, 255, 255, 0.28); - backdrop-filter: blur(18px); - -webkit-backdrop-filter: blur(18px); - border: 1px solid rgba(255, 255, 255, 0.5); - box-shadow: - 0 4px 20px rgba(253, 189, 219, 0.12), - inset 0 1px 0 rgba(255, 255, 255, 0.35); -} - -.home-posts-spotlight, -.feed-list-page .feed-spotlight { - position: absolute; - top: 4px; - bottom: 4px; - left: 0; - width: var(--spot-w, 4rem); - border-radius: 999px; - background: var(--post-accent-bg); - border: 1px solid rgba(240, 168, 196, 0.55); - box-shadow: 0 2px 14px rgba(253, 189, 219, 0.35); - transform: translateX(var(--spot-l, 0)); - transition: - transform 0.28s cubic-bezier(0.34, 1.2, 0.64, 1), - width 0.28s cubic-bezier(0.34, 1.2, 0.64, 1); - pointer-events: none; - z-index: 0; -} - -.home-posts-tabs-scroll, -.feed-list-page .feed-tabs-scroll { - position: relative; - z-index: 1; - width: 100%; - min-width: 0; - overflow-x: auto; - overflow-y: hidden; - max-width: 100%; - scroll-behavior: smooth; - -ms-overflow-style: none; - scrollbar-width: none; - mask-image: linear-gradient( - to right, - transparent, - #000 12px, - #000 calc(100% - 12px), - transparent - ); -} - -.home-posts-tabs-scroll::-webkit-scrollbar, -.feed-list-page .feed-tabs-scroll::-webkit-scrollbar { - display: none; -} - -.home-posts-tabs, -.feed-list-page .feed-tabs { - display: flex; - flex-wrap: nowrap; - gap: 2px; - padding: 0 2px; -} - -.home-posts-tab, -.feed-list-page .feed-tab { - flex-shrink: 0; - padding: 0.4rem 1rem; - border-radius: 999px; - font-size: 0.8125rem; - font-weight: 500; - text-decoration: none; - color: #555; - background: transparent; - border: 1px solid transparent; - transition: color 0.2s ease; - white-space: nowrap; -} - -.home-posts-tab:hover, -.feed-list-page .feed-tab:hover { - color: var(--post-accent-text); -} - -.home-posts-tab.active, -.feed-list-page .feed-tab.active { - color: var(--post-accent-text); - font-weight: 600; -} - -.home-posts-tab-more { - background: rgba(253, 189, 219, 0.32); - border-color: rgba(253, 189, 219, 0.45); - color: var(--post-accent-text); -} - -.home-posts-tab-more:hover { - background: rgba(253, 189, 219, 0.48); - color: var(--post-accent-text); -} - -.home-posts-scroll, -.feed-list-page .feed-scroll { - flex: 0 0 32px; - width: 32px; - min-width: 32px; - max-width: 32px; - height: 32px; - padding: 0; - margin: 0; - display: inline-flex; - align-items: center; - justify-content: center; - border: 1px solid rgba(255, 255, 255, 0.5); - border-radius: 50%; - background: rgba(255, 255, 255, 0.35); - backdrop-filter: blur(10px); - color: var(--post-accent-text); - cursor: pointer; - transition: background 0.2s, transform 0.2s, opacity 0.2s; - box-sizing: border-box; - -webkit-appearance: none; - appearance: none; -} - -.home-posts-scroll:hover, -.feed-list-page .feed-scroll:hover { - background: rgba(253, 189, 219, 0.35); - transform: scale(1.05); -} - -.home-posts-scroll:disabled, -.home-posts-scroll.is-hidden, -.feed-list-page .feed-scroll.is-hidden { - opacity: 0.3; - pointer-events: none; - transform: none; - /* 仍占位,避免板块栏折行 */ - visibility: visible; - flex: 0 0 32px; - width: 32px; - min-width: 32px; -} - -/* ---------- 帖子卡片列表 ---------- */ -.home-posts-list, -.feed-list-page .feed-posts-list { - list-style: none; - margin: 0; - padding: 0; - display: flex; - flex-direction: column; - gap: 0.65rem; -} - -.home-post-card, -.feed-list-page .feed-post-card { - border-radius: 14px; - background: rgba(255, 255, 255, 0.32); - backdrop-filter: blur(12px); - -webkit-backdrop-filter: blur(12px); - border: 1px solid rgba(255, 255, 255, 0.42); - box-shadow: 0 4px 16px rgba(253, 189, 219, 0.08); - transition: transform 0.2s ease, box-shadow 0.2s ease, background 0.2s ease; -} - -.home-post-card:hover, -.feed-list-page .feed-post-card:hover { - transform: translateY(-2px); - background: rgba(255, 255, 255, 0.42); - box-shadow: 0 8px 24px rgba(253, 189, 219, 0.18); -} - -.home-post-card-link, -.feed-list-page .feed-post-card-link { - display: grid; - grid-template-columns: auto 1fr auto; - align-items: center; - gap: 0.75rem 1rem; - padding: 0.75rem 1rem; - text-decoration: none; - color: inherit; -} - -.home-post-board, -.feed-list-page .feed-post-board { - flex-shrink: 0; - padding: 0.2rem 0.55rem; - border-radius: 6px; - font-size: 0.6875rem; - font-weight: 600; - color: var(--post-accent-text); - background: rgba(253, 189, 219, 0.28); - white-space: nowrap; - max-width: 5rem; - overflow: hidden; - text-overflow: ellipsis; -} - -.home-post-body, -.feed-list-page .feed-post-body { - min-width: 0; -} - -.home-post-title, -.feed-list-page .feed-post-title { - margin: 0 0 0.3rem; - font-size: 0.9375rem; - font-weight: 600; - color: #222; - line-height: 1.35; - display: -webkit-box; - -webkit-box-orient: vertical; - -webkit-line-clamp: 1; - overflow: hidden; -} - -.home-post-meta, -.feed-list-page .feed-post-meta { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 0.5rem 0.85rem; - font-size: 0.75rem; - color: #666; -} - -.home-post-meta-item, -.feed-list-page .feed-post-meta-item { - display: inline-flex; - align-items: center; - gap: 0.25rem; -} - -.home-post-meta i, -.feed-list-page .feed-post-meta i { - font-size: 0.7rem; - opacity: 0.75; -} - -.home-post-meta time, -.feed-list-page .feed-post-meta time { - color: var(--post-accent-muted); -} - -.home-post-arrow, -.feed-list-page .feed-post-arrow { - color: rgba(253, 189, 219, 0.9); - font-size: 0.75rem; - opacity: 0.7; - transition: opacity 0.2s, transform 0.2s; -} - -.home-post-card:hover .home-post-arrow, -.feed-list-page .feed-post-card:hover .feed-post-arrow { - opacity: 1; - transform: translateX(2px); -} - -.home-posts-empty, -.feed-list-page .feed-empty { - text-align: center; - padding: 2rem; - color: #666; -} - -.home-posts-more-link { - display: block; - width: fit-content; - margin: 1rem auto 0; - padding: 0.45rem 1.25rem; - border-radius: 999px; - font-size: 0.8125rem; - font-weight: 600; - text-decoration: none; - color: var(--post-accent-text); - background: rgba(253, 189, 219, 0.35); - border: 1px solid rgba(253, 189, 219, 0.55); - transition: background 0.2s, box-shadow 0.2s; -} - -.home-posts-more-link:hover { - background: rgba(253, 189, 219, 0.5); - box-shadow: 0 4px 14px rgba(253, 189, 219, 0.25); -} - -/* ---------- 新闻列表卡片(横向胶囊风格,静态列表) ---------- */ -.feed-list-page .feed-news-list { - list-style: none; - margin: 0; - padding: 0; - display: flex; - flex-direction: column; - gap: 0.65rem; -} - -.feed-list-page .feed-news-card { - border-radius: 14px; - background: rgba(255, 255, 255, 0.32); - backdrop-filter: blur(12px); - -webkit-backdrop-filter: blur(12px); - border: 1px solid rgba(255, 255, 255, 0.42); - box-shadow: 0 4px 16px rgba(253, 189, 219, 0.08); - transition: transform 0.2s ease, box-shadow 0.2s ease, background 0.2s ease; -} - -.feed-list-page .feed-news-card:hover { - transform: translateY(-2px); - background: rgba(255, 255, 255, 0.42); - box-shadow: 0 8px 24px rgba(253, 189, 219, 0.18); -} - -.feed-list-page .feed-news-card-link { - display: grid; - grid-template-columns: auto 1fr auto; - align-items: center; - gap: 0.75rem 1rem; - padding: 0.75rem 1rem; - text-decoration: none; - color: inherit; -} - -.feed-list-page .feed-news-side { - flex-shrink: 0; - display: flex; - flex-direction: column; - align-items: flex-start; - gap: 0.15rem; - padding-right: 0.65rem; - border-right: 1px solid rgba(253, 189, 219, 0.35); - min-width: 4.5rem; -} - -.feed-list-page .feed-news-date { - font-size: 0.6875rem; - font-weight: 700; - color: var(--post-accent-muted); - white-space: nowrap; -} - -.feed-list-page .feed-news-board { - font-size: 0.625rem; - font-weight: 600; - color: var(--post-accent-text); - background: rgba(253, 189, 219, 0.22); - padding: 0.12rem 0.35rem; - border-radius: 3px; - max-width: 5.5rem; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -@media (max-width: 576px) { - .home-posts-board-bar, - .feed-list-page .feed-board-bar { - gap: 0.35rem; - } - - .home-posts-scroll, - .feed-list-page .feed-scroll { - flex: 0 0 28px; - width: 28px; - min-width: 28px; - max-width: 28px; - height: 28px; - font-size: 0.7rem; - } - - .home-posts-scroll.is-hidden, - .feed-list-page .feed-scroll.is-hidden { - flex: 0 0 28px; - width: 28px; - min-width: 28px; - } - - .home-posts-tab, - .feed-list-page .feed-tab { - padding: 0.35rem 0.7rem; - font-size: 0.75rem; - } - - .home-post-card-link, - .feed-list-page .feed-post-card-link, - .feed-list-page .feed-news-card-link { - grid-template-columns: 1fr auto; - grid-template-rows: auto auto; - } - - .home-post-board, - .feed-list-page .feed-post-board, - .feed-list-page .feed-news-side { - grid-column: 1; - justify-self: start; - border-right: none; - padding-right: 0; - flex-direction: row; - gap: 0.35rem; - } - - .home-post-body, - .feed-list-page .feed-post-body { - grid-column: 1; - } - - .home-post-arrow, - .feed-list-page .feed-post-arrow { - grid-column: 2; - grid-row: 1 / span 2; - align-self: center; - } -} diff --git a/examples/anlian-mq/public/css/feed_list.css b/examples/anlian-mq/public/css/feed_list.css deleted file mode 100644 index ed255e2..0000000 --- a/examples/anlian-mq/public/css/feed_list.css +++ /dev/null @@ -1,116 +0,0 @@ -/** - * 帖子/新闻独立列表页布局(与首页 section-wrap 宽度一致) - * 不依赖 index.css(首页 hero/notice 专用) - */ - -section.feed-list-page { - height: auto; - min-height: 0; - box-sizing: border-box; -} - -.feed-list-page { - padding: 2rem 0 3rem; -} - -.feed-list-page .section-wrap.feed-list-stage { - display: block; - width: 90%; - max-width: none; - margin-left: auto; - margin-right: auto; - box-sizing: border-box; - background-color: rgba(255, 255, 255, 0.14); - border: 1px solid rgba(255, 255, 255, 0.2); - box-shadow: inset 0 0 5px rgba(255, 255, 255, 0.1); - border-radius: 30px; - backdrop-filter: blur(12px); - padding: 2rem 2.5rem 2.5rem; - height: auto; - min-height: 0; - max-height: none; - overflow: visible; -} - -.feed-list-body { - width: 100%; - overflow: visible; -} - -.feed-list-title { - margin: 0 0 1.25rem; - font-size: 1.5rem; - font-weight: 600; - color: #111; - text-align: center; - border-bottom: 1px solid rgba(255, 255, 255, 0.45); - padding-bottom: 0.65rem; -} - -.feed-list-actions { - display: flex; - justify-content: center; - margin-bottom: 1rem; -} - -.feed-list-actions .feed-action-link { - padding: 0.4rem 1rem; - border-radius: 999px; - font-size: 0.8125rem; - font-weight: 600; - text-decoration: none; - color: var(--post-accent-text); - background: rgba(253, 189, 219, 0.35); - border: 1px solid rgba(253, 189, 219, 0.55); - transition: background 0.2s, box-shadow 0.2s; -} - -.feed-list-actions .feed-action-link:hover { - background: rgba(253, 189, 219, 0.5); - box-shadow: 0 4px 14px rgba(253, 189, 219, 0.25); -} - -.feed-list-page .feed-pagination { - margin-top: 1.5rem; -} - -.feed-list-page .feed-pagination .page-link { - color: var(--post-accent-text); - background: rgba(255, 255, 255, 0.32); - backdrop-filter: blur(10px); - border: 1px solid rgba(253, 189, 219, 0.4); - border-radius: 8px; - margin: 0 0.2rem; - transition: background 0.2s; -} - -.feed-list-page .feed-pagination .page-link:hover { - background: rgba(253, 189, 219, 0.35); -} - -.feed-list-page .feed-pagination .page-item.active .page-link { - background: rgba(253, 189, 219, 0.55); - border-color: rgba(240, 168, 196, 0.75); - color: var(--post-accent-text); - font-weight: 600; -} - -@media (max-width: 768px) { - section.feed-list-page, - .feed-list-page { - padding: 16px 0; - } - - .feed-list-page .section-wrap.feed-list-stage { - width: 95%; - border-radius: 20px; - padding: 1.25rem 1.5rem 1.75rem; - } -} - -@media (max-width: 576px) { - .feed-list-page .section-wrap.feed-list-stage { - width: 98%; - padding: 1rem 1.15rem 1.5rem; - } -} diff --git a/examples/anlian-mq/public/css/footer.css b/examples/anlian-mq/public/css/footer.css deleted file mode 100644 index 24f937c..0000000 --- a/examples/anlian-mq/public/css/footer.css +++ /dev/null @@ -1,251 +0,0 @@ -/* 全站页脚:白色毛玻璃,与导航/首页区块风格一致 */ -.site-footer { - margin-top: 2rem; - padding: 2.25rem 1.5rem 2.75rem; - background: rgba(255, 255, 255, 0.28); - backdrop-filter: blur(14px); - -webkit-backdrop-filter: blur(14px); - border-top: 1px solid rgba(255, 255, 255, 0.45); - box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.35); - color: #333; -} - -.site-footer-inner { - max-width: 1000px; - margin: 0 auto; - display: grid; - grid-template-columns: 1fr 1fr; - gap: 2rem 3rem; - align-items: start; -} - -.footer-col { - display: flex; - flex-direction: column; - align-items: center; - text-align: center; -} - -/* ---------- 左栏:站点信息(居中 + 字号层级) ---------- */ -.footer-site-logo { - border-radius: 50%; - object-fit: cover; - margin-bottom: 0.5rem; -} - -.footer-site-name { - margin: 0 0 0.35rem; - font-size: 1.25rem; - font-weight: 700; - color: #111; - letter-spacing: 0.02em; -} - -.footer-site-tagline { - margin: 0 0 0.75rem; - font-size: 0.8125rem; - font-weight: 400; - color: #555; - line-height: 1.5; - max-width: 22rem; -} - -.footer-copy { - margin: 0 0 0.5rem; - font-size: 0.9375rem; - font-weight: 500; - color: #444; -} - -.footer-meta-sm { - margin: 0.2rem 0; - font-size: 0.8125rem; - color: #666; - line-height: 1.45; -} - -.footer-meta-label { - display: inline; - margin-right: 0.35rem; - font-size: 0.75rem; - color: #888; -} - -.footer-meta-label::after { - content: ":"; -} - -.footer-col-site a { - color: #2a5db0; - text-decoration: none; -} - -.footer-col-site a:hover { - color: #0d47a1; - text-decoration: underline; -} - -.footer-api-guide { - margin-top: 0.45rem; -} - -.footer-guide-btn { - display: inline-flex; - align-items: center; - gap: 0.35rem; - padding: 0.28rem 0.65rem; - font-size: 0.75rem; - font-weight: 600; - color: #555 !important; - text-decoration: none !important; - background: rgba(255, 255, 255, 0.45); - border: 1px solid rgba(0, 0, 0, 0.08); - border-radius: 999px; - transition: background 0.2s ease, color 0.2s ease, border-color 0.2s ease; -} - -.footer-guide-btn:hover { - color: #2a5db0 !important; - background: rgba(255, 255, 255, 0.75); - border-color: rgba(42, 93, 176, 0.25); -} - -.footer-guide-btn .anlian-icon { - font-size: 0.7rem; - opacity: 0.85; -} - -.footer-beian { - display: flex; - flex-wrap: wrap; - justify-content: center; - gap: 0.35rem 0.85rem; - margin-top: 0.65rem; -} - -.footer-beian-link { - display: inline-flex; - align-items: center; - gap: 0.3rem; - font-size: 0.75rem; - color: #777 !important; - text-decoration: none; -} - -.footer-beian-link:hover { - color: #333 !important; - text-decoration: underline; -} - -.beian-icon { - vertical-align: middle; -} - -/* ---------- 右栏:作者(头像在上,信息居中,无卡片) ---------- */ -.footer-col-author { - gap: 0.65rem; -} - -.footer-author-avatar { - width: 72px; - height: 72px; - border-radius: 50%; - object-fit: cover; - border: 2px solid rgba(255, 255, 255, 0.85); - box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08); -} - -.footer-author-info { - display: flex; - flex-direction: column; - align-items: center; - gap: 0.2rem; - width: 100%; - max-width: 16rem; -} - -.footer-author-name { - margin: 0; - font-size: 1.125rem; - font-weight: 700; - color: #111; -} - -.footer-author-name a { - color: #111; - text-decoration: none; -} - -.footer-author-name a:hover { - color: #111; - text-decoration: underline; -} - -.footer-author-title { - margin: 0; - font-size: 0.875rem; - color: #666; -} - -.footer-author-meta { - margin: 0.1rem 0; - font-size: 0.8125rem; - color: #555; -} - -.footer-author-meta a { - color: #555; - text-decoration: none; - word-break: break-all; -} - -.footer-author-meta a:hover { - color: #333; - text-decoration: underline; -} - -/* 个人主页:白色加粗,悬浮白色下划线(与全站毛玻璃主题一致) */ -.footer-author-home a { - color: #fff; - font-weight: 700; - text-decoration: none; - text-shadow: 0 1px 3px rgba(0, 0, 0, 0.35); -} - -.footer-author-home a:hover, -.footer-author-home a:focus-visible { - color: #fff; - text-decoration: underline; - text-decoration-color: #fff; - text-underline-offset: 0.2em; -} - -/* ---------- 首页与其它页面共用 ---------- */ -.page-home .main-container { - max-width: none; - width: 100%; - padding: 0; - margin: 0; -} - - -.hero .social a { - color: inherit; - text-decoration: none; -} - -.hero .social a:hover { - opacity: 0.85; -} - -@media (max-width: 767.98px) { - .site-footer-inner { - grid-template-columns: 1fr; - gap: 2rem; - } - - .footer-col-author { - padding-top: 0.5rem; - border-top: 1px solid rgba(0, 0, 0, 0.06); - } -} diff --git a/examples/anlian-mq/public/css/icons.css b/examples/anlian-mq/public/css/icons.css deleted file mode 100644 index eaa3b2d..0000000 --- a/examples/anlian-mq/public/css/icons.css +++ /dev/null @@ -1,17 +0,0 @@ -.anlian-icon { - display: inline-flex; - align-items: center; - justify-content: center; - width: 1em; - height: 1em; - vertical-align: -0.125em; - fill: currentColor; - flex-shrink: 0; - line-height: 1; -} - -.anlian-icon svg { - display: block; - width: 100%; - height: 100%; -} diff --git a/examples/anlian-mq/public/css/index.css b/examples/anlian-mq/public/css/index.css deleted file mode 100644 index 79008ca..0000000 --- a/examples/anlian-mq/public/css/index.css +++ /dev/null @@ -1,180 +0,0 @@ -/* ========== 原有基础样式保留(略作优化) ========== */ -/* 针对section的css样式 */ -section, -.right, -.left, -.social, -.social .anlian-icon { - display: flex; - justify-content: center; - align-items: center; -} - -section { - height: 100vh; - /* 新增:确保小屏幕也能完整显示内容,避免溢出 */ - min-height: 600px; - padding: 20px 0; - box-sizing: border-box; -} - -.section-wrap { - background-color: rgba(255, 255, 255, 0.2); - height: 80vh; - min-height: 500px; /* 新增:最小高度,避免小屏幕塌陷 */ - width: 90%; - border: 1px solid rgba(255, 255, 255, 0.2); - box-shadow: inset 0 0 5px rgba(255, 255, 255, 0.1); - border-radius: 30px; - backdrop-filter: blur(12px); - padding: 50px 100px; - overflow: hidden; - box-sizing: border-box; /* 新增:内边距计入宽度 */ -} - -@media (max-width: 992px) { - .section-wrap { - padding: 30px 50px; /* 减小内边距 */ - height: 85vh; /* 增加高度占比,容纳内容 */ - } -} - -@media (max-width: 768px) { - section { - height: auto; /* 取消固定高度,自适应内容 */ - min-height: 100vh; /* 确保至少占满视窗 */ - padding: 40px 0; - } - - .section-wrap { - height: auto; /* 取消固定高度 */ - /* min-height: auto; */ - padding: 20px 30px; - width: 95%; /* 增加宽度占比 */ - border-radius: 20px; /* 减小圆角,适配小屏 */ - } -} - -@media (max-width: 576px) { - .section-wrap { - padding: 15px 20px; - width: 98%; - } -} - -/* 内容型区块:取消 100vh + flex 居中,避免列表被压扁裁切(桌面端亦生效) */ -section.feed-list-page, -.page-home section.home-posts, -.page-home section.home-news { - height: auto; - min-height: 0; - align-items: stretch; - justify-content: flex-start; -} - -/* 公告 / 新闻 / 帖子 / 列表页:统一宽度 */ -.page-home section.notice > .section-wrap, -.page-home section.home-news > .section-wrap, -.page-home section.home-posts > .section-wrap, -section.feed-list-page > .section-wrap.feed-list-stage { - width: 90%; - max-width: none; - margin-left: auto; - margin-right: auto; - box-sizing: border-box; -} - -/* 公告:保留轮播区高度(勿用 min-height:0,否则绝对定位容器坍塌) */ -.page-home section.notice > .section-wrap { - position: relative; - min-height: clamp(380px, 52vh, 560px); - overflow: hidden; -} - -/* 新闻 / 帖子 / 列表:高度随内容,覆盖全局 80vh + overflow:hidden */ -.page-home section.home-news > .section-wrap, -.page-home section.home-posts > .section-wrap, -section.feed-list-page > .section-wrap.feed-list-stage { - height: auto; - min-height: 0; - max-height: none; - overflow: visible; -} - -/* 首页 Hero:全屏感 + 与其它区块统一宽度 */ -.page-home section.hero { - height: auto; - min-height: 100vh; - align-items: stretch; - padding: 20px 0; -} - -.page-home section.hero > .section-wrap { - width: 90%; - max-width: none; - margin-left: auto; - margin-right: auto; - height: auto; - min-height: clamp(520px, 82vh, 760px); - overflow: visible; - box-sizing: border-box; -} - -@media (max-width: 1024px) { - .page-home section.hero { - min-height: auto; - padding: 16px 0; - } - - .page-home section.hero > .section-wrap { - min-height: clamp(460px, 75vh, 680px); - padding: 28px 40px; - } -} - -@media (max-width: 768px) { - .page-home section.hero, - .page-home section.home-posts, - .page-home section.home-news, - .page-home section.notice, - section.feed-list-page { - min-height: auto; - padding: 16px 0; - } - - .page-home section.notice > .section-wrap, - .page-home section.home-news > .section-wrap, - .page-home section.home-posts > .section-wrap, - section.feed-list-page > .section-wrap.feed-list-stage, - .page-home section.hero > .section-wrap { - width: 95%; - } - - .page-home section.hero > .section-wrap { - min-height: auto; - padding: 20px 24px; - } - - .page-home section.notice > .section-wrap { - min-height: clamp(340px, 58vh, 480px); - } -} - -@media (max-width: 576px) { - .page-home section.notice > .section-wrap, - .page-home section.home-news > .section-wrap, - .page-home section.home-posts > .section-wrap, - section.feed-list-page > .section-wrap.feed-list-stage, - .page-home section.hero > .section-wrap { - width: 98%; - } - - .page-home section.hero > .section-wrap { - padding: 16px 18px; - border-radius: 20px; - } - - .page-home section.notice > .section-wrap { - min-height: clamp(300px, 62vh, 420px); - } -} diff --git a/examples/anlian-mq/public/css/index/hero.css b/examples/anlian-mq/public/css/index/hero.css deleted file mode 100644 index 6cd2953..0000000 --- a/examples/anlian-mq/public/css/index/hero.css +++ /dev/null @@ -1,276 +0,0 @@ -/** - * 首页 Hero(暗恋见君) - * 断点:台式 ≥1025px | 平板 768–1024px | 手机 ≤767px - */ - -@keyframes heroImageFloat { - 0%, - 100% { - transform: scale(1); - } - 50% { - transform: scale(1.04); - } -} - -/* ---------- 区块与容器 ---------- */ -section.hero { - align-items: stretch; - justify-content: center; -} - -.hero .section-wrap { - display: flex; - flex-direction: column; - justify-content: space-between; - gap: 1.25rem; - width: 100%; - box-sizing: border-box; -} - -/* ---------- 顶栏 Logo ---------- */ -.hero header { - display: flex; - flex-direction: row; - flex-wrap: nowrap; - align-items: center; - justify-content: flex-start; - gap: 0.65rem; - width: 100%; - padding-bottom: 0.75rem; - flex-shrink: 0; -} - -.hero header img { - width: 30px; - height: 30px; - flex-shrink: 0; - object-fit: contain; -} - -.head-logo { - font-size: 2rem; - font-weight: bold; - text-transform: uppercase; - letter-spacing: 2px; - cursor: pointer; - text-decoration: none; - color: #000; - white-space: nowrap; -} - -.head-logo span { - color: #ffd0d0; -} - -/* ---------- 主内容区 ---------- */ -.hero-content { - display: grid; - grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); - align-items: center; - gap: 2rem; - flex: 1 1 auto; - min-height: 0; - width: 100%; -} - -.hero .left { - display: flex; - flex-direction: column; - align-items: flex-start; - justify-content: center; - min-width: 0; - width: 100%; -} - -.hero .right { - display: flex; - align-items: center; - justify-content: center; - min-width: 0; - width: 100%; -} - -.main-text { - margin: 0 0 1.875rem; - font-size: 6rem; - font-weight: 800; - line-height: 1.2; - text-transform: uppercase; - color: #111; - word-break: break-word; - overflow-wrap: anywhere; - width: 100%; -} - -.main-text span { - color: #ffd0d0; -} - -.sub-text { - margin: 0 0 3.125rem; - font-size: 1.2rem; - letter-spacing: 1px; - font-weight: 400; - color: rgba(60, 60, 60, 0.85); - line-height: 1.5; - max-width: none; -} - -.hero .right img { - display: block; - width: 85%; - max-width: 100%; - height: auto; - filter: drop-shadow(0 0 20px rgba(255, 208, 208, 0.45)); - animation: heroImageFloat 30s linear infinite; - pointer-events: none; -} - -/* ---------- 社交链接 ---------- */ -.hero .social { - display: flex; - flex-wrap: wrap; - align-items: center; - justify-content: flex-start; - gap: 0.5rem; - width: 100%; - flex-shrink: 0; - padding-top: 0.25rem; -} - -.hero .social a { - display: inline-flex; - text-decoration: none; -} - -.hero .social .anlian-icon { - display: inline-flex; - align-items: center; - justify-content: center; - width: 40px; - height: 40px; - font-size: 1.1rem; - border: 1px solid rgba(241, 248, 233, 0.9); - border-radius: 50%; - margin: 0; - cursor: pointer; - transition: border-color 0.25s, box-shadow 0.25s, transform 0.25s, color 0.25s; -} - -.hero .social .anlian-icon:hover { - border-color: #ffd0d0; - box-shadow: 0 0 20px rgba(255, 208, 208, 0.45); - color: #ffd0d0; - transform: rotate(360deg); -} - -/* ========== 平板(768px–1024px) ========== */ -@media (max-width: 1024px) { - .head-logo { - font-size: 1.8rem; - letter-spacing: 0.08em; - } - - .hero-content { - grid-template-columns: minmax(0, 1.05fr) minmax(0, 0.95fr); - gap: 1.25rem; - } - - .main-text { - font-size: clamp(2.5rem, 4.5vw, 4rem); - margin-bottom: 1.25rem; - line-height: 1.15; - } - - .sub-text { - font-size: 1rem; - margin-bottom: 2rem; - } - - .hero .right img { - width: min(90%, 340px); - } -} - -/* ========== 手机(≤767px) ========== */ -@media (max-width: 767px) { - .hero .section-wrap { - gap: 1rem; - } - - .hero header { - justify-content: center; - } - - .hero-content { - grid-template-columns: 1fr; - grid-template-rows: auto auto; - gap: 1.5rem; - } - - .hero .left { - align-items: center; - text-align: center; - order: 1; - } - - .hero .right { - order: 2; - } - - .main-text { - font-size: clamp(1.85rem, 8vw, 2.75rem); - text-align: center; - } - - .sub-text { - text-align: center; - padding: 0 0.5rem; - } - - .hero .right img { - width: min(72%, 280px); - margin: 0 auto; - } - - .hero .social { - justify-content: center; - padding-top: 0.5rem; - } - - .hero .social .anlian-icon { - width: 36px; - height: 36px; - font-size: 1rem; - } -} - -@media (max-width: 576px) { - .hero header img { - width: 26px; - height: 26px; - } - - .main-text { - font-size: clamp(1.65rem, 9vw, 2.2rem); - } - - .sub-text { - font-size: 0.875rem; - } - - .hero .right img { - width: min(78%, 240px); - } -} - -@media (prefers-reduced-motion: reduce) { - .hero .right img { - animation: none; - } - - .hero .social .anlian-icon:hover { - transform: none; - } -} diff --git a/examples/anlian-mq/public/css/index/home_news_timeline.css b/examples/anlian-mq/public/css/index/home_news_timeline.css deleted file mode 100644 index 722d654..0000000 --- a/examples/anlian-mq/public/css/index/home_news_timeline.css +++ /dev/null @@ -1,461 +0,0 @@ -/** - * 首页新闻时间轴 - * - 台式(≥1025px):横向轨道,五条均分,卡片上下交错 - * - 平板(768–1024px):横向轨道,卡片横向滑动 - * - 手机(≤767px):竖向轨道,卡片左右交错 - */ - -.home-news { - --news-accent: #fdbbdb; - --news-accent-deep: #f0a8c4; - --news-accent-text: #a85878; - --news-accent-muted: #c97a96; - --timeline-axis-offset: 50%; - --bp-tablet: 1024px; - --bp-mobile: 767px; - - height: auto; - min-height: 0; - padding: 20px 0; -} - -section.home-news { - align-items: stretch; -} - -.home-news .section-wrap.home-news-stage { - display: block; - position: relative; - height: auto; - min-height: 0; - max-height: none; - overflow: visible; -} - -.home-news .news-timeline-panel, -.home-news .news-timeline-wrap, -.home-news .news-timeline { - overflow: visible; -} - -.home-news .news-title { - font-size: 1.5rem; - font-weight: 600; - margin-bottom: 1rem; - color: #111; - border-bottom: 1px solid rgba(255, 255, 255, 0.5); - padding-bottom: 0.5rem; - text-align: center; -} - -.home-news .home-news-board-bar { - margin-bottom: 1rem; -} - -/* ---------- 时间轴容器 ---------- */ -.home-news .news-timeline-wrap { - position: relative; - width: 100%; - max-width: none; - margin: 2rem 0 0; - padding: 0.5rem 0 1.5rem; - box-sizing: border-box; -} - -.home-news .news-timeline-panel { - contain: layout style; -} - -.home-news .news-timeline { - position: relative; - min-height: 13.5rem; - height: auto; - padding: 0.5rem 0 0; -} - -/* ---------- 横向轨道(台式 + 平板) ---------- */ -.home-news .news-timeline-rail { - position: absolute; - left: 1.25rem; - right: 1.25rem; - top: var(--timeline-axis-offset); - transform: translateY(-50%); - height: 3px; - width: auto; - pointer-events: none; - z-index: 0; -} - -.home-news .news-timeline-line { - display: block; - width: 100%; - height: 100%; - border-radius: 999px; - background: linear-gradient( - 90deg, - rgba(253, 189, 219, 0.35) 0%, - rgba(253, 189, 219, 0.75) 55%, - rgba(240, 168, 196, 0.9) 100% - ); - box-shadow: 0 0 10px rgba(253, 189, 219, 0.25); -} - -.home-news .news-timeline-arrow { - position: absolute; - right: -0.35rem; - top: 50%; - transform: translateY(-50%); - width: 1.5rem; - height: 1.5rem; - display: flex; - align-items: center; - justify-content: center; - color: var(--news-accent-deep); - font-size: 0.85rem; - filter: drop-shadow(0 1px 3px rgba(253, 189, 219, 0.45)); -} - -.home-news .news-timeline-arrow .news-timeline-arrow-icon--down { - display: none; -} - -.home-news .news-timeline-items { - list-style: none; - margin: 0; - padding: 0 0.5rem; - display: flex; - align-items: stretch; - justify-content: space-between; - gap: 0.65rem; - position: relative; - z-index: 1; - min-height: 13.5rem; -} - -.home-news .news-timeline-item { - flex: 1 1 0; - min-width: 0; - max-width: 11.5rem; - display: grid; - grid-template-rows: 1fr auto 1fr; - grid-template-columns: none; - align-items: center; - justify-items: center; -} - -.home-news .news-timeline-node { - grid-row: 2; - grid-column: auto; - width: 12px; - height: 12px; - border-radius: 50%; - background: rgba(255, 255, 255, 0.85); - border: 2px solid var(--news-accent-deep); - box-shadow: - 0 0 0 3px rgba(253, 189, 219, 0.25), - 0 2px 8px rgba(253, 189, 219, 0.35); - flex-shrink: 0; - z-index: 2; - transition: transform 0.2s ease, box-shadow 0.2s ease; -} - -.home-news .news-timeline-item:nth-child(odd) .news-timeline-card { - grid-row: 1; - grid-column: auto; - align-self: end; - margin: 0 0 0.45rem; -} - -.home-news .news-timeline-item:nth-child(even) .news-timeline-card { - grid-row: 3; - grid-column: auto; - align-self: start; - margin: 0.45rem 0 0; -} - -.home-news .news-timeline-item:hover .news-timeline-node { - transform: scale(1.15); - box-shadow: - 0 0 0 4px rgba(253, 189, 219, 0.35), - 0 4px 12px rgba(253, 189, 219, 0.4); -} - -.home-news .news-timeline-card { - width: 100%; - padding: 0.65rem 0.75rem; - border-radius: 14px; - background: rgba(255, 255, 255, 0.38); - backdrop-filter: blur(16px); - -webkit-backdrop-filter: blur(16px); - border: 1px solid rgba(255, 255, 255, 0.42); - box-shadow: 0 6px 20px rgba(253, 189, 219, 0.12); - transition: transform 0.2s ease, box-shadow 0.2s ease, background 0.2s ease; -} - -.home-news .news-timeline-item:nth-child(odd):hover .news-timeline-card { - transform: translateY(-4px); - background: rgba(255, 255, 255, 0.52); - box-shadow: 0 10px 28px rgba(253, 189, 219, 0.22); -} - -.home-news .news-timeline-item:nth-child(even):hover .news-timeline-card { - transform: translateY(4px); - background: rgba(255, 255, 255, 0.52); - box-shadow: 0 10px 28px rgba(253, 189, 219, 0.22); -} - -.home-news .news-timeline-meta { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 0.35rem 0.5rem; - margin-bottom: 0.35rem; -} - -.home-news .news-timeline-date { - font-size: 0.6875rem; - font-weight: 700; - color: var(--news-accent-muted); - white-space: nowrap; -} - -.home-news .news-timeline-board { - font-size: 0.625rem; - font-weight: 600; - color: var(--news-accent-text); - background: rgba(253, 189, 219, 0.22); - padding: 0.1rem 0.35rem; - border-radius: 3px; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - max-width: 100%; -} - -.home-news .news-timeline-title { - margin: 0; - min-width: 0; -} - -.home-news .news-timeline-link { - display: -webkit-box; - -webkit-box-orient: vertical; - -webkit-line-clamp: 2; - overflow: hidden; - font-size: 0.8125rem; - font-weight: 600; - line-height: 1.35; - color: #222; - text-decoration: none; -} - -.home-news .news-timeline-link:hover { - color: var(--news-accent-text); -} - -.home-news .news-timeline-empty { - margin: 0; - text-align: center; - color: #666; - font-size: 0.9rem; -} - -.home-news .news-timeline-item-empty { - flex: 1 1 100%; - max-width: none; - grid-template-rows: auto; - grid-template-columns: 1fr; -} - -.home-news .news-timeline-item-empty .news-timeline-card { - grid-row: 1; - grid-column: 1; - margin: 0; -} - -.home-news .news-timeline-wrap::before { - content: ""; - position: absolute; - left: 5%; - right: 5%; - top: var(--timeline-axis-offset); - transform: translateY(-50%); - height: 70%; - background: radial-gradient( - ellipse 85% 100% at 50% 50%, - rgba(253, 189, 219, 0.18) 0%, - transparent 72% - ); - pointer-events: none; - z-index: 0; -} - -/* ========== 平板(768px–1024px):横向轨道 + 卡片横滑 ========== */ -@media (max-width: 1024px) { - .home-news .news-timeline-wrap { - margin-top: 1.75rem; - } - - .home-news .news-timeline { - min-height: 12rem; - } - - .home-news .news-timeline-items { - justify-content: flex-start; - flex-wrap: nowrap; - gap: 0.75rem; - min-height: 12rem; - overflow-x: auto; - overflow-y: visible; - scroll-snap-type: x proximity; - -webkit-overflow-scrolling: touch; - padding: 0 0.5rem 0.5rem; - scrollbar-width: thin; - scrollbar-color: rgba(253, 189, 219, 0.5) transparent; - } - - .home-news .news-timeline-items::-webkit-scrollbar { - height: 5px; - } - - .home-news .news-timeline-items::-webkit-scrollbar-thumb { - background: rgba(253, 189, 219, 0.45); - border-radius: 999px; - } - - .home-news .news-timeline-item { - flex: 0 0 auto; - width: min(10.5rem, 38vw); - max-width: 11rem; - scroll-snap-align: center; - } - - .home-news .news-timeline-rail { - left: 0.75rem; - right: 0.75rem; - } -} - -/* ========== 手机(≤767px):竖向时间轴 ========== */ -@media (max-width: 767px) { - .home-news .news-timeline-wrap { - margin-top: 1.5rem; - } - - .home-news .news-timeline-wrap::before { - left: 50%; - right: auto; - top: 4%; - bottom: 4%; - width: min(18rem, 72%); - height: auto; - transform: translateX(-50%); - background: radial-gradient( - ellipse 70% 90% at 50% 50%, - rgba(253, 189, 219, 0.2) 0%, - transparent 72% - ); - } - - .home-news .news-timeline { - min-height: 0; - padding: 0.25rem 0 0.5rem; - } - - .home-news .news-timeline-rail { - left: 50%; - right: auto; - top: 0.35rem; - bottom: 0.65rem; - width: 3px; - height: auto; - transform: translateX(-50%); - } - - .home-news .news-timeline-line { - width: 100%; - height: 100%; - background: linear-gradient( - 180deg, - rgba(253, 189, 219, 0.35) 0%, - rgba(253, 189, 219, 0.75) 55%, - rgba(240, 168, 196, 0.9) 100% - ); - } - - .home-news .news-timeline-arrow { - left: 50%; - right: auto; - top: auto; - bottom: -0.6rem; - transform: translateX(-50%); - } - - .home-news .news-timeline-arrow .news-timeline-arrow-icon--right { - display: none; - } - - .home-news .news-timeline-arrow .news-timeline-arrow-icon--down { - display: block; - } - - .home-news .news-timeline-items { - flex-direction: column; - align-items: stretch; - gap: 1.25rem; - min-height: 0; - padding: 0.35rem 0.5rem 1.25rem; - overflow: visible; - scroll-snap-type: none; - } - - .home-news .news-timeline-item { - flex: none; - width: 100%; - max-width: none; - display: grid; - grid-template-columns: minmax(0, 1fr) 12px minmax(0, 1fr); - grid-template-rows: auto; - column-gap: 0.55rem; - } - - .home-news .news-timeline-node { - grid-row: 1; - grid-column: 2; - justify-self: center; - } - - .home-news .news-timeline-item:nth-child(odd) .news-timeline-card { - grid-row: 1; - grid-column: 3; - align-self: center; - margin: 0; - } - - .home-news .news-timeline-item:nth-child(even) .news-timeline-card { - grid-row: 1; - grid-column: 1; - align-self: center; - margin: 0; - } - - .home-news .news-timeline-item:nth-child(odd):hover .news-timeline-card { - transform: translateX(4px); - } - - .home-news .news-timeline-item:nth-child(even):hover .news-timeline-card { - transform: translateX(-4px); - } - - .home-news .news-timeline-item-empty { - grid-template-columns: 1fr; - } - - .home-news .news-timeline-card { - padding: 0.6rem 0.65rem; - } - - .home-news .news-timeline-link { - font-size: 0.78rem; - } -} diff --git a/examples/anlian-mq/public/css/index/home_posts.css b/examples/anlian-mq/public/css/index/home_posts.css deleted file mode 100644 index 2c31305..0000000 --- a/examples/anlian-mq/public/css/index/home_posts.css +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 首页「论坛交流」区块(共用样式见 feed_common.css,由模板单独引入) - */ - -/* 覆盖 index.css 的 100vh / 80vh,使 10 条帖子完整展示 */ -section.home-posts { - height: auto; - min-height: 0; - align-items: stretch; -} - -.home-posts { - padding: 20px 0 28px; -} - -.home-posts .section-wrap.home-posts-stage { - display: block; - background-color: rgba(255, 255, 255, 0.14); - height: auto; - min-height: 0; - max-height: none; - overflow: visible; -} - -.home-posts-panel, -#tenPostContainer { - overflow: visible; -} - -.home-posts-title { - margin: 0 0 1.25rem; - font-size: 1.5rem; - font-weight: 600; - color: #111; - text-align: center; - border-bottom: 1px solid rgba(255, 255, 255, 0.45); - padding-bottom: 0.65rem; -} - -.home-posts-board-bar { - margin-bottom: 1.25rem; -} - -.home-posts-panel { - contain: layout style; -} diff --git a/examples/anlian-mq/public/css/index/notice.css b/examples/anlian-mq/public/css/index/notice.css deleted file mode 100644 index 9abe800..0000000 --- a/examples/anlian-mq/public/css/index/notice.css +++ /dev/null @@ -1,349 +0,0 @@ -/* ========== 原有基础样式保留(略作优化) ========== */ -/* 公告标题样式 */ -.notice-title { - font-size: 1.5rem; - font-weight: 600; - margin-bottom: 1.5rem; - color: #212529; - border-bottom: 1px solid rgba(255, 255, 255, 0.3); - padding-bottom: 0.5rem; - text-align: center; - /* 新增:确保标题在小屏不溢出 */ - width: 100%; - box-sizing: border-box; -} - -/* 公告内容article样式 - 居中显示 */ -.notice-item>article { - text-align: center; - padding: 1.5rem; - background-color: rgba(255, 255, 255, 0.1); - border-radius: 0.5rem; - word-wrap: break-word; - min-height: 100px; - display: block; - position: relative; - width: 100%; - margin-bottom: 0; - box-sizing: border-box; /* 新增:内边距计入宽度 */ -} - -/* 确保article内部HTML内容正常显示 */ -.notice-item>article * { - text-align: center; - margin: 0.5rem 0; - max-width: 100%; - word-wrap: break-word; -} - -/* 为article内部元素添加基础样式 */ -.notice-item>article p { - line-height: 1.6; - margin-bottom: 1rem; -} - -.notice-item>article h1, -.notice-item>article h2, -.notice-item>article h3 { - font-weight: 600; - margin-top: 1rem; - margin-bottom: 0.5rem; -} - -.notice-item>article ul, -.notice-item>article ol { - padding-left: 1.5rem; - margin-bottom: 1rem; -} - -.notice-item>article li { - margin-bottom: 0.5rem; -} - -/* 公告时间样式 - 放在右下角 */ -.notice-item>.notice-create-time { - font-size: 0.85rem; - color: #6c757d; - margin-bottom: 0; - position: absolute; - bottom: 1rem; - right: 1rem; - white-space: nowrap; - /* 新增:小屏时调整位置,避免溢出 */ - z-index: 2; -} - -/* 定义外层容器样式 */ -.notice-content-container { - position: absolute; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - /* 初始尺寸(大屏) */ - width: 60vw; - height: 50vw; - margin: 0; - color: rgb(0, 0, 0); - perspective: 1000px; - transform-origin: center; - /* 新增:确保容器不会溢出父元素 */ - max-width: 600px; - max-height: 500px; - box-sizing: border-box; -} - -/* 定义内容容器样式 */ -.notice-list { - display: flex; - justify-content: center; - align-items: center; - position: absolute; - width: 100%; - height: 100%; - transform-origin: center; - transform-style: preserve-3d; - transform: translateZ(-30vw) rotateY(0); - animation: carousel 9s infinite cubic-bezier(0.77, 0, 0.175, 1) forwards; -} - -/* 定义项目样式 */ -.notice-item { - position: absolute; - /* 初始尺寸(大屏) */ - width: 60vw; - height: 40vw; - max-width: 380px; - max-height: 250px; - box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3); - border-radius: 6px; - background-size: cover; - -webkit-box-reflect: below 25px -webkit-linear-gradient(transparent 50%, rgba(255, 255, 255, 0.3)); - /* 新增:小屏时调整倒影,避免遮挡 */ - box-sizing: border-box; -} - -/* 第一个项目样式 */ -.notice-item:nth-child(1) { - transform: rotateY(0) translateZ(35vw); -} - -/* 第二个项目样式 */ -.notice-item:nth-child(2) { - transform: rotateY(120deg) translateZ(35vw); -} - -/* 第三个项目样式 */ -.notice-item:nth-child(3) { - transform: rotateY(240deg) translateZ(35vw); -} - -/* 定义动画 */ -@keyframes carousel { - 0%, - 17.5% { - transform: translateZ(-35vw) rotateY(0); - } - 27.5%, - 45% { - transform: translateZ(-35vw) rotateY(-120deg); - } - 55%, - 72.5% { - transform: translateZ(-35vw) rotateY(-240deg); - } - 82.5%, - 100% { - transform: translateZ(-35vw) rotateY(-360deg); - } -} - -/* ========== 新增响应式设计(核心) ========== */ -/* 1. 平板横向/大屏手机 (≤ 992px) */ -@media (max-width: 992px) { - /* 调整公告容器尺寸 */ - .notice-content-container { - width: 70vw; - height: 60vw; - max-width: 500px; - max-height: 400px; - } - - /* 调整轮播项尺寸 */ - .notice-item { - width: 70vw; - height: 45vw; - max-width: 350px; - max-height: 220px; - } - - /* 调整3D平移距离,适配尺寸 */ - .notice-list { - transform: translateZ(-35vw) rotateY(0); - } - .notice-item:nth-child(1), - .notice-item:nth-child(2), - .notice-item:nth-child(3) { - transform: rotateY(var(--rotate-deg)) translateZ(40vw); - } - @keyframes carousel { - 0%, 17.5% { transform: translateZ(-40vw) rotateY(0); } - 27.5%, 45% { transform: translateZ(-40vw) rotateY(-120deg); } - 55%, 72.5% { transform: translateZ(-40vw) rotateY(-240deg); } - 82.5%, 100% { transform: translateZ(-40vw) rotateY(-360deg); } - } - - /* 调整标题和内容字体 */ - .notice-title { - font-size: 1.3rem; - margin-bottom: 1rem; - } - .notice-item>article { - padding: 1.2rem; - min-height: 80px; - } - .notice-item>article p { - font-size: 0.95rem; - line-height: 1.5; - } - .notice-create-time { - font-size: 0.8rem; - bottom: 0.8rem; - right: 0.8rem; - } -} - -/* 2. 平板竖向/中屏手机 (≤ 768px) */ -@media (max-width: 768px) { - /* 进一步调整容器尺寸 */ - .notice-content-container { - width: 80vw; - height: 70vw; - max-width: 400px; - max-height: 350px; - /* 小屏时微调定位,避免偏上 */ - top: 55%; - } - - /* 调整轮播项尺寸 */ - .notice-item { - width: 80vw; - height: 50vw; - max-width: 320px; - max-height: 200px; - /* 减小阴影,适配小屏 */ - box-shadow: 0 3px 15px rgba(0, 0, 0, 0.2); - /* 减小倒影高度,避免遮挡 */ - -webkit-box-reflect: below 15px -webkit-linear-gradient(transparent 60%, rgba(255, 255, 255, 0.2)); - } - - /* 调整3D平移距离 */ - .notice-list { - transform: translateZ(-40vw) rotateY(0); - } - .notice-item:nth-child(1), - .notice-item:nth-child(2), - .notice-item:nth-child(3) { - transform: rotateY(var(--rotate-deg)) translateZ(45vw); - } - @keyframes carousel { - 0%, 17.5% { transform: translateZ(-45vw) rotateY(0); } - 27.5%, 45% { transform: translateZ(-45vw) rotateY(-120deg); } - 55%, 72.5% { transform: translateZ(-45vw) rotateY(-240deg); } - 82.5%, 100% { transform: translateZ(-45vw) rotateY(-360deg); } - } - - /* 调整文字样式 */ - .notice-title { - font-size: 1.2rem; - padding-bottom: 0.4rem; - } - .notice-item>article { - padding: 1rem; - min-height: 70px; - } - .notice-item>article h1, - .notice-item>article h2, - .notice-item>article h3 { - font-size: 1.1rem; - margin-top: 0.8rem; - } -} - -/* 3. 小屏手机 (≤ 576px) */ -@media (max-width: 576px) { - /* 极致适配小屏 */ - .notice-content-container { - width: 90vw; - height: 80vw; - max-width: 350px; - max-height: 300px; - top: 55%; - /* 减小透视距离,避免轮播项超出屏幕 */ - perspective: 800px; - } - - /* 轮播项适配 */ - .notice-item { - width: 90vw; - height: 55vw; - max-width: 300px; - max-height: 180px; - box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15); - -webkit-box-reflect: below 10px -webkit-linear-gradient(transparent 70%, rgba(255, 255, 255, 0.1)); - } - - /* 调整3D平移距离(关键:避免轮播项出屏) */ - .notice-list { - transform: translateZ(-45vw) rotateY(0); - } - .notice-item:nth-child(1) { - transform: rotateY(0) translateZ(50vw); - } - .notice-item:nth-child(2) { - transform: rotateY(120deg) translateZ(50vw); - } - .notice-item:nth-child(3) { - transform: rotateY(240deg) translateZ(50vw); - } - @keyframes carousel { - 0%, 17.5% { transform: translateZ(-50vw) rotateY(0); } - 27.5%, 45% { transform: translateZ(-50vw) rotateY(-120deg); } - 55%, 72.5% { transform: translateZ(-50vw) rotateY(-240deg); } - 82.5%, 100% { transform: translateZ(-50vw) rotateY(-360deg); } - } - - /* 文字极致适配 */ - .notice-title { - font-size: 1.1rem; - margin-bottom: 0.8rem; - } - .notice-item>article { - padding: 0.8rem; - min-height: 60px; - border-radius: 0.3rem; - } - .notice-item>article p { - font-size: 0.85rem; - line-height: 1.4; - margin-bottom: 0.8rem; - } - .notice-create-time { - font-size: 0.75rem; - bottom: 0.5rem; - right: 0.5rem; - /* 小屏时背景半透,避免文字看不清 */ - background-color: rgba(255, 255, 255, 0.2); - padding: 0.2rem 0.4rem; - border-radius: 0.2rem; - } - /* 隐藏过长的列表项符号,避免溢出 */ - .notice-item>article ul, - .notice-item>article ol { - padding-left: 1rem; - } -} - -/* 补充:修复CSS变量(可选,增强兼容性) */ -.notice-item:nth-child(1) { --rotate-deg: 0deg; } -.notice-item:nth-child(2) { --rotate-deg: 120deg; } -.notice-item:nth-child(3) { --rotate-deg: 240deg; } \ No newline at end of file diff --git a/examples/anlian-mq/public/css/login.css b/examples/anlian-mq/public/css/login.css deleted file mode 100644 index 390470f..0000000 --- a/examples/anlian-mq/public/css/login.css +++ /dev/null @@ -1,128 +0,0 @@ -/* 登录 / 注册页:在 anlian_forms.css 之上的薄封装 */ - -.page-title { - margin: 0 0 1.25rem; - font-size: 1.75rem; - font-weight: 700; - color: var(--anlian-text, #222); - text-align: center; -} - -.login-container { - width: 100%; - max-width: 440px; -} - -.text-center.text-muted, -.anlian-page-lead { - margin: -0.25rem 0 1.25rem; - font-size: 0.9rem; - color: var(--anlian-text-muted, #666); - text-align: center; - line-height: 1.5; -} - -.mb-3 { - margin-bottom: 1rem; -} - -/* 注册页旧类名兼容 */ -.auth-code-row, -.anlian-code-row { - display: flex; - gap: 0.5rem; - align-items: stretch; -} - -.auth-code-row .form-control, -.anlian-code-row input { - flex: 1; - min-width: 0; -} - -.btn-send-code, -.anlian-btn-send-code { - flex-shrink: 0; - align-self: stretch; - padding: 0 1rem; - border: 1px solid rgba(253, 189, 219, 0.5); - border-radius: 12px; - background: rgba(253, 189, 219, 0.32); - color: var(--anlian-accent-text, #a85878); - font-size: 0.8125rem; - font-weight: 600; - cursor: pointer; - white-space: nowrap; - transition: background 0.2s ease; -} - -.btn-send-code:hover:not(:disabled), -.anlian-btn-send-code:hover:not(:disabled) { - background: rgba(253, 189, 219, 0.48); -} - -.btn-send-code:disabled, -.anlian-btn-send-code:disabled { - opacity: 0.55; - cursor: not-allowed; -} - -.field-hint, -.anlian-field-hint { - display: block; - margin-top: 0.35rem; - font-size: 0.75rem; - color: var(--anlian-text-muted, #666); -} - -.field-error, -.anlian-field-error { - display: block; - margin-top: 0.35rem; - font-size: 0.8125rem; - color: #b33a4d; -} - -.alert-danger, -.anlian-alert-danger { - padding: 0.85rem 1rem; - margin-bottom: 1rem; - border-radius: 12px; - font-size: 0.875rem; - background: rgba(220, 80, 100, 0.12); - border: 1px solid rgba(220, 80, 100, 0.28); - color: #9e3a4a; -} - -.form-links, -.anlian-form-links { - display: flex; - justify-content: center; - gap: 1rem; - margin-top: 1.25rem; - flex-wrap: wrap; -} - -.form-links a, -.anlian-form-links a { - font-size: 0.875rem; - font-weight: 500; - color: var(--anlian-accent-text, #a85878); - text-decoration: none; -} - -.form-links a:hover, -.anlian-form-links a:hover { - text-decoration: underline; -} - -@media (max-width: 576px) { - .auth-code-row { - flex-direction: column; - } - - .btn-send-code { - width: 100%; - padding: 0.65rem; - } -} diff --git a/examples/anlian-mq/public/css/navbar_search.css b/examples/anlian-mq/public/css/navbar_search.css deleted file mode 100644 index 5276eb4..0000000 --- a/examples/anlian-mq/public/css/navbar_search.css +++ /dev/null @@ -1,80 +0,0 @@ -/** - * 导航栏搜索框 — 粉色主题 - */ - -.navbar-search { - gap: 0.45rem; - align-items: stretch; - flex-shrink: 1; - min-width: 0; -} - -.navbar-search .form-control { - min-width: 8.5rem; - max-width: 11.5rem; - padding: 0.45rem 0.85rem; - font-size: 0.875rem; - line-height: 1.35; - color: #f5f5f5; - background: rgba(255, 255, 255, 0.14); - border: 1px solid rgba(253, 189, 219, 0.45); - border-radius: 999px; - transition: background 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease; -} - -.navbar-search .form-control::placeholder { - color: rgba(255, 255, 255, 0.55); -} - -.navbar-search .form-control:focus { - color: #fff; - background: rgba(255, 255, 255, 0.22); - border-color: rgba(253, 189, 219, 0.75); - box-shadow: 0 0 0 2px rgba(253, 189, 219, 0.28); - outline: none; -} - -.navbar-search .btn-search-submit { - flex-shrink: 0; - padding: 0.45rem 0.95rem; - font-size: 0.8125rem; - font-weight: 600; - line-height: 1.35; - color: #a85878; - white-space: nowrap; - background: linear-gradient(135deg, rgba(253, 189, 219, 0.92), rgba(240, 168, 196, 0.95)); - border: 1px solid rgba(255, 255, 255, 0.35); - border-radius: 999px; - transition: box-shadow 0.2s ease, transform 0.2s ease, filter 0.2s ease; -} - -.navbar-search .btn-search-submit:hover { - color: #8a4560; - background: linear-gradient(135deg, rgba(253, 189, 219, 1), rgba(240, 168, 196, 1)); - border-color: rgba(255, 255, 255, 0.5); - box-shadow: 0 3px 14px rgba(253, 189, 219, 0.35); - transform: translateY(-1px); -} - -@media (max-width: 991.98px) { - .navbar-search { - width: 100%; - margin: 0.5rem 0; - } - - .navbar-search .form-control { - flex: 1; - max-width: none; - min-width: 0; - } - - .navbar-search .btn-search-submit { - padding: 0.45rem 1.1rem; - } -} - -@media (max-width: 576px) { - .navbar-search .btn-search-submit { - flex: 1; - } -} diff --git a/examples/anlian-mq/public/css/post_detail.css b/examples/anlian-mq/public/css/post_detail.css deleted file mode 100644 index f4746e4..0000000 --- a/examples/anlian-mq/public/css/post_detail.css +++ /dev/null @@ -1,289 +0,0 @@ -/* - * @File: post_detail.css - * @Description: 帖子详情页专用样式文件,实现了内容的清晰排版、评论区美化及响应式适配。 - * @Author: Your Name - * @Date: 2023-10-27 - */ - -:root { - --bs-heading-color: #1a1a1a; - --post-detail-sidebar-break: 1200px; -} - -/* 宽屏:左作者卡片 + 居中正文(右侧留空平衡) */ -body.page-post-detail .main-container { - max-width: none; - width: 100%; - padding-left: 1rem; - padding-right: 1rem; - margin-left: auto; - margin-right: auto; -} - -.post-detail-shell { - display: grid; - grid-template-columns: 1fr min(900px, 100%) 1fr; - align-items: start; - width: 100%; -} - -.post-detail-aside { - grid-column: 1; - justify-self: end; - width: min(268px, 100%); - margin-top: 2rem; - padding-right: 1.5rem; - position: sticky; - top: 1.25rem; -} - -/* 作者卡片:玻璃质感 + 纵向对齐,hover 仅上浮不做倾斜 */ -.post-author-card { - position: relative; - display: flex; - flex-direction: column; - align-items: stretch; - gap: 0.7rem; - width: 100%; - padding: 1.35rem 1.15rem 1.2rem; - border-radius: 20px; - background: rgba(255, 255, 255, 0.12); - backdrop-filter: blur(12px); - border: 1px solid rgba(255, 255, 255, 0.5); - border-top: 1px solid rgba(255, 255, 255, 0.75); - border-left: 1px solid rgba(255, 255, 255, 0.75); - box-shadow: 0 22px 42px rgba(0, 0, 0, 0.07); - font-family: 'Poppins', sans-serif; - transition: transform 0.45s cubic-bezier(0.22, 1, 0.36, 1), - box-shadow 0.45s ease, - background 0.35s ease; - overflow: hidden; -} - -.post-author-card__quote { - position: absolute; - top: 10px; - left: 10px; - width: 52px; - height: 52px; - border-radius: 10px; - background: rgba(255, 255, 255, 0.1) url(https://s3.cflmy.cn/cflmy/left-quote.png) center / 40px no-repeat; - border: 1px solid rgba(255, 255, 255, 0.45); - opacity: 0; - transition: opacity 0.4s ease; - pointer-events: none; -} - -.post-author-card__avatar { - align-self: center; - position: relative; - z-index: 1; - padding: 9px; - border-radius: 14px; - background: rgba(255, 255, 255, 0.14); - backdrop-filter: blur(6px); - border: 1px solid rgba(255, 255, 255, 0.55); - border-top: 1px solid rgba(255, 255, 255, 0.75); - box-shadow: 0 14px 28px rgba(0, 0, 0, 0.08); - transition: transform 0.45s cubic-bezier(0.22, 1, 0.36, 1), - box-shadow 0.45s ease; -} - -.post-author-card__avatar--link { - text-decoration: none; - color: inherit; - cursor: pointer; -} - -.post-author-card__avatar--link:focus-visible { - outline: 2px solid rgba(168, 88, 120, 0.75); - outline-offset: 3px; -} - -.post-author-card__avatar img { - display: block; - width: 88px; - height: 88px; - border-radius: 10px; - object-fit: cover; - border: 1px solid rgba(255, 255, 255, 0.45); -} - -.post-author-card__name { - margin: 0; - padding: 0.15rem 0.25rem 0; - text-align: center; - font-size: 1.05rem; - font-weight: 600; - color: #644651; - word-break: break-word; - transition: color 0.3s ease; -} - -.post-author-card__body { - display: flex; - flex-direction: column; - align-items: center; - padding: 0 0.25rem 0.15rem; - text-align: center; - transition: transform 0.45s cubic-bezier(0.22, 1, 0.36, 1); -} - -.post-author-card__signature { - margin: 0; - color: #644651; - font-size: 0.82rem; - line-height: 1.55; -} - -.post-author-card__signature--empty { - color: #9a8490; - font-style: italic; -} - -.post-author-card:hover { - transform: translateY(-7px); - background: rgba(255, 255, 255, 0.16); - box-shadow: 0 30px 52px rgba(0, 0, 0, 0.11); -} - -.post-author-card:hover .post-author-card__quote { - opacity: 0.85; -} - -.post-author-card:hover .post-author-card__avatar { - transform: translateY(-5px) scale(1.03); - box-shadow: 0 18px 34px rgba(0, 0, 0, 0.11); -} - -.post-author-card:hover .post-author-card__name { - color: #4a3340; -} - -.post-author-card:hover .post-author-card__body { - transform: translateY(-2px); -} - -.post-author-card:hover .post-author-card__signature { - color: #4a3340; -} - -/* --- 1. 页面布局与容器样式 --- */ -.main-container { - width: 100%; - max-width: 900px; - margin: 2rem auto; - padding: 0 1rem; -} - -body.page-post-detail .main-container { - margin-top: 2rem; - margin-bottom: 2rem; -} - -.post-detail { - grid-column: 2; - background-color: rgba(255, 255, 255, 0.2); - backdrop-filter: blur(24px); - border: 1px solid rgba(255, 255, 255, 0.2); - box-shadow: inset 0 0 5px rgba(255, 255, 255, 0.1); - border-radius: 30px; - padding: 50px 100px; - transition: all 0.3s ease; -} - -/* --- 2. 帖子头部元信息(非主体)样式 --- */ -.post-detail h2 { - font-size: 2rem; - font-weight: 700; - color: #212529; /* 标题偏深但非纯黑,低于主体优先级 */ - margin-bottom: 1.5rem; - line-height: 1.4; -} - -/* 详情页顶栏元信息(仅直接子级 p,勿用 :first-of-type,否则会误伤 article) */ -.post-detail > p.post-content { - display: flex; - flex-wrap: wrap; - gap: 0.5rem 1.5rem; - font-size: 0.9rem; - margin-bottom: 2rem; - padding-bottom: 1rem; - border-bottom: 1px solid #e9ecef; -} - -.post-author-profile a { - color: #a85878; - text-decoration: none; - font-weight: 500; -} - -.post-author-profile a:hover { - text-decoration: underline; -} - -/* --- 3. 帖子/新闻正文卡片 --- */ -article.anlian-rich-content, -article.post-content.anlian-rich-content, -article.news-content.anlian-rich-content { - display: block; - margin-bottom: 3rem; - background-color: rgba(255, 255, 255, 0.45); - padding: 2.2rem; - border-radius: 1rem; - box-shadow: 0 3px 10px rgba(0, 0, 0, 0.06); -} - -/* 主体内图片样式见 rich_content.css */ - -/* 评论表单由 anlian_forms.css 统一;此处仅保留错误列表 */ -.post-detail .error-messages { - list-style: none; - padding: 0; - margin: 0 0 1rem; - color: #b33a4d; - font-size: 0.875rem; -} - -.post-detail .text-muted a { - color: #a85878; - font-weight: 500; -} - -.post-detail .anlian-comment-form { - margin-bottom: 1.75rem; -} - -/* --- 5. 响应式适配:主体字号同步调整,保持区分度 --- */ -@media (max-width: 1199.98px) { - .post-detail-aside { - display: none; - } - - .post-detail-shell { - display: block; - } - - body.page-post-detail .main-container { - max-width: 900px; - } -} - -@media (max-width: 767.98px) { - .main-container { - margin: 1rem auto; - } - .post-detail { - padding: 1.5rem; - } - - .post-detail h2 { - font-size: 1.75rem; - } - - /* 移动端正文卡片 */ - article.anlian-rich-content, - article.post-content.anlian-rich-content { - padding: 1.5rem; - } -} \ No newline at end of file diff --git a/examples/anlian-mq/public/css/public_post.css b/examples/anlian-mq/public/css/public_post.css deleted file mode 100644 index 73c45ce..0000000 --- a/examples/anlian-mq/public/css/public_post.css +++ /dev/null @@ -1,27 +0,0 @@ -/* 发帖 / 发新闻编辑页 */ - -.anlian-publish-page { - max-width: 800px; - margin: 0 auto; - padding: 1.5rem 1rem 2.5rem; - box-sizing: border-box; -} - -.anlian-publish-page .anlian-page-title { - margin-bottom: 1.25rem; -} - -.anlian-publish-page .anlian-form-card { - padding: 2rem 1.75rem; -} - -.anlian-publish-page .anlian-editor-wrap { - margin-top: 0.25rem; - min-height: 360px; -} - -@media (max-width: 576px) { - .anlian-publish-page .anlian-form-card { - padding: 1.35rem 1.15rem; - } -} diff --git a/examples/anlian-mq/public/css/rich_content.css b/examples/anlian-mq/public/css/rich_content.css deleted file mode 100644 index f39f10d..0000000 --- a/examples/anlian-mq/public/css/rich_content.css +++ /dev/null @@ -1,131 +0,0 @@ -/** - * 富文本正文 — 编辑器与详情页共用,保证 Enter 换行所见即所得 - */ - -:root { - --anlian-rich-font-size: 1.2rem; - --anlian-rich-line-height: 1.85; - --anlian-rich-color: #000; - --anlian-rich-weight: 450; - /* Enter 新段落:约半行间距,接近自然换行 */ - --anlian-rich-p-gap: 0.28em; - /* 空行(


    ):略大于段内换行 */ - --anlian-rich-blank-gap: 0.55em; -} - -/* 详情页正文 + wangEditor 编辑区 */ -.anlian-rich-content, -.anlian-editor-wrap .w-e-text-container .w-e-text { - display: block; - font-size: var(--anlian-rich-font-size) !important; - line-height: var(--anlian-rich-line-height) !important; - color: var(--anlian-rich-color) !important; - font-weight: var(--anlian-rich-weight); - word-wrap: break-word; - overflow-wrap: break-word; -} - -.anlian-rich-content p, -.anlian-editor-wrap .w-e-text-container .w-e-text p { - display: block; - margin: 0 0 var(--anlian-rich-p-gap); - padding: 0; -} - -.anlian-rich-content p:last-child, -.anlian-editor-wrap .w-e-text-container .w-e-text p:last-child { - margin-bottom: 0; -} - -/* 连按 Enter 产生的空行 */ -.anlian-rich-content p:empty, -.anlian-rich-content p:has(> br:only-child), -.anlian-editor-wrap .w-e-text-container .w-e-text p:empty, -.anlian-editor-wrap .w-e-text-container .w-e-text p:has(> br:only-child) { - margin: 0 0 var(--anlian-rich-blank-gap); - min-height: var(--anlian-rich-blank-gap); - line-height: var(--anlian-rich-blank-gap); -} - -.anlian-rich-content h1, -.anlian-rich-content h2, -.anlian-rich-content h3, -.anlian-rich-content h4, -.anlian-editor-wrap .w-e-text-container .w-e-text h1, -.anlian-editor-wrap .w-e-text-container .w-e-text h2, -.anlian-editor-wrap .w-e-text-container .w-e-text h3, -.anlian-editor-wrap .w-e-text-container .w-e-text h4 { - display: block; - margin: 0.75em 0 0.35em; - font-weight: 700; - line-height: 1.4; - color: var(--anlian-rich-color); -} - -.anlian-rich-content h1:first-child, -.anlian-rich-content h2:first-child, -.anlian-editor-wrap .w-e-text-container .w-e-text h1:first-child, -.anlian-editor-wrap .w-e-text-container .w-e-text h2:first-child { - margin-top: 0; -} - -.anlian-rich-content a, -.anlian-editor-wrap .w-e-text-container .w-e-text a { - color: #a85878; - text-decoration: underline; -} - -.anlian-rich-content blockquote, -.anlian-editor-wrap .w-e-text-container .w-e-text blockquote { - margin: 0.5em 0; - padding: 0.35em 0 0.35em 1em; - border-left: 3px solid rgba(253, 189, 219, 0.85); - color: #333; -} - -.anlian-rich-content ul, -.anlian-rich-content ol, -.anlian-editor-wrap .w-e-text-container .w-e-text ul, -.anlian-editor-wrap .w-e-text-container .w-e-text ol { - margin: 0.35em 0; - padding-left: 1.5em; -} - -.anlian-rich-content li, -.anlian-editor-wrap .w-e-text-container .w-e-text li { - margin: 0.15em 0; -} - -.anlian-rich-content img, -.anlian-editor-wrap .w-e-text-container .w-e-text img { - max-width: 80%; - max-height: 600px; - height: auto; - display: block; - margin: 1em auto; - border-radius: 0.8rem; - box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); -} - -/* 编辑区内边距,接近详情页正文卡片 */ -.anlian-editor-wrap .w-e-text-container .w-e-text { - padding: 1.25rem 1.5rem !important; - min-height: 280px; - box-sizing: border-box; -} - -@media (max-width: 767.98px) { - :root { - --anlian-rich-font-size: 1.15rem; - } - - .anlian-rich-content img, - .anlian-editor-wrap .w-e-text-container .w-e-text img { - max-width: 95%; - } - - .anlian-editor-wrap .w-e-text-container .w-e-text { - padding: 1rem 1.1rem !important; - min-height: 240px; - } -} diff --git a/examples/anlian-mq/public/css/search.css b/examples/anlian-mq/public/css/search.css deleted file mode 100644 index 3b031ed..0000000 --- a/examples/anlian-mq/public/css/search.css +++ /dev/null @@ -1,363 +0,0 @@ -/** - * 全站搜索页 — 粉色毛玻璃主题(与 anlian_forms / feed 一致) - */ - -.search-page { - --search-accent: #fdbbdb; - --search-accent-deep: #f0a8c4; - --search-accent-text: #a85878; - --search-muted: #888; - --search-radius: 18px; - --search-glass: rgba(255, 255, 255, 0.42); - --search-ring: rgba(253, 189, 219, 0.48); - - width: min(100% - 2rem, 920px); - margin: 0 auto; - padding: 1.25rem 0 2.5rem; - box-sizing: border-box; -} - -/* —— 顶部搜索框(页内) —— */ -.search-header { - position: relative; - overflow: hidden; - padding: 1.35rem 1.5rem; - margin-bottom: 1rem; - border-radius: var(--search-radius); - background: transparent; - border: none; - box-shadow: 0 8px 28px rgba(253, 189, 219, 0.12); -} - -.search-header::before { - content: ''; - position: absolute; - inset: 0; - z-index: 0; - border-radius: inherit; - background: var(--search-glass); - backdrop-filter: blur(16px); - -webkit-backdrop-filter: blur(16px); -} - -.search-header::after { - content: ''; - position: absolute; - inset: 0; - z-index: 0; - border-radius: inherit; - box-shadow: inset 0 0 0 1px var(--search-ring); - pointer-events: none; -} - -.search-header > * { - position: relative; - z-index: 1; -} - -.search-title { - margin: 0 0 1rem; - font-size: 1.5rem; - font-weight: 700; - color: var(--search-accent-text); - text-align: center; -} - -.search-form { - display: flex; - gap: 0.55rem; - align-items: stretch; -} - -.search-input { - flex: 1; - min-width: 0; - padding: 0.72rem 1rem; - font-size: 1rem; - border: 1px solid rgba(253, 189, 219, 0.45); - border-radius: 12px; - background: rgba(255, 255, 255, 0.58); - color: #222; - transition: border-color 0.2s ease, box-shadow 0.2s ease; -} - -.search-input::placeholder { - color: #999; -} - -.search-input:focus { - outline: none; - border-color: var(--search-accent-deep); - box-shadow: 0 0 0 3px rgba(253, 189, 219, 0.28); - background: rgba(255, 255, 255, 0.72); -} - -.search-submit { - flex-shrink: 0; - padding: 0 1.4rem; - font-size: 0.9375rem; - font-weight: 600; - color: var(--search-accent-text); - background: linear-gradient(135deg, rgba(253, 189, 219, 0.58), rgba(240, 168, 196, 0.68)); - border: 1px solid rgba(240, 168, 196, 0.75); - border-radius: 999px; - cursor: pointer; - transition: box-shadow 0.2s ease, transform 0.2s ease; -} - -.search-submit:hover { - box-shadow: 0 5px 18px rgba(253, 189, 219, 0.32); - transform: translateY(-1px); -} - -/* —— 结果总栏(含「共找到」) —— */ -.search-panel { - position: relative; - overflow: hidden; - padding: 1.25rem 1.35rem 1.35rem; - border-radius: var(--search-radius); - background: transparent; - box-shadow: 0 6px 26px rgba(253, 189, 219, 0.1); -} - -.search-panel::before { - content: ''; - position: absolute; - inset: 0; - z-index: 0; - border-radius: inherit; - background: var(--search-glass); - backdrop-filter: blur(14px); - -webkit-backdrop-filter: blur(14px); -} - -.search-panel::after { - content: ''; - position: absolute; - inset: 0; - z-index: 0; - border-radius: inherit; - box-shadow: inset 0 0 0 1px var(--search-ring); - pointer-events: none; -} - -.search-panel > * { - position: relative; - z-index: 1; -} - -.search-panel--message { - padding: 1.5rem; -} - -.search-panel__head { - margin-bottom: 1.15rem; - padding-bottom: 1rem; - border-bottom: 1px solid rgba(253, 189, 219, 0.35); - text-align: center; -} - -.search-panel__title { - margin: 0 0 0.5rem; - font-size: 1.2rem; - font-weight: 700; - color: var(--search-accent-text); -} - -.search-summary { - margin: 0; - font-size: 0.9375rem; - color: #444; - line-height: 1.5; -} - -.search-summary strong { - color: var(--search-accent-text); - font-weight: 700; -} - -.search-sort-hint { - margin: 0.45rem 0 0; - font-size: 0.75rem; - color: var(--search-muted); -} - -.search-hint, -.search-empty { - margin: 0; - font-size: 0.9375rem; - color: var(--search-muted); - text-align: center; -} - -/* —— 分类区块 —— */ -.search-block { - margin-top: 1.15rem; - padding-top: 1rem; - border-top: 1px dashed rgba(253, 189, 219, 0.35); -} - -.search-block:first-of-type { - margin-top: 0; - padding-top: 0; - border-top: none; -} - -.search-block__head { - display: flex; - align-items: center; - justify-content: space-between; - gap: 0.75rem; - margin-bottom: 0.85rem; -} - -.search-block__title { - margin: 0; - font-size: 1.05rem; - font-weight: 700; - color: var(--search-accent-text); -} - -.search-block__badge { - flex-shrink: 0; - padding: 0.2rem 0.65rem; - font-size: 0.75rem; - font-weight: 600; - color: var(--search-accent-text); - background: rgba(253, 189, 219, 0.32); - border: 1px solid rgba(253, 189, 219, 0.45); - border-radius: 999px; -} - -.search-result-list { - list-style: none; - margin: 0; - padding: 0; - display: flex; - flex-direction: column; - gap: 0.65rem; -} - -/* —— 单条结果卡片(边框区分) —— */ -.search-card { - padding: 0.9rem 1rem; - border-radius: 14px; - background: rgba(255, 255, 255, 0.48); - border: 1px solid rgba(253, 189, 219, 0.42); - box-shadow: 0 2px 12px rgba(253, 189, 219, 0.08); - transition: border-color 0.2s ease, box-shadow 0.2s ease; -} - -.search-card:hover { - border-color: rgba(240, 168, 196, 0.65); - box-shadow: 0 6px 20px rgba(253, 189, 219, 0.16); -} - -.search-card--user { - padding: 0.75rem 1rem; -} - -.search-card__title { - display: block; - font-size: 1rem; - font-weight: 600; - color: #222; - text-decoration: none; - line-height: 1.35; -} - -.search-card__title:hover { - color: var(--search-accent-text); -} - -.search-card__meta { - margin: 0.35rem 0 0; - font-size: 0.78rem; - color: var(--search-muted); -} - -.search-card__snippet { - margin: 0.45rem 0 0; - font-size: 0.875rem; - line-height: 1.55; - color: #444; -} - -.search-block__footer { - display: flex; - justify-content: center; - margin-top: 1rem; -} - -.search-action-btn { - display: inline-flex; - align-items: center; - justify-content: center; - min-height: 2.5rem; - padding: 0.5rem 1.35rem; - font-size: 0.875rem; - font-weight: 600; - color: var(--search-accent-text); - text-decoration: none; - border-radius: 999px; - border: 1px solid rgba(240, 168, 196, 0.65); - background: linear-gradient(135deg, rgba(253, 189, 219, 0.45), rgba(240, 168, 196, 0.52)); - box-shadow: 0 3px 12px rgba(253, 189, 219, 0.18); - transition: box-shadow 0.2s ease, transform 0.2s ease; -} - -.search-action-btn:hover { - text-decoration: none; - color: var(--search-accent-text); - box-shadow: 0 5px 18px rgba(253, 189, 219, 0.28); - transform: translateY(-1px); -} - -/* —— 分页 —— */ -.search-pagination { - margin-top: 1rem; -} - -.search-pagination .page-link { - color: var(--search-accent-text); - background: rgba(255, 255, 255, 0.45); - border: 1px solid rgba(253, 189, 219, 0.4); - border-radius: 8px; - margin: 0.15rem; -} - -.search-pagination .page-link:hover { - background: rgba(253, 189, 219, 0.35); - color: var(--search-accent-text); -} - -.search-pagination .page-item.active .page-link { - background: rgba(253, 189, 219, 0.55); - border-color: rgba(240, 168, 196, 0.6); - color: var(--search-accent-text); -} - -.search-pagination .page-item.disabled .page-link { - background: rgba(255, 255, 255, 0.25); - color: #aaa; -} - -@media (max-width: 576px) { - .search-page { - width: min(100% - 1rem, 920px); - } - - .search-form { - flex-direction: column; - } - - .search-submit { - width: 100%; - padding: 0.68rem; - } - - .search-block__head { - flex-direction: column; - align-items: flex-start; - } -} diff --git a/examples/anlian-mq/public/css/topic_index.css b/examples/anlian-mq/public/css/topic_index.css deleted file mode 100644 index 5bdde6f..0000000 --- a/examples/anlian-mq/public/css/topic_index.css +++ /dev/null @@ -1,215 +0,0 @@ -/** - * 专题书架 — 书本式卡片 - */ - -.topic-shelf-page .topic-shelf-header { - margin-bottom: 2rem; -} - -.topic-shelf-lead { - margin: 0; - text-align: center; - font-size: 0.95rem; - color: rgba(17, 17, 17, 0.75); - line-height: 1.6; -} - -.topic-book-grid { - list-style: none; - margin: 0; - padding: 0; - display: grid; - grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); - gap: 2.25rem 1.75rem; - align-items: stretch; -} - -.topic-book-item { - margin: 0; - display: flex; -} - -.topic-book { - display: flex; - flex-direction: column; - align-items: center; - text-decoration: none; - color: inherit; - width: 100%; - min-height: 100%; - transition: transform 0.35s ease; -} - -.topic-book:hover, -.topic-book:focus-visible { - transform: translateY(-6px); - text-decoration: none; - color: inherit; -} - -.topic-book__volume { - position: relative; - display: flex; - align-items: stretch; - width: 12.5rem; - height: 17.5rem; - margin-bottom: 1.1rem; - perspective: 900px; - filter: drop-shadow(0 14px 28px rgba(61, 32, 64, 0.35)); -} - -.topic-book__spine { - width: 1.65rem; - flex-shrink: 0; - background: linear-gradient(180deg, #5c2d4a 0%, #3d2040 55%, #2a1528 100%); - border-radius: 4px 0 0 4px; - box-shadow: inset -2px 0 6px rgba(0, 0, 0, 0.25); - display: flex; - align-items: center; - justify-content: center; - padding: 0.65rem 0.15rem; -} - -/* 书脊竖排:汉字正向自上而下(勿 rotate 180°) */ -.topic-book__spine-title { - writing-mode: vertical-rl; - text-orientation: upright; - font-size: 0.7rem; - font-weight: 600; - letter-spacing: 0.12em; - color: rgba(255, 232, 245, 0.92); - line-height: 1.45; - max-height: 14rem; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.topic-book__cover { - position: relative; - flex: 1; - overflow: hidden; - border-radius: 0 6px 6px 0; - background: #2a1528; - transform-origin: left center; - transition: transform 0.4s ease; -} - -.topic-book:hover .topic-book__cover { - transform: rotateY(-8deg); -} - -.topic-book__cover img { - width: 100%; - height: 100%; - object-fit: cover; - display: block; -} - -.topic-book__shine { - pointer-events: none; - position: absolute; - inset: 0; - background: linear-gradient( - 125deg, - rgba(255, 255, 255, 0.28) 0%, - transparent 42%, - transparent 58%, - rgba(253, 189, 219, 0.12) 100% - ); -} - -.topic-book__info { - display: flex; - flex-direction: column; - align-items: center; - text-align: center; - width: 14rem; - min-height: 10.5rem; - flex: 1; -} - -.topic-book__title { - margin: 0 0 0.5rem; - min-height: 2.85rem; - display: flex; - align-items: center; - justify-content: center; - font-size: 1.05rem; - font-weight: 600; - color: #1a1020; - line-height: 1.35; -} - -.topic-book__summary { - flex: 1; - width: 100%; - min-height: 3.9rem; - margin: 0 0 0.75rem; - font-size: 0.8125rem; - line-height: 1.55; - color: rgba(26, 16, 32, 0.72); - display: -webkit-box; - -webkit-line-clamp: 3; - -webkit-box-orient: vertical; - overflow: hidden; -} - -.topic-book__summary:empty::before { - content: '\00a0'; - visibility: hidden; -} - -.topic-book__cta { - display: inline-block; - margin-top: auto; - flex-shrink: 0; - font-size: 0.75rem; - font-weight: 600; - letter-spacing: 0.04em; - color: #6b3458; - padding: 0.28rem 0.85rem; - border-radius: 999px; - background: rgba(253, 189, 219, 0.35); - border: 1px solid rgba(253, 189, 219, 0.55); - transition: background 0.2s, box-shadow 0.2s; -} - -.topic-book:hover .topic-book__cta { - background: rgba(253, 189, 219, 0.55); - box-shadow: 0 4px 12px rgba(253, 189, 219, 0.3); -} - -.topic-shelf-empty { - text-align: center; - padding: 3rem 1rem; - color: rgba(17, 17, 17, 0.65); -} - -@media (max-width: 576px) { - .topic-book-grid { - grid-template-columns: 1fr; - justify-items: center; - } - - .topic-book__volume { - width: 11rem; - height: 15.5rem; - } -} - -@media (prefers-reduced-motion: reduce) { - .topic-book, - .topic-book__cover { - transition: none; - } - - .topic-book:hover, - .topic-book:focus-visible { - transform: none; - } - - .topic-book:hover .topic-book__cover { - transform: none; - } -} diff --git a/examples/anlian-mq/public/favicon-32.png b/examples/anlian-mq/public/favicon-32.png deleted file mode 100644 index 22b2407..0000000 Binary files a/examples/anlian-mq/public/favicon-32.png and /dev/null differ diff --git a/examples/anlian-mq/public/img/apple-touch-icon.png b/examples/anlian-mq/public/img/apple-touch-icon.png deleted file mode 100644 index b24d001..0000000 Binary files a/examples/anlian-mq/public/img/apple-touch-icon.png and /dev/null differ diff --git a/examples/anlian-mq/public/img/author_avatar-144.webp b/examples/anlian-mq/public/img/author_avatar-144.webp deleted file mode 100644 index f3ccaf2..0000000 Binary files a/examples/anlian-mq/public/img/author_avatar-144.webp and /dev/null differ diff --git a/examples/anlian-mq/public/img/bg-body-960.webp b/examples/anlian-mq/public/img/bg-body-960.webp deleted file mode 100644 index b3c6603..0000000 Binary files a/examples/anlian-mq/public/img/bg-body-960.webp and /dev/null differ diff --git a/examples/anlian-mq/public/img/bg-hero-640.webp b/examples/anlian-mq/public/img/bg-hero-640.webp deleted file mode 100644 index 491e199..0000000 Binary files a/examples/anlian-mq/public/img/bg-hero-640.webp and /dev/null differ diff --git a/examples/anlian-mq/public/img/bg.webp b/examples/anlian-mq/public/img/bg.webp deleted file mode 100644 index 4f4034f..0000000 Binary files a/examples/anlian-mq/public/img/bg.webp and /dev/null differ diff --git a/examples/anlian-mq/public/img/favicon-32.png b/examples/anlian-mq/public/img/favicon-32.png deleted file mode 100644 index 22b2407..0000000 Binary files a/examples/anlian-mq/public/img/favicon-32.png and /dev/null differ diff --git a/examples/anlian-mq/public/img/logo.svg b/examples/anlian-mq/public/img/logo.svg deleted file mode 100644 index b9ecada..0000000 --- a/examples/anlian-mq/public/img/logo.svg +++ /dev/null @@ -1,101 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/anlian-mq/public/img/og-share.png b/examples/anlian-mq/public/img/og-share.png deleted file mode 100644 index 3eb3e01..0000000 Binary files a/examples/anlian-mq/public/img/og-share.png and /dev/null differ diff --git a/examples/anlian-mq/public/js/anlian_partial.js b/examples/anlian-mq/public/js/anlian_partial.js deleted file mode 100644 index d338c38..0000000 --- a/examples/anlian-mq/public/js/anlian_partial.js +++ /dev/null @@ -1,117 +0,0 @@ -/** - * 列表页局部刷新:板块切换与分页,无全页重载、无加载动画。 - */ -(function () { - const AJAX_HEADERS = { 'X-Requested-With': 'XMLHttpRequest' }; - - document.addEventListener('DOMContentLoaded', function () { - initFeedListPartial(); - initCommentListPartial(); - }); - - function initFeedListPartial() { - const page = document.querySelector('.feed-list-page[data-partial-feed]'); - if (!page) return; - - page.addEventListener('click', function (event) { - const tab = event.target.closest('.feed-tab'); - const pageLink = event.target.closest('.feed-pagination .page-link[href]'); - const link = tab || pageLink; - if (!link || link.classList.contains('disabled')) return; - event.preventDefault(); - loadFeedPartial(page, link.href); - }); - } - - async function loadFeedPartial(page, url) { - const body = page.querySelector('.feed-list-body'); - if (!body) return; - - try { - const response = await fetch(url, { headers: AJAX_HEADERS }); - if (!response.ok) throw new Error(String(response.status)); - const html = await response.text(); - const doc = new DOMParser().parseFromString(html, 'text/html'); - const newBody = doc.querySelector('.feed-list-body'); - const newPagination = doc.querySelector('.feed-pagination'); - if (newBody) body.innerHTML = newBody.innerHTML; - - let pagination = page.querySelector('.feed-pagination'); - if (newPagination) { - if (pagination) { - pagination.replaceWith(newPagination); - } else { - body.insertAdjacentElement('afterend', newPagination); - } - pagination = newPagination; - } else if (pagination) { - pagination.remove(); - } - - syncFeedTabsFromUrl(page, url); - history.pushState(null, '', url); - page.scrollIntoView({ block: 'nearest', behavior: 'instant' in window ? 'instant' : 'auto' }); - } catch (err) { - console.error('列表局部刷新失败', err); - } - } - - function syncFeedTabsFromUrl(page, url) { - const parsed = new URL(url, window.location.origin); - const boardId = parsed.searchParams.get('board_id') - || parsed.searchParams.get('news_board_id') - || ''; - const param = parsed.searchParams.has('news_board_id') ? 'news_board_id' : 'board_id'; - - page.querySelectorAll('.feed-tab').forEach((tab) => { - const tabUrl = new URL(tab.href, window.location.origin); - const tabBoard = tabUrl.searchParams.get(param) || ''; - const isActive = tabBoard === boardId; - tab.classList.toggle('active', isActive); - }); - - const activeTab = page.querySelector('.feed-tab.active'); - const bar = page.querySelector('[data-feed-board]'); - if (activeTab && bar && typeof initFeedBoardUI === 'function') { - initFeedBoardUI(bar); - } - } - - function initCommentListPartial() { - const root = document.querySelector('[data-partial-comments]'); - if (!root) return; - - root.addEventListener('click', function (event) { - const link = event.target.closest('.comment-pagination .page-link[href]'); - if (!link) return; - event.preventDefault(); - loadCommentPartial(root, link.href); - }); - } - - async function loadCommentPartial(root, url) { - const list = root.querySelector('.comment-list-container'); - const pagination = root.querySelector('.comment-pagination'); - if (!list) return; - - try { - const response = await fetch(url, { headers: AJAX_HEADERS }); - if (!response.ok) throw new Error(String(response.status)); - const html = await response.text(); - const doc = new DOMParser().parseFromString(html, 'text/html'); - const newList = doc.querySelector('.comment-list-container'); - const newPagination = doc.querySelector('.comment-pagination'); - if (newList) list.innerHTML = newList.innerHTML; - if (newPagination && pagination) { - pagination.replaceWith(newPagination); - } else if (newPagination) { - list.insertAdjacentElement('afterend', newPagination); - } else if (pagination) { - pagination.remove(); - } - history.replaceState(null, '', url); - } catch (err) { - console.error('评论分页刷新失败', err); - } - } -})(); diff --git a/examples/anlian-mq/public/js/chat_room_list.js b/examples/anlian-mq/public/js/chat_room_list.js deleted file mode 100644 index 92a12d6..0000000 --- a/examples/anlian-mq/public/js/chat_room_list.js +++ /dev/null @@ -1,35 +0,0 @@ -(function () { - 'use strict'; - - document.addEventListener('DOMContentLoaded', function () { - var input = document.getElementById('chat-room-search-input'); - var grid = document.getElementById('chat-room-grid'); - var emptyHint = document.getElementById('chat-search-empty'); - if (!input || !grid) { - return; - } - - var cards = grid.querySelectorAll('.chat-room-card'); - - function filterRooms() { - var query = input.value.trim().toLowerCase(); - var visibleCount = 0; - - cards.forEach(function (card) { - var haystack = (card.dataset.search || '').toLowerCase(); - var match = !query || haystack.indexOf(query) !== -1; - card.hidden = !match; - if (match) { - visibleCount += 1; - } - }); - - if (emptyHint) { - emptyHint.hidden = visibleCount > 0 || !query; - } - } - - input.addEventListener('input', filterRooms); - filterRooms(); - }); -})(); diff --git a/examples/anlian-mq/public/js/chat_ws.js b/examples/anlian-mq/public/js/chat_ws.js deleted file mode 100644 index 2757163..0000000 --- a/examples/anlian-mq/public/js/chat_ws.js +++ /dev/null @@ -1,286 +0,0 @@ -(function () { - 'use strict'; - - function wsBaseUrl() { - var scheme = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; - return scheme + '//' + window.location.host; - } - - function escapeHtml(text) { - var div = document.createElement('div'); - div.textContent = text; - return div.innerHTML; - } - - function formatContent(text) { - return escapeHtml(text).replace(/\n/g, '
    '); - } - - function scrollToBottom(container) { - if (!container) { - return; - } - container.scrollTop = container.scrollHeight; - } - - function removeEmptyHint(container) { - var empty = container.querySelector('.chat-empty'); - if (empty) { - empty.remove(); - } - } - - function buildRoomMessageNode(data, profileBase) { - var article = document.createElement('article'); - article.className = 'chat-message' + (data.is_mine ? ' chat-message-mine' : ''); - article.dataset.messageId = String(data.id); - - var profileLink = ''; - if (!data.is_anonymous && data.author_username) { - profileLink = - '主页'; - } - - article.innerHTML = - '' + - '
    ' + - '
    ' + - '' + - escapeHtml(data.author_display) + - '' + - profileLink + - '' + - '
    ' + - '

    ' + - formatContent(data.content) + - '

    ' + - '
    '; - - return article; - } - - function buildDirectMessageNode(data) { - var article = document.createElement('article'); - article.className = 'chat-message' + (data.is_mine ? ' chat-message-mine' : ''); - article.dataset.messageId = String(data.id); - - article.innerHTML = - '' + - '
    ' + - '
    ' + - '' + - escapeHtml(data.author_display) + - '' + - '' + - '
    ' + - '

    ' + - formatContent(data.content) + - '

    ' + - '
    '; - - return article; - } - - function appendMessage(container, node) { - removeEmptyHint(container); - if (container.querySelector('[data-message-id="' + node.dataset.messageId + '"]')) { - return; - } - container.appendChild(node); - scrollToBottom(container); - } - - function setStatus(root, text, isError) { - var status = root.querySelector('.chat-ws-status'); - if (!status) { - return; - } - status.textContent = text; - status.classList.toggle('chat-ws-status-error', !!isError); - status.classList.toggle('chat-ws-status-ok', !isError); - } - - function initChatApp(root) { - var wsPath = root.dataset.wsPath; - var kind = root.dataset.chatKind || 'room'; - var canSend = root.dataset.canSend === '1'; - var profileBase = root.dataset.profileBase || '/user/'; - var messagesEl = root.querySelector('#chat-messages'); - var form = root.querySelector('.chat-compose'); - var textarea = form ? form.querySelector('textarea[name="content"]') : null; - var anonInput = form ? form.querySelector('input[name="is_anonymous"]') : null; - var errorBox = root.querySelector('.chat-ws-errors'); - var socket = null; - var reconnectTimer = null; - var reconnectDelay = 1000; - var reconnectAttempts = 0; - var maxReconnectAttempts = 12; - - if (!wsPath || !messagesEl) { - return; - } - - function showError(detail) { - if (!errorBox) { - return; - } - errorBox.textContent = detail; - errorBox.hidden = false; - } - - function clearError() { - if (errorBox) { - errorBox.hidden = true; - errorBox.textContent = ''; - } - } - - function connect() { - if (socket && (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING)) { - return; - } - - setStatus(root, '连接中…', false); - socket = new WebSocket(wsBaseUrl() + wsPath); - - socket.addEventListener('open', function () { - reconnectDelay = 1000; - reconnectAttempts = 0; - setStatus(root, '已连接', false); - clearError(); - }); - - socket.addEventListener('message', function (event) { - var payload; - try { - payload = JSON.parse(event.data); - } catch (err) { - return; - } - - if (payload.event === 'connected') { - setStatus(root, '已连接', false); - return; - } - - if (payload.event === 'error') { - showError(payload.detail || '发送失败'); - return; - } - - if (payload.event === 'message' && payload.message) { - clearError(); - var node = - kind === 'direct' - ? buildDirectMessageNode(payload.message) - : buildRoomMessageNode(payload.message, profileBase); - appendMessage(messagesEl, node); - } - }); - - socket.addEventListener('close', function () { - socket = null; - reconnectAttempts += 1; - if (reconnectAttempts >= maxReconnectAttempts) { - setStatus(root, '连接失败', true); - showError('无法连接聊天服务器,请刷新页面后重试'); - return; - } - setStatus(root, '连接已断开,正在重连…', true); - reconnectTimer = window.setTimeout(function () { - reconnectDelay = Math.min(reconnectDelay * 2, 15000); - connect(); - }, reconnectDelay); - }); - - socket.addEventListener('error', function () { - setStatus(root, '连接异常', true); - }); - } - - if (form && canSend) { - form.addEventListener('submit', function (event) { - event.preventDefault(); - clearError(); - - if (!socket || socket.readyState !== WebSocket.OPEN) { - showError('尚未连接到服务器,请稍候再试'); - connect(); - return; - } - - var content = (textarea && textarea.value ? textarea.value : '').trim(); - if (!content) { - showError('消息不能为空'); - return; - } - - socket.send( - JSON.stringify({ - action: 'send', - content: content, - is_anonymous: !!(anonInput && anonInput.checked), - }) - ); - if (textarea) { - textarea.value = ''; - } - }); - } - - scrollToBottom(messagesEl); - - function scheduleConnect() { - var started = false; - function run() { - if (started) { - return; - } - started = true; - connect(); - } - if (form) { - form.addEventListener('focusin', run, { once: true }); - } - if ('requestIdleCallback' in window) { - requestIdleCallback(run, { timeout: 2500 }); - } else { - setTimeout(run, 100); - } - } - - setStatus(root, '待连接', false); - scheduleConnect(); - - window.addEventListener('beforeunload', function () { - if (reconnectTimer) { - window.clearTimeout(reconnectTimer); - } - if (socket) { - socket.close(); - } - }); - } - - document.addEventListener('DOMContentLoaded', function () { - var root = document.getElementById('chat-app'); - if (root) { - initChatApp(root); - } - }); -})(); diff --git a/examples/anlian-mq/public/js/detail_reading.js b/examples/anlian-mq/public/js/detail_reading.js deleted file mode 100644 index c42a9c0..0000000 --- a/examples/anlian-mq/public/js/detail_reading.js +++ /dev/null @@ -1,98 +0,0 @@ -(function () { - 'use strict'; - - function perView() { - return window.matchMedia('(min-width: 768px)').matches ? 2 : 1; - } - - function pageCount(total, pv) { - if (total <= 0) return 0; - return Math.max(1, total - pv + 1); - } - - function initCarousel(root) { - var track = root.querySelector('.detail-recommend-track'); - var dotsWrap = root.querySelector('.detail-recommend-dots'); - if (!track || !dotsWrap) return; - - var slides = track.querySelectorAll('.detail-recommend-slide'); - var total = slides.length; - if (total === 0) return; - - var index = 0; - var timer = null; - var pv = perView(); - var pages = pageCount(total, pv); - - function renderDots() { - dotsWrap.innerHTML = ''; - for (var i = 0; i < pages; i++) { - var btn = document.createElement('button'); - btn.type = 'button'; - btn.className = 'detail-recommend-dot' + (i === index ? ' is-active' : ''); - btn.setAttribute('aria-label', '第 ' + (i + 1) + ' 组推荐'); - btn.setAttribute('aria-selected', i === index ? 'true' : 'false'); - btn.dataset.page = String(i); - btn.addEventListener('click', function () { - goTo(parseInt(this.dataset.page, 10)); - restartAuto(); - }); - dotsWrap.appendChild(btn); - } - } - - function applyTransform() { - var slidePct = 100 / pv; - track.style.transform = 'translateX(-' + index * slidePct + '%)'; - var dotEls = dotsWrap.querySelectorAll('.detail-recommend-dot'); - dotEls.forEach(function (el, i) { - el.classList.toggle('is-active', i === index); - el.setAttribute('aria-selected', i === index ? 'true' : 'false'); - }); - } - - function goTo(i) { - index = Math.max(0, Math.min(i, pages - 1)); - applyTransform(); - } - - function restartAuto() { - if (timer) clearInterval(timer); - if (pages <= 1) return; - timer = setInterval(function () { - goTo((index + 1) % pages); - }, 5000); - } - - function onResize() { - var newPv = perView(); - if (newPv !== pv) { - pv = newPv; - pages = pageCount(total, pv); - if (index >= pages) index = pages - 1; - renderDots(); - } - applyTransform(); - } - - renderDots(); - applyTransform(); - restartAuto(); - window.addEventListener('resize', onResize); - - root.addEventListener('mouseenter', function () { - if (timer) clearInterval(timer); - }); - root.addEventListener('mouseleave', restartAuto); - } - - function boot() { - document.querySelectorAll('[data-recommend-carousel]').forEach(initCarousel); - } - - if (document.readyState === 'loading') { - document.addEventListener('DOMContentLoaded', boot); - } else { - boot(); - } -})(); diff --git a/examples/anlian-mq/public/js/feed_board.js b/examples/anlian-mq/public/js/feed_board.js deleted file mode 100644 index 972db43..0000000 --- a/examples/anlian-mq/public/js/feed_board.js +++ /dev/null @@ -1,62 +0,0 @@ -/** - * 分段板块栏:横向滚动 + 滑动光晕(首页与列表页共用) - */ -function initFeedBoardUI(root) { - if (!root) return; - - const scrollWrap = root.querySelector('.home-posts-tabs-scroll, .feed-tabs-scroll'); - const scrollLeft = root.querySelector('.home-posts-scroll-left, .feed-scroll-left'); - const scrollRight = root.querySelector('.home-posts-scroll-right, .feed-scroll-right'); - const spotlight = root.querySelector('.home-posts-spotlight, .feed-spotlight'); - const segment = root.querySelector('.home-posts-segment, .feed-segment'); - - if (scrollWrap && scrollLeft && scrollRight) { - const scrollAmount = 140; - scrollLeft.addEventListener('click', function () { - scrollWrap.scrollBy({ left: -scrollAmount, behavior: 'smooth' }); - }); - scrollRight.addEventListener('click', function () { - scrollWrap.scrollBy({ left: scrollAmount, behavior: 'smooth' }); - }); - - function updateScrollButtons() { - const max = scrollWrap.scrollWidth - scrollWrap.clientWidth; - const atStart = scrollWrap.scrollLeft <= 4; - const atEnd = scrollWrap.scrollLeft >= max - 4; - scrollLeft.classList.toggle('is-hidden', atStart); - scrollRight.classList.toggle('is-hidden', atEnd); - } - - updateScrollButtons(); - scrollWrap.addEventListener('scroll', updateScrollButtons); - window.addEventListener('resize', updateScrollButtons); - } - - if (spotlight && segment) { - const tabSelector = '.home-posts-tab, .feed-tab'; - const moveSpotlight = (tab) => { - if (!tab) return; - const pad = segment.getBoundingClientRect(); - const rect = tab.getBoundingClientRect(); - const left = rect.left - pad.left; - spotlight.style.setProperty('--spot-l', `${left}px`); - spotlight.style.setProperty('--spot-w', `${rect.width}px`); - }; - - moveSpotlight(root.querySelector(`${tabSelector}.active`)); - - root.querySelectorAll(tabSelector).forEach((tab) => { - tab.addEventListener('click', () => { - requestAnimationFrame(() => moveSpotlight(tab)); - }); - }); - - window.addEventListener('resize', () => { - moveSpotlight(root.querySelector(`${tabSelector}.active`)); - }); - } -} - -document.addEventListener('DOMContentLoaded', function () { - document.querySelectorAll('[data-feed-board]').forEach(initFeedBoardUI); -}); diff --git a/examples/anlian-mq/public/js/index.js b/examples/anlian-mq/public/js/index.js deleted file mode 100644 index dfbac93..0000000 --- a/examples/anlian-mq/public/js/index.js +++ /dev/null @@ -1,99 +0,0 @@ -/** - * 首页:新闻/帖子板块 AJAX(板块栏交互见 feed_board.js) - */ -document.addEventListener('DOMContentLoaded', function () { - if (document.body.classList.contains('page-home')) { - initHomePanelSwap(); - } -}); - -function initHomePanelSwap() { - const newsPanel = document.getElementById('homeNewsPanel'); - const postPanel = document.getElementById('tenPostContainer'); - - bindPanelTabs({ - tabSelector: '.js-home-news-tab', - panel: newsPanel, - queryKey: 'news_board_id', - getBoardId: (el) => el.dataset.newsBoard || '0', - onAfterActive: (tab) => syncFeedBoardSpotlight('.home-news-board-bar', tab), - }); - - bindPanelTabs({ - tabSelector: '.js-home-post-tab', - panel: postPanel, - queryKey: 'board_id', - getBoardId: (el) => el.dataset.board || '0', - onAfterActive: (tab) => syncFeedBoardSpotlight('.home-posts-board-bar', tab), - }); -} - -function bindPanelTabs({ tabSelector, panel, queryKey, getBoardId, onSwapped, onAfterActive }) { - if (!panel) return; - - document.addEventListener('click', function (e) { - const tab = e.target.closest(tabSelector); - if (!tab) return; - - e.preventDefault(); - - if (tab.classList.contains('active')) return; - - const boardId = getBoardId(tab); - const requestUrl = tab.getAttribute('href'); - - setActiveTab(tabSelector, tab); - if (typeof onAfterActive === 'function') { - onAfterActive(tab); - } - swapPanelHtml(panel, requestUrl, onSwapped); - updateHomeUrlParam(queryKey, boardId); - }); -} - -function setActiveTab(tabSelector, activeTab) { - const root = activeTab.closest('.home-posts-tabs'); - if (!root) return; - root.querySelectorAll(tabSelector).forEach((el) => el.classList.remove('active')); - activeTab.classList.add('active'); -} - -function syncFeedBoardSpotlight(barSelector, tab) { - const root = document.querySelector(barSelector); - if (!root || !tab) return; - const spotlight = root.querySelector('.home-posts-spotlight'); - const segment = root.querySelector('.home-posts-segment'); - if (!spotlight || !segment) return; - const pad = segment.getBoundingClientRect(); - const rect = tab.getBoundingClientRect(); - spotlight.style.setProperty('--spot-l', `${rect.left - pad.left}px`); - spotlight.style.setProperty('--spot-w', `${rect.width}px`); -} - -async function swapPanelHtml(panel, url, onSwapped) { - try { - const response = await fetch(url, { - headers: { 'X-Requested-With': 'XMLHttpRequest' }, - }); - if (!response.ok) throw new Error(response.status); - const html = await response.text(); - panel.innerHTML = html; - if (typeof onSwapped === 'function') { - onSwapped(panel); - } - } catch (err) { - console.error('板块内容加载失败', err); - panel.innerHTML = - '

    加载失败,请稍后重试

    '; - } -} - -function updateHomeUrlParam(key, value) { - const url = new URL(window.location.href); - if (value === '0') { - url.searchParams.delete(key); - } else { - url.searchParams.set(key, value); - } - history.replaceState(null, '', url.pathname + url.search); -} diff --git a/examples/anlian-mq/public/logo.svg b/examples/anlian-mq/public/logo.svg deleted file mode 100644 index b9ecada..0000000 --- a/examples/anlian-mq/public/logo.svg +++ /dev/null @@ -1,101 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/anlian-mq/public/vendor/bootstrap-anlian.min.css b/examples/anlian-mq/public/vendor/bootstrap-anlian.min.css deleted file mode 100644 index 514693c..0000000 --- a/examples/anlian-mq/public/vendor/bootstrap-anlian.min.css +++ /dev/null @@ -1 +0,0 @@ -:root,[data-bs-theme=light]{--bs-blue: #0d6efd;--bs-indigo: #6610f2;--bs-purple: #6f42c1;--bs-pink: #d63384;--bs-red: #dc3545;--bs-orange: #fd7e14;--bs-yellow: #ffc107;--bs-green: #198754;--bs-teal: #20c997;--bs-cyan: #0dcaf0;--bs-black: #000;--bs-white: #fff;--bs-gray: #6c757d;--bs-gray-dark: #343a40;--bs-gray-100: #f8f9fa;--bs-gray-200: #e9ecef;--bs-gray-300: #dee2e6;--bs-gray-400: #ced4da;--bs-gray-500: #adb5bd;--bs-gray-600: #6c757d;--bs-gray-700: #495057;--bs-gray-800: #343a40;--bs-gray-900: #212529;--bs-primary: #0d6efd;--bs-secondary: #6c757d;--bs-success: #198754;--bs-info: #0dcaf0;--bs-warning: #ffc107;--bs-danger: #dc3545;--bs-light: #f8f9fa;--bs-dark: #212529;--bs-primary-rgb: 13, 110, 253;--bs-secondary-rgb: 108, 117, 125;--bs-success-rgb: 25, 135, 84;--bs-info-rgb: 13, 202, 240;--bs-warning-rgb: 255, 193, 7;--bs-danger-rgb: 220, 53, 69;--bs-light-rgb: 248, 249, 250;--bs-dark-rgb: 33, 37, 41;--bs-primary-text-emphasis: #052c65;--bs-secondary-text-emphasis: #2b2f32;--bs-success-text-emphasis: #0a3622;--bs-info-text-emphasis: #055160;--bs-warning-text-emphasis: #664d03;--bs-danger-text-emphasis: #58151c;--bs-light-text-emphasis: #495057;--bs-dark-text-emphasis: #495057;--bs-primary-bg-subtle: #cfe2ff;--bs-secondary-bg-subtle: #e2e3e5;--bs-success-bg-subtle: #d1e7dd;--bs-info-bg-subtle: #cff4fc;--bs-warning-bg-subtle: #fff3cd;--bs-danger-bg-subtle: #f8d7da;--bs-light-bg-subtle: #fcfcfd;--bs-dark-bg-subtle: #ced4da;--bs-primary-border-subtle: #9ec5fe;--bs-secondary-border-subtle: #c4c8cb;--bs-success-border-subtle: #a3cfbb;--bs-info-border-subtle: #9eeaf9;--bs-warning-border-subtle: #ffe69c;--bs-danger-border-subtle: #f1aeb5;--bs-light-border-subtle: #e9ecef;--bs-dark-border-subtle: #adb5bd;--bs-white-rgb: 255, 255, 255;--bs-black-rgb: 0, 0, 0;--bs-font-sans-serif: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", "Liberation Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--bs-font-monospace: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--bs-gradient: linear-gradient(180deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0));--bs-body-font-family: var(--bs-font-sans-serif);--bs-body-font-size:1rem;--bs-body-font-weight: 400;--bs-body-line-height: 1.5;--bs-body-color: #212529;--bs-body-color-rgb: 33, 37, 41;--bs-body-bg: #fff;--bs-body-bg-rgb: 255, 255, 255;--bs-emphasis-color: #000;--bs-emphasis-color-rgb: 0, 0, 0;--bs-secondary-color: rgba(33, 37, 41, 0.75);--bs-secondary-color-rgb: 33, 37, 41;--bs-secondary-bg: #e9ecef;--bs-secondary-bg-rgb: 233, 236, 239;--bs-tertiary-color: rgba(33, 37, 41, 0.5);--bs-tertiary-color-rgb: 33, 37, 41;--bs-tertiary-bg: #f8f9fa;--bs-tertiary-bg-rgb: 248, 249, 250;--bs-heading-color: inherit;--bs-link-color: #0d6efd;--bs-link-color-rgb: 13, 110, 253;--bs-link-decoration: underline;--bs-link-hover-color: #0a58ca;--bs-link-hover-color-rgb: 10, 88, 202;--bs-code-color: #d63384;--bs-highlight-color: #212529;--bs-highlight-bg: #fff3cd;--bs-border-width: 1px;--bs-border-style: solid;--bs-border-color: #dee2e6;--bs-border-color-translucent: rgba(0, 0, 0, 0.175);--bs-border-radius: 0.375rem;--bs-border-radius-sm: 0.25rem;--bs-border-radius-lg: 0.5rem;--bs-border-radius-xl: 1rem;--bs-border-radius-xxl: 2rem;--bs-border-radius-2xl: var(--bs-border-radius-xxl);--bs-border-radius-pill: 50rem;--bs-box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);--bs-box-shadow-sm: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);--bs-box-shadow-lg: 0 1rem 3rem rgba(0, 0, 0, 0.175);--bs-box-shadow-inset: inset 0 1px 2px rgba(0, 0, 0, 0.075);--bs-focus-ring-width: 0.25rem;--bs-focus-ring-opacity: 0.25;--bs-focus-ring-color: rgba(13, 110, 253, 0.25);--bs-form-valid-color: #198754;--bs-form-valid-border-color: #198754;--bs-form-invalid-color: #dc3545;--bs-form-invalid-border-color: #dc3545}[data-bs-theme=dark]{color-scheme:dark;--bs-body-color: #dee2e6;--bs-body-color-rgb: 222, 226, 230;--bs-body-bg: #212529;--bs-body-bg-rgb: 33, 37, 41;--bs-emphasis-color: #fff;--bs-emphasis-color-rgb: 255, 255, 255;--bs-secondary-color: rgba(222, 226, 230, 0.75);--bs-secondary-color-rgb: 222, 226, 230;--bs-secondary-bg: #343a40;--bs-secondary-bg-rgb: 52, 58, 64;--bs-tertiary-color: rgba(222, 226, 230, 0.5);--bs-tertiary-color-rgb: 222, 226, 230;--bs-tertiary-bg: #2b3035;--bs-tertiary-bg-rgb: 43, 48, 53;--bs-primary-text-emphasis: #6ea8fe;--bs-secondary-text-emphasis: #a7acb1;--bs-success-text-emphasis: #75b798;--bs-info-text-emphasis: #6edff6;--bs-warning-text-emphasis: #ffda6a;--bs-danger-text-emphasis: #ea868f;--bs-light-text-emphasis: #f8f9fa;--bs-dark-text-emphasis: #dee2e6;--bs-primary-bg-subtle: #031633;--bs-secondary-bg-subtle: #161719;--bs-success-bg-subtle: #051b11;--bs-info-bg-subtle: #032830;--bs-warning-bg-subtle: #332701;--bs-danger-bg-subtle: #2c0b0e;--bs-light-bg-subtle: #343a40;--bs-dark-bg-subtle: #1a1d20;--bs-primary-border-subtle: #084298;--bs-secondary-border-subtle: #41464b;--bs-success-border-subtle: #0f5132;--bs-info-border-subtle: #087990;--bs-warning-border-subtle: #997404;--bs-danger-border-subtle: #842029;--bs-light-border-subtle: #495057;--bs-dark-border-subtle: #343a40;--bs-heading-color: inherit;--bs-link-color: #6ea8fe;--bs-link-hover-color: #8bb9fe;--bs-link-color-rgb: 110, 168, 254;--bs-link-hover-color-rgb: 139, 185, 254;--bs-code-color: #e685b5;--bs-highlight-color: #dee2e6;--bs-highlight-bg: #664d03;--bs-border-color: #495057;--bs-border-color-translucent: rgba(255, 255, 255, 0.15);--bs-form-valid-color: #75b798;--bs-form-valid-border-color: #75b798;--bs-form-invalid-color: #ea868f;--bs-form-invalid-border-color: #ea868f}*,*::before,*::after{box-sizing:border-box}@media(prefers-reduced-motion: no-preference){:root{scroll-behavior:smooth}}body{margin:0;font-family:var(--bs-body-font-family);font-size:var(--bs-body-font-size);font-weight:var(--bs-body-font-weight);line-height:var(--bs-body-line-height);color:var(--bs-body-color);text-align:var(--bs-body-text-align);background-color:var(--bs-body-bg);-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:rgba(0,0,0,0)}hr{margin:1rem 0;color:inherit;border:0;border-top:var(--bs-border-width) solid;opacity:.25}h6,.h6,h5,.h5,h4,.h4,h3,.h3,h2,.h2,h1,.h1{margin-top:0;margin-bottom:.5rem;font-weight:500;line-height:1.2;color:var(--bs-heading-color)}h1,.h1{font-size:calc(1.375rem + 1.5vw)}@media(min-width: 1200px){h1,.h1{font-size:2.5rem}}h2,.h2{font-size:calc(1.325rem + 0.9vw)}@media(min-width: 1200px){h2,.h2{font-size:2rem}}h3,.h3{font-size:calc(1.3rem + 0.6vw)}@media(min-width: 1200px){h3,.h3{font-size:1.75rem}}h4,.h4{font-size:calc(1.275rem + 0.3vw)}@media(min-width: 1200px){h4,.h4{font-size:1.5rem}}h5,.h5{font-size:1.25rem}h6,.h6{font-size:1rem}p{margin-top:0;margin-bottom:1rem}abbr[title]{text-decoration:underline dotted;cursor:help;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}ol,ul{padding-left:2rem}ol,ul,dl{margin-top:0;margin-bottom:1rem}ol ol,ul ul,ol ul,ul ol{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-left:0}blockquote{margin:0 0 1rem}b,strong{font-weight:bolder}small,.small{font-size:0.875em}mark,.mark{padding:.1875em;color:var(--bs-highlight-color);background-color:var(--bs-highlight-bg)}sub,sup{position:relative;font-size:0.75em;line-height:0;vertical-align:baseline}sub{bottom:-0.25em}sup{top:-0.5em}a{color:rgba(var(--bs-link-color-rgb), var(--bs-link-opacity, 1));text-decoration:underline}a:hover{--bs-link-color-rgb: var(--bs-link-hover-color-rgb)}a:not([href]):not([class]),a:not([href]):not([class]):hover{color:inherit;text-decoration:none}pre,code,kbd,samp{font-family:var(--bs-font-monospace);font-size:1em}pre{display:block;margin-top:0;margin-bottom:1rem;overflow:auto;font-size:0.875em}pre code{font-size:inherit;color:inherit;word-break:normal}code{font-size:0.875em;color:var(--bs-code-color);word-wrap:break-word}a>code{color:inherit}kbd{padding:.1875rem .375rem;font-size:0.875em;color:var(--bs-body-bg);background-color:var(--bs-body-color);border-radius:.25rem}kbd kbd{padding:0;font-size:1em}figure{margin:0 0 1rem}img,svg{vertical-align:middle}table{caption-side:bottom;border-collapse:collapse}caption{padding-top:.5rem;padding-bottom:.5rem;color:var(--bs-secondary-color);text-align:left}th{text-align:inherit;text-align:-webkit-match-parent}thead,tbody,tfoot,tr,td,th{border-color:inherit;border-style:solid;border-width:0}label{display:inline-block}button{border-radius:0}button:focus:not(:focus-visible){outline:0}input,button,select,optgroup,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,select{text-transform:none}[role=button]{cursor:pointer}select{word-wrap:normal}select:disabled{opacity:1}[list]:not([type=date]):not([type=datetime-local]):not([type=month]):not([type=week]):not([type=time])::-webkit-calendar-picker-indicator{display:none !important}button,[type=button],[type=reset],[type=submit]{-webkit-appearance:button}button:not(:disabled),[type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled){cursor:pointer}::-moz-focus-inner{padding:0;border-style:none}textarea{resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{float:left;width:100%;padding:0;margin-bottom:.5rem;font-size:calc(1.275rem + 0.3vw);line-height:inherit}@media(min-width: 1200px){legend{font-size:1.5rem}}legend+*{clear:left}::-webkit-datetime-edit-fields-wrapper,::-webkit-datetime-edit-text,::-webkit-datetime-edit-minute,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-year-field{padding:0}::-webkit-inner-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-color-swatch-wrapper{padding:0}::file-selector-button{font:inherit;-webkit-appearance:button}output{display:inline-block}iframe{border:0}summary{display:list-item;cursor:pointer}progress{vertical-align:baseline}[hidden]{display:none !important}.lead{font-size:1.25rem;font-weight:300}.display-1{font-size:calc(1.625rem + 4.5vw);font-weight:300;line-height:1.2}@media(min-width: 1200px){.display-1{font-size:5rem}}.display-2{font-size:calc(1.575rem + 3.9vw);font-weight:300;line-height:1.2}@media(min-width: 1200px){.display-2{font-size:4.5rem}}.display-3{font-size:calc(1.525rem + 3.3vw);font-weight:300;line-height:1.2}@media(min-width: 1200px){.display-3{font-size:4rem}}.display-4{font-size:calc(1.475rem + 2.7vw);font-weight:300;line-height:1.2}@media(min-width: 1200px){.display-4{font-size:3.5rem}}.display-5{font-size:calc(1.425rem + 2.1vw);font-weight:300;line-height:1.2}@media(min-width: 1200px){.display-5{font-size:3rem}}.display-6{font-size:calc(1.375rem + 1.5vw);font-weight:300;line-height:1.2}@media(min-width: 1200px){.display-6{font-size:2.5rem}}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none}.list-inline-item{display:inline-block}.list-inline-item:not(:last-child){margin-right:.5rem}.initialism{font-size:0.875em;text-transform:uppercase}.blockquote{margin-bottom:1rem;font-size:1.25rem}.blockquote>:last-child{margin-bottom:0}.blockquote-footer{margin-top:-1rem;margin-bottom:1rem;font-size:0.875em;color:#6c757d}.blockquote-footer::before{content:"— "}.container,.container-fluid,.container-xxl,.container-xl,.container-lg,.container-md,.container-sm{--bs-gutter-x: 1.5rem;--bs-gutter-y: 0;width:100%;padding-right:calc(var(--bs-gutter-x)*.5);padding-left:calc(var(--bs-gutter-x)*.5);margin-right:auto;margin-left:auto}@media(min-width: 576px){.container-sm,.container{max-width:540px}}@media(min-width: 768px){.container-md,.container-sm,.container{max-width:720px}}@media(min-width: 992px){.container-lg,.container-md,.container-sm,.container{max-width:960px}}@media(min-width: 1200px){.container-xl,.container-lg,.container-md,.container-sm,.container{max-width:1140px}}@media(min-width: 1400px){.container-xxl,.container-xl,.container-lg,.container-md,.container-sm,.container{max-width:1320px}}.nav{--bs-nav-link-padding-x: 1rem;--bs-nav-link-padding-y: 0.5rem;--bs-nav-link-font-weight: ;--bs-nav-link-color: var(--bs-link-color);--bs-nav-link-hover-color: var(--bs-link-hover-color);--bs-nav-link-disabled-color: var(--bs-secondary-color);display:flex;flex-wrap:wrap;padding-left:0;margin-bottom:0;list-style:none}.nav-link{display:block;padding:var(--bs-nav-link-padding-y) var(--bs-nav-link-padding-x);font-size:var(--bs-nav-link-font-size);font-weight:var(--bs-nav-link-font-weight);color:var(--bs-nav-link-color);text-decoration:none;background:none;border:0;transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out}@media(prefers-reduced-motion: reduce){.nav-link{transition:none}}.nav-link:hover,.nav-link:focus{color:var(--bs-nav-link-hover-color)}.nav-link:focus-visible{outline:0;box-shadow:0 0 0 .25rem rgba(13,110,253,.25)}.nav-link.disabled,.nav-link:disabled{color:var(--bs-nav-link-disabled-color);pointer-events:none;cursor:default}.nav-tabs{--bs-nav-tabs-border-width: var(--bs-border-width);--bs-nav-tabs-border-color: var(--bs-border-color);--bs-nav-tabs-border-radius: var(--bs-border-radius);--bs-nav-tabs-link-hover-border-color: var(--bs-secondary-bg) var(--bs-secondary-bg) var(--bs-border-color);--bs-nav-tabs-link-active-color: var(--bs-emphasis-color);--bs-nav-tabs-link-active-bg: var(--bs-body-bg);--bs-nav-tabs-link-active-border-color: var(--bs-border-color) var(--bs-border-color) var(--bs-body-bg);border-bottom:var(--bs-nav-tabs-border-width) solid var(--bs-nav-tabs-border-color)}.nav-tabs .nav-link{margin-bottom:calc(-1*var(--bs-nav-tabs-border-width));border:var(--bs-nav-tabs-border-width) solid rgba(0,0,0,0);border-top-left-radius:var(--bs-nav-tabs-border-radius);border-top-right-radius:var(--bs-nav-tabs-border-radius)}.nav-tabs .nav-link:hover,.nav-tabs .nav-link:focus{isolation:isolate;border-color:var(--bs-nav-tabs-link-hover-border-color)}.nav-tabs .nav-link.active,.nav-tabs .nav-item.show .nav-link{color:var(--bs-nav-tabs-link-active-color);background-color:var(--bs-nav-tabs-link-active-bg);border-color:var(--bs-nav-tabs-link-active-border-color)}.nav-tabs .dropdown-menu{margin-top:calc(-1*var(--bs-nav-tabs-border-width));border-top-left-radius:0;border-top-right-radius:0}.nav-pills{--bs-nav-pills-border-radius: var(--bs-border-radius);--bs-nav-pills-link-active-color: #fff;--bs-nav-pills-link-active-bg: #0d6efd}.nav-pills .nav-link{border-radius:var(--bs-nav-pills-border-radius)}.nav-pills .nav-link.active,.nav-pills .show>.nav-link{color:var(--bs-nav-pills-link-active-color);background-color:var(--bs-nav-pills-link-active-bg)}.nav-underline{--bs-nav-underline-gap: 1rem;--bs-nav-underline-border-width: 0.125rem;--bs-nav-underline-link-active-color: var(--bs-emphasis-color);gap:var(--bs-nav-underline-gap)}.nav-underline .nav-link{padding-right:0;padding-left:0;border-bottom:var(--bs-nav-underline-border-width) solid rgba(0,0,0,0)}.nav-underline .nav-link:hover,.nav-underline .nav-link:focus{border-bottom-color:currentcolor}.nav-underline .nav-link.active,.nav-underline .show>.nav-link{font-weight:700;color:var(--bs-nav-underline-link-active-color);border-bottom-color:currentcolor}.nav-fill>.nav-link,.nav-fill .nav-item{flex:1 1 auto;text-align:center}.nav-justified>.nav-link,.nav-justified .nav-item{flex-basis:0;flex-grow:1;text-align:center}.nav-fill .nav-item .nav-link,.nav-justified .nav-item .nav-link{width:100%}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.navbar{--bs-navbar-padding-x: 0;--bs-navbar-padding-y: 0.5rem;--bs-navbar-color: rgba(var(--bs-emphasis-color-rgb), 0.65);--bs-navbar-hover-color: rgba(var(--bs-emphasis-color-rgb), 0.8);--bs-navbar-disabled-color: rgba(var(--bs-emphasis-color-rgb), 0.3);--bs-navbar-active-color: rgba(var(--bs-emphasis-color-rgb), 1);--bs-navbar-brand-padding-y: 0.3125rem;--bs-navbar-brand-margin-end: 1rem;--bs-navbar-brand-font-size: 1.25rem;--bs-navbar-brand-color: rgba(var(--bs-emphasis-color-rgb), 1);--bs-navbar-brand-hover-color: rgba(var(--bs-emphasis-color-rgb), 1);--bs-navbar-nav-link-padding-x: 0.5rem;--bs-navbar-toggler-padding-y: 0.25rem;--bs-navbar-toggler-padding-x: 0.75rem;--bs-navbar-toggler-font-size: 1.25rem;--bs-navbar-toggler-icon-bg: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%2833, 37, 41, 0.75%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e");--bs-navbar-toggler-border-color: rgba(var(--bs-emphasis-color-rgb), 0.15);--bs-navbar-toggler-border-radius: var(--bs-border-radius);--bs-navbar-toggler-focus-width: 0.25rem;--bs-navbar-toggler-transition: box-shadow 0.15s ease-in-out;position:relative;display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;padding:var(--bs-navbar-padding-y) var(--bs-navbar-padding-x)}.navbar>.container,.navbar>.container-fluid,.navbar>.container-sm,.navbar>.container-md,.navbar>.container-lg,.navbar>.container-xl,.navbar>.container-xxl{display:flex;flex-wrap:inherit;align-items:center;justify-content:space-between}.navbar-brand{padding-top:var(--bs-navbar-brand-padding-y);padding-bottom:var(--bs-navbar-brand-padding-y);margin-right:var(--bs-navbar-brand-margin-end);font-size:var(--bs-navbar-brand-font-size);color:var(--bs-navbar-brand-color);text-decoration:none;white-space:nowrap}.navbar-brand:hover,.navbar-brand:focus{color:var(--bs-navbar-brand-hover-color)}.navbar-nav{--bs-nav-link-padding-x: 0;--bs-nav-link-padding-y: 0.5rem;--bs-nav-link-font-weight: ;--bs-nav-link-color: var(--bs-navbar-color);--bs-nav-link-hover-color: var(--bs-navbar-hover-color);--bs-nav-link-disabled-color: var(--bs-navbar-disabled-color);display:flex;flex-direction:column;padding-left:0;margin-bottom:0;list-style:none}.navbar-nav .nav-link.active,.navbar-nav .nav-link.show{color:var(--bs-navbar-active-color)}.navbar-nav .dropdown-menu{position:static}.navbar-text{padding-top:.5rem;padding-bottom:.5rem;color:var(--bs-navbar-color)}.navbar-text a,.navbar-text a:hover,.navbar-text a:focus{color:var(--bs-navbar-active-color)}.navbar-collapse{flex-basis:100%;flex-grow:1;align-items:center}.navbar-toggler{padding:var(--bs-navbar-toggler-padding-y) var(--bs-navbar-toggler-padding-x);font-size:var(--bs-navbar-toggler-font-size);line-height:1;color:var(--bs-navbar-color);background-color:rgba(0,0,0,0);border:var(--bs-border-width) solid var(--bs-navbar-toggler-border-color);border-radius:var(--bs-navbar-toggler-border-radius);transition:var(--bs-navbar-toggler-transition)}@media(prefers-reduced-motion: reduce){.navbar-toggler{transition:none}}.navbar-toggler:hover{text-decoration:none}.navbar-toggler:focus{text-decoration:none;outline:0;box-shadow:0 0 0 var(--bs-navbar-toggler-focus-width)}.navbar-toggler-icon{display:inline-block;width:1.5em;height:1.5em;vertical-align:middle;background-image:var(--bs-navbar-toggler-icon-bg);background-repeat:no-repeat;background-position:center;background-size:100%}.navbar-nav-scroll{max-height:var(--bs-scroll-height, 75vh);overflow-y:auto}@media(min-width: 576px){.navbar-expand-sm{flex-wrap:nowrap;justify-content:flex-start}.navbar-expand-sm .navbar-nav{flex-direction:row}.navbar-expand-sm .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-sm .navbar-nav .nav-link{padding-right:var(--bs-navbar-nav-link-padding-x);padding-left:var(--bs-navbar-nav-link-padding-x)}.navbar-expand-sm .navbar-nav-scroll{overflow:visible}.navbar-expand-sm .navbar-collapse{display:flex !important;flex-basis:auto}.navbar-expand-sm .navbar-toggler{display:none}.navbar-expand-sm .offcanvas{position:static;z-index:auto;flex-grow:1;width:auto !important;height:auto !important;visibility:visible !important;background-color:rgba(0,0,0,0) !important;border:0 !important;transform:none !important;transition:none}.navbar-expand-sm .offcanvas .offcanvas-header{display:none}.navbar-expand-sm .offcanvas .offcanvas-body{display:flex;flex-grow:0;padding:0;overflow-y:visible}}@media(min-width: 768px){.navbar-expand-md{flex-wrap:nowrap;justify-content:flex-start}.navbar-expand-md .navbar-nav{flex-direction:row}.navbar-expand-md .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-md .navbar-nav .nav-link{padding-right:var(--bs-navbar-nav-link-padding-x);padding-left:var(--bs-navbar-nav-link-padding-x)}.navbar-expand-md .navbar-nav-scroll{overflow:visible}.navbar-expand-md .navbar-collapse{display:flex !important;flex-basis:auto}.navbar-expand-md .navbar-toggler{display:none}.navbar-expand-md .offcanvas{position:static;z-index:auto;flex-grow:1;width:auto !important;height:auto !important;visibility:visible !important;background-color:rgba(0,0,0,0) !important;border:0 !important;transform:none !important;transition:none}.navbar-expand-md .offcanvas .offcanvas-header{display:none}.navbar-expand-md .offcanvas .offcanvas-body{display:flex;flex-grow:0;padding:0;overflow-y:visible}}@media(min-width: 992px){.navbar-expand-lg{flex-wrap:nowrap;justify-content:flex-start}.navbar-expand-lg .navbar-nav{flex-direction:row}.navbar-expand-lg .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-lg .navbar-nav .nav-link{padding-right:var(--bs-navbar-nav-link-padding-x);padding-left:var(--bs-navbar-nav-link-padding-x)}.navbar-expand-lg .navbar-nav-scroll{overflow:visible}.navbar-expand-lg .navbar-collapse{display:flex !important;flex-basis:auto}.navbar-expand-lg .navbar-toggler{display:none}.navbar-expand-lg .offcanvas{position:static;z-index:auto;flex-grow:1;width:auto !important;height:auto !important;visibility:visible !important;background-color:rgba(0,0,0,0) !important;border:0 !important;transform:none !important;transition:none}.navbar-expand-lg .offcanvas .offcanvas-header{display:none}.navbar-expand-lg .offcanvas .offcanvas-body{display:flex;flex-grow:0;padding:0;overflow-y:visible}}@media(min-width: 1200px){.navbar-expand-xl{flex-wrap:nowrap;justify-content:flex-start}.navbar-expand-xl .navbar-nav{flex-direction:row}.navbar-expand-xl .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-xl .navbar-nav .nav-link{padding-right:var(--bs-navbar-nav-link-padding-x);padding-left:var(--bs-navbar-nav-link-padding-x)}.navbar-expand-xl .navbar-nav-scroll{overflow:visible}.navbar-expand-xl .navbar-collapse{display:flex !important;flex-basis:auto}.navbar-expand-xl .navbar-toggler{display:none}.navbar-expand-xl .offcanvas{position:static;z-index:auto;flex-grow:1;width:auto !important;height:auto !important;visibility:visible !important;background-color:rgba(0,0,0,0) !important;border:0 !important;transform:none !important;transition:none}.navbar-expand-xl .offcanvas .offcanvas-header{display:none}.navbar-expand-xl .offcanvas .offcanvas-body{display:flex;flex-grow:0;padding:0;overflow-y:visible}}@media(min-width: 1400px){.navbar-expand-xxl{flex-wrap:nowrap;justify-content:flex-start}.navbar-expand-xxl .navbar-nav{flex-direction:row}.navbar-expand-xxl .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-xxl .navbar-nav .nav-link{padding-right:var(--bs-navbar-nav-link-padding-x);padding-left:var(--bs-navbar-nav-link-padding-x)}.navbar-expand-xxl .navbar-nav-scroll{overflow:visible}.navbar-expand-xxl .navbar-collapse{display:flex !important;flex-basis:auto}.navbar-expand-xxl .navbar-toggler{display:none}.navbar-expand-xxl .offcanvas{position:static;z-index:auto;flex-grow:1;width:auto !important;height:auto !important;visibility:visible !important;background-color:rgba(0,0,0,0) !important;border:0 !important;transform:none !important;transition:none}.navbar-expand-xxl .offcanvas .offcanvas-header{display:none}.navbar-expand-xxl .offcanvas .offcanvas-body{display:flex;flex-grow:0;padding:0;overflow-y:visible}}.navbar-expand{flex-wrap:nowrap;justify-content:flex-start}.navbar-expand .navbar-nav{flex-direction:row}.navbar-expand .navbar-nav .dropdown-menu{position:absolute}.navbar-expand .navbar-nav .nav-link{padding-right:var(--bs-navbar-nav-link-padding-x);padding-left:var(--bs-navbar-nav-link-padding-x)}.navbar-expand .navbar-nav-scroll{overflow:visible}.navbar-expand .navbar-collapse{display:flex !important;flex-basis:auto}.navbar-expand .navbar-toggler{display:none}.navbar-expand .offcanvas{position:static;z-index:auto;flex-grow:1;width:auto !important;height:auto !important;visibility:visible !important;background-color:rgba(0,0,0,0) !important;border:0 !important;transform:none !important;transition:none}.navbar-expand .offcanvas .offcanvas-header{display:none}.navbar-expand .offcanvas .offcanvas-body{display:flex;flex-grow:0;padding:0;overflow-y:visible}.navbar-dark,.navbar[data-bs-theme=dark]{--bs-navbar-color: rgba(255, 255, 255, 0.55);--bs-navbar-hover-color: rgba(255, 255, 255, 0.75);--bs-navbar-disabled-color: rgba(255, 255, 255, 0.25);--bs-navbar-active-color: #fff;--bs-navbar-brand-color: #fff;--bs-navbar-brand-hover-color: #fff;--bs-navbar-toggler-border-color: rgba(255, 255, 255, 0.1);--bs-navbar-toggler-icon-bg: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%28255, 255, 255, 0.55%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e")}[data-bs-theme=dark] .navbar-toggler-icon{--bs-navbar-toggler-icon-bg: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%28255, 255, 255, 0.55%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e")}.form-label{margin-bottom:.5rem}.col-form-label{padding-top:calc(0.375rem + var(--bs-border-width));padding-bottom:calc(0.375rem + var(--bs-border-width));margin-bottom:0;font-size:inherit;line-height:1.5}.col-form-label-lg{padding-top:calc(0.5rem + var(--bs-border-width));padding-bottom:calc(0.5rem + var(--bs-border-width));font-size:1.25rem}.col-form-label-sm{padding-top:calc(0.25rem + var(--bs-border-width));padding-bottom:calc(0.25rem + var(--bs-border-width));font-size:0.875rem}.form-text{margin-top:.25rem;font-size:0.875em;color:var(--bs-secondary-color)}.form-control{display:block;width:100%;padding:.375rem .75rem;font-size:1rem;font-weight:400;line-height:1.5;color:var(--bs-body-color);appearance:none;background-color:var(--bs-body-bg);background-clip:padding-box;border:var(--bs-border-width) solid var(--bs-border-color);border-radius:var(--bs-border-radius);transition:border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media(prefers-reduced-motion: reduce){.form-control{transition:none}}.form-control[type=file]{overflow:hidden}.form-control[type=file]:not(:disabled):not([readonly]){cursor:pointer}.form-control:focus{color:var(--bs-body-color);background-color:var(--bs-body-bg);border-color:#86b7fe;outline:0;box-shadow:0 0 0 .25rem rgba(13,110,253,.25)}.form-control::-webkit-date-and-time-value{min-width:85px;height:1.5em;margin:0}.form-control::-webkit-datetime-edit{display:block;padding:0}.form-control::placeholder{color:var(--bs-secondary-color);opacity:1}.form-control:disabled{background-color:var(--bs-secondary-bg);opacity:1}.form-control::file-selector-button{padding:.375rem .75rem;margin:-0.375rem -0.75rem;margin-inline-end:.75rem;color:var(--bs-body-color);background-color:var(--bs-tertiary-bg);pointer-events:none;border-color:inherit;border-style:solid;border-width:0;border-inline-end-width:var(--bs-border-width);border-radius:0;transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media(prefers-reduced-motion: reduce){.form-control::file-selector-button{transition:none}}.form-control:hover:not(:disabled):not([readonly])::file-selector-button{background-color:var(--bs-secondary-bg)}.form-control-plaintext{display:block;width:100%;padding:.375rem 0;margin-bottom:0;line-height:1.5;color:var(--bs-body-color);background-color:rgba(0,0,0,0);border:solid rgba(0,0,0,0);border-width:var(--bs-border-width) 0}.form-control-plaintext:focus{outline:0}.form-control-plaintext.form-control-sm,.form-control-plaintext.form-control-lg{padding-right:0;padding-left:0}.form-control-sm{min-height:calc(1.5em + 0.5rem + calc(var(--bs-border-width) * 2));padding:.25rem .5rem;font-size:0.875rem;border-radius:var(--bs-border-radius-sm)}.form-control-sm::file-selector-button{padding:.25rem .5rem;margin:-0.25rem -0.5rem;margin-inline-end:.5rem}.form-control-lg{min-height:calc(1.5em + 1rem + calc(var(--bs-border-width) * 2));padding:.5rem 1rem;font-size:1.25rem;border-radius:var(--bs-border-radius-lg)}.form-control-lg::file-selector-button{padding:.5rem 1rem;margin:-0.5rem -1rem;margin-inline-end:1rem}textarea.form-control{min-height:calc(1.5em + 0.75rem + calc(var(--bs-border-width) * 2))}textarea.form-control-sm{min-height:calc(1.5em + 0.5rem + calc(var(--bs-border-width) * 2))}textarea.form-control-lg{min-height:calc(1.5em + 1rem + calc(var(--bs-border-width) * 2))}.form-control-color{width:3rem;height:calc(1.5em + 0.75rem + calc(var(--bs-border-width) * 2));padding:.375rem}.form-control-color:not(:disabled):not([readonly]){cursor:pointer}.form-control-color::-moz-color-swatch{border:0 !important;border-radius:var(--bs-border-radius)}.form-control-color::-webkit-color-swatch{border:0 !important;border-radius:var(--bs-border-radius)}.form-control-color.form-control-sm{height:calc(1.5em + 0.5rem + calc(var(--bs-border-width) * 2))}.form-control-color.form-control-lg{height:calc(1.5em + 1rem + calc(var(--bs-border-width) * 2))}.form-select{--bs-form-select-bg-img: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m2 5 6 6 6-6'/%3e%3c/svg%3e");display:block;width:100%;padding:.375rem 2.25rem .375rem .75rem;font-size:1rem;font-weight:400;line-height:1.5;color:var(--bs-body-color);appearance:none;background-color:var(--bs-body-bg);background-image:var(--bs-form-select-bg-img),var(--bs-form-select-bg-icon, none);background-repeat:no-repeat;background-position:right .75rem center;background-size:16px 12px;border:var(--bs-border-width) solid var(--bs-border-color);border-radius:var(--bs-border-radius);transition:border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media(prefers-reduced-motion: reduce){.form-select{transition:none}}.form-select:focus{border-color:#86b7fe;outline:0;box-shadow:0 0 0 .25rem rgba(13,110,253,.25)}.form-select[multiple],.form-select[size]:not([size="1"]){padding-right:.75rem;background-image:none}.form-select:disabled{background-color:var(--bs-secondary-bg)}.form-select:-moz-focusring{color:rgba(0,0,0,0);text-shadow:0 0 0 var(--bs-body-color)}.form-select-sm{padding-top:.25rem;padding-bottom:.25rem;padding-left:.5rem;font-size:0.875rem;border-radius:var(--bs-border-radius-sm)}.form-select-lg{padding-top:.5rem;padding-bottom:.5rem;padding-left:1rem;font-size:1.25rem;border-radius:var(--bs-border-radius-lg)}[data-bs-theme=dark] .form-select{--bs-form-select-bg-img: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23dee2e6' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m2 5 6 6 6-6'/%3e%3c/svg%3e")}.form-check{display:block;min-height:1.5rem;padding-left:1.5em;margin-bottom:.125rem}.form-check .form-check-input{float:left;margin-left:-1.5em}.form-check-reverse{padding-right:1.5em;padding-left:0;text-align:right}.form-check-reverse .form-check-input{float:right;margin-right:-1.5em;margin-left:0}.form-check-input{--bs-form-check-bg: var(--bs-body-bg);flex-shrink:0;width:1em;height:1em;margin-top:.25em;vertical-align:top;appearance:none;background-color:var(--bs-form-check-bg);background-image:var(--bs-form-check-bg-image);background-repeat:no-repeat;background-position:center;background-size:contain;border:var(--bs-border-width) solid var(--bs-border-color);print-color-adjust:exact}.form-check-input[type=checkbox]{border-radius:.25em}.form-check-input[type=radio]{border-radius:50%}.form-check-input:active{filter:brightness(90%)}.form-check-input:focus{border-color:#86b7fe;outline:0;box-shadow:0 0 0 .25rem rgba(13,110,253,.25)}.form-check-input:checked{background-color:#0d6efd;border-color:#0d6efd}.form-check-input:checked[type=checkbox]{--bs-form-check-bg-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3e%3cpath fill='none' stroke='%23fff' stroke-linecap='round' stroke-linejoin='round' stroke-width='3' d='m6 10 3 3 6-6'/%3e%3c/svg%3e")}.form-check-input:checked[type=radio]{--bs-form-check-bg-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='2' fill='%23fff'/%3e%3c/svg%3e")}.form-check-input[type=checkbox]:indeterminate{background-color:#0d6efd;border-color:#0d6efd;--bs-form-check-bg-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3e%3cpath fill='none' stroke='%23fff' stroke-linecap='round' stroke-linejoin='round' stroke-width='3' d='M6 10h8'/%3e%3c/svg%3e")}.form-check-input:disabled{pointer-events:none;filter:none;opacity:.5}.form-check-input[disabled]~.form-check-label,.form-check-input:disabled~.form-check-label{cursor:default;opacity:.5}.form-switch{padding-left:2.5em}.form-switch .form-check-input{--bs-form-switch-bg: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='rgba%280, 0, 0, 0.25%29'/%3e%3c/svg%3e");width:2em;margin-left:-2.5em;background-image:var(--bs-form-switch-bg);background-position:left center;border-radius:2em;transition:background-position .15s ease-in-out}@media(prefers-reduced-motion: reduce){.form-switch .form-check-input{transition:none}}.form-switch .form-check-input:focus{--bs-form-switch-bg: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%2386b7fe'/%3e%3c/svg%3e")}.form-switch .form-check-input:checked{background-position:right center;--bs-form-switch-bg: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%23fff'/%3e%3c/svg%3e")}.form-switch.form-check-reverse{padding-right:2.5em;padding-left:0}.form-switch.form-check-reverse .form-check-input{margin-right:-2.5em;margin-left:0}.form-check-inline{display:inline-block;margin-right:1rem}.btn-check{position:absolute;clip:rect(0, 0, 0, 0);pointer-events:none}.btn-check[disabled]+.btn,.btn-check:disabled+.btn{pointer-events:none;filter:none;opacity:.65}[data-bs-theme=dark] .form-switch .form-check-input:not(:checked):not(:focus){--bs-form-switch-bg: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='rgba%28255, 255, 255, 0.25%29'/%3e%3c/svg%3e")}.form-range{width:100%;height:1.5rem;padding:0;appearance:none;background-color:rgba(0,0,0,0)}.form-range:focus{outline:0}.form-range:focus::-webkit-slider-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .25rem rgba(13,110,253,.25)}.form-range:focus::-moz-range-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .25rem rgba(13,110,253,.25)}.form-range::-moz-focus-outer{border:0}.form-range::-webkit-slider-thumb{width:1rem;height:1rem;margin-top:-0.25rem;appearance:none;background-color:#0d6efd;border:0;border-radius:1rem;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media(prefers-reduced-motion: reduce){.form-range::-webkit-slider-thumb{transition:none}}.form-range::-webkit-slider-thumb:active{background-color:#b6d4fe}.form-range::-webkit-slider-runnable-track{width:100%;height:.5rem;color:rgba(0,0,0,0);cursor:pointer;background-color:var(--bs-secondary-bg);border-color:rgba(0,0,0,0);border-radius:1rem}.form-range::-moz-range-thumb{width:1rem;height:1rem;appearance:none;background-color:#0d6efd;border:0;border-radius:1rem;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media(prefers-reduced-motion: reduce){.form-range::-moz-range-thumb{transition:none}}.form-range::-moz-range-thumb:active{background-color:#b6d4fe}.form-range::-moz-range-track{width:100%;height:.5rem;color:rgba(0,0,0,0);cursor:pointer;background-color:var(--bs-secondary-bg);border-color:rgba(0,0,0,0);border-radius:1rem}.form-range:disabled{pointer-events:none}.form-range:disabled::-webkit-slider-thumb{background-color:var(--bs-secondary-color)}.form-range:disabled::-moz-range-thumb{background-color:var(--bs-secondary-color)}.form-floating{position:relative}.form-floating>.form-control,.form-floating>.form-control-plaintext,.form-floating>.form-select{height:calc(3.5rem + calc(var(--bs-border-width) * 2));min-height:calc(3.5rem + calc(var(--bs-border-width) * 2));line-height:1.25}.form-floating>label{position:absolute;top:0;left:0;z-index:2;height:100%;padding:1rem .75rem;overflow:hidden;text-align:start;text-overflow:ellipsis;white-space:nowrap;pointer-events:none;border:var(--bs-border-width) solid rgba(0,0,0,0);transform-origin:0 0;transition:opacity .1s ease-in-out,transform .1s ease-in-out}@media(prefers-reduced-motion: reduce){.form-floating>label{transition:none}}.form-floating>.form-control,.form-floating>.form-control-plaintext{padding:1rem .75rem}.form-floating>.form-control::placeholder,.form-floating>.form-control-plaintext::placeholder{color:rgba(0,0,0,0)}.form-floating>.form-control:focus,.form-floating>.form-control:not(:placeholder-shown),.form-floating>.form-control-plaintext:focus,.form-floating>.form-control-plaintext:not(:placeholder-shown){padding-top:1.625rem;padding-bottom:.625rem}.form-floating>.form-control:-webkit-autofill,.form-floating>.form-control-plaintext:-webkit-autofill{padding-top:1.625rem;padding-bottom:.625rem}.form-floating>.form-select{padding-top:1.625rem;padding-bottom:.625rem}.form-floating>.form-control:focus~label,.form-floating>.form-control:not(:placeholder-shown)~label,.form-floating>.form-control-plaintext~label,.form-floating>.form-select~label{color:rgba(var(--bs-body-color-rgb), 0.65);transform:scale(0.85) translateY(-0.5rem) translateX(0.15rem)}.form-floating>.form-control:focus~label::after,.form-floating>.form-control:not(:placeholder-shown)~label::after,.form-floating>.form-control-plaintext~label::after,.form-floating>.form-select~label::after{position:absolute;inset:1rem .375rem;z-index:-1;height:1.5em;content:"";background-color:var(--bs-body-bg);border-radius:var(--bs-border-radius)}.form-floating>.form-control:-webkit-autofill~label{color:rgba(var(--bs-body-color-rgb), 0.65);transform:scale(0.85) translateY(-0.5rem) translateX(0.15rem)}.form-floating>.form-control-plaintext~label{border-width:var(--bs-border-width) 0}.form-floating>:disabled~label,.form-floating>.form-control:disabled~label{color:#6c757d}.form-floating>:disabled~label::after,.form-floating>.form-control:disabled~label::after{background-color:var(--bs-secondary-bg)}.input-group{position:relative;display:flex;flex-wrap:wrap;align-items:stretch;width:100%}.input-group>.form-control,.input-group>.form-select,.input-group>.form-floating{position:relative;flex:1 1 auto;width:1%;min-width:0}.input-group>.form-control:focus,.input-group>.form-select:focus,.input-group>.form-floating:focus-within{z-index:5}.input-group .btn{position:relative;z-index:2}.input-group .btn:focus{z-index:5}.input-group-text{display:flex;align-items:center;padding:.375rem .75rem;font-size:1rem;font-weight:400;line-height:1.5;color:var(--bs-body-color);text-align:center;white-space:nowrap;background-color:var(--bs-tertiary-bg);border:var(--bs-border-width) solid var(--bs-border-color);border-radius:var(--bs-border-radius)}.input-group-lg>.form-control,.input-group-lg>.form-select,.input-group-lg>.input-group-text,.input-group-lg>.btn{padding:.5rem 1rem;font-size:1.25rem;border-radius:var(--bs-border-radius-lg)}.input-group-sm>.form-control,.input-group-sm>.form-select,.input-group-sm>.input-group-text,.input-group-sm>.btn{padding:.25rem .5rem;font-size:0.875rem;border-radius:var(--bs-border-radius-sm)}.input-group-lg>.form-select,.input-group-sm>.form-select{padding-right:3rem}.input-group:not(.has-validation)>:not(:last-child):not(.dropdown-toggle):not(.dropdown-menu):not(.form-floating),.input-group:not(.has-validation)>.dropdown-toggle:nth-last-child(n+3),.input-group:not(.has-validation)>.form-floating:not(:last-child)>.form-control,.input-group:not(.has-validation)>.form-floating:not(:last-child)>.form-select{border-top-right-radius:0;border-bottom-right-radius:0}.input-group.has-validation>:nth-last-child(n+3):not(.dropdown-toggle):not(.dropdown-menu):not(.form-floating),.input-group.has-validation>.dropdown-toggle:nth-last-child(n+4),.input-group.has-validation>.form-floating:nth-last-child(n+3)>.form-control,.input-group.has-validation>.form-floating:nth-last-child(n+3)>.form-select{border-top-right-radius:0;border-bottom-right-radius:0}.input-group>:not(:first-child):not(.dropdown-menu):not(.valid-tooltip):not(.valid-feedback):not(.invalid-tooltip):not(.invalid-feedback){margin-left:calc(var(--bs-border-width)*-1);border-top-left-radius:0;border-bottom-left-radius:0}.input-group>.form-floating:not(:first-child)>.form-control,.input-group>.form-floating:not(:first-child)>.form-select{border-top-left-radius:0;border-bottom-left-radius:0}.valid-feedback{display:none;width:100%;margin-top:.25rem;font-size:0.875em;color:var(--bs-form-valid-color)}.valid-tooltip{position:absolute;top:100%;z-index:5;display:none;max-width:100%;padding:.25rem .5rem;margin-top:.1rem;font-size:0.875rem;color:#fff;background-color:var(--bs-success);border-radius:var(--bs-border-radius)}.was-validated :valid~.valid-feedback,.was-validated :valid~.valid-tooltip,.is-valid~.valid-feedback,.is-valid~.valid-tooltip{display:block}.was-validated .form-control:valid,.form-control.is-valid{border-color:var(--bs-form-valid-border-color);padding-right:calc(1.5em + 0.75rem);background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%23198754' d='M2.3 6.73.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");background-repeat:no-repeat;background-position:right calc(0.375em + 0.1875rem) center;background-size:calc(0.75em + 0.375rem) calc(0.75em + 0.375rem)}.was-validated .form-control:valid:focus,.form-control.is-valid:focus{border-color:var(--bs-form-valid-border-color);box-shadow:0 0 0 .25rem rgba(var(--bs-success-rgb), 0.25)}.was-validated textarea.form-control:valid,textarea.form-control.is-valid{padding-right:calc(1.5em + 0.75rem);background-position:top calc(0.375em + 0.1875rem) right calc(0.375em + 0.1875rem)}.was-validated .form-select:valid,.form-select.is-valid{border-color:var(--bs-form-valid-border-color)}.was-validated .form-select:valid:not([multiple]):not([size]),.was-validated .form-select:valid:not([multiple])[size="1"],.form-select.is-valid:not([multiple]):not([size]),.form-select.is-valid:not([multiple])[size="1"]{--bs-form-select-bg-icon: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%23198754' d='M2.3 6.73.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");padding-right:4.125rem;background-position:right .75rem center,center right 2.25rem;background-size:16px 12px,calc(0.75em + 0.375rem) calc(0.75em + 0.375rem)}.was-validated .form-select:valid:focus,.form-select.is-valid:focus{border-color:var(--bs-form-valid-border-color);box-shadow:0 0 0 .25rem rgba(var(--bs-success-rgb), 0.25)}.was-validated .form-control-color:valid,.form-control-color.is-valid{width:calc(3rem + calc(1.5em + 0.75rem))}.was-validated .form-check-input:valid,.form-check-input.is-valid{border-color:var(--bs-form-valid-border-color)}.was-validated .form-check-input:valid:checked,.form-check-input.is-valid:checked{background-color:var(--bs-form-valid-color)}.was-validated .form-check-input:valid:focus,.form-check-input.is-valid:focus{box-shadow:0 0 0 .25rem rgba(var(--bs-success-rgb), 0.25)}.was-validated .form-check-input:valid~.form-check-label,.form-check-input.is-valid~.form-check-label{color:var(--bs-form-valid-color)}.form-check-inline .form-check-input~.valid-feedback{margin-left:.5em}.was-validated .input-group>.form-control:not(:focus):valid,.input-group>.form-control:not(:focus).is-valid,.was-validated .input-group>.form-select:not(:focus):valid,.input-group>.form-select:not(:focus).is-valid,.was-validated .input-group>.form-floating:not(:focus-within):valid,.input-group>.form-floating:not(:focus-within).is-valid{z-index:3}.invalid-feedback{display:none;width:100%;margin-top:.25rem;font-size:0.875em;color:var(--bs-form-invalid-color)}.invalid-tooltip{position:absolute;top:100%;z-index:5;display:none;max-width:100%;padding:.25rem .5rem;margin-top:.1rem;font-size:0.875rem;color:#fff;background-color:var(--bs-danger);border-radius:var(--bs-border-radius)}.was-validated :invalid~.invalid-feedback,.was-validated :invalid~.invalid-tooltip,.is-invalid~.invalid-feedback,.is-invalid~.invalid-tooltip{display:block}.was-validated .form-control:invalid,.form-control.is-invalid{border-color:var(--bs-form-invalid-border-color);padding-right:calc(1.5em + 0.75rem);background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");background-repeat:no-repeat;background-position:right calc(0.375em + 0.1875rem) center;background-size:calc(0.75em + 0.375rem) calc(0.75em + 0.375rem)}.was-validated .form-control:invalid:focus,.form-control.is-invalid:focus{border-color:var(--bs-form-invalid-border-color);box-shadow:0 0 0 .25rem rgba(var(--bs-danger-rgb), 0.25)}.was-validated textarea.form-control:invalid,textarea.form-control.is-invalid{padding-right:calc(1.5em + 0.75rem);background-position:top calc(0.375em + 0.1875rem) right calc(0.375em + 0.1875rem)}.was-validated .form-select:invalid,.form-select.is-invalid{border-color:var(--bs-form-invalid-border-color)}.was-validated .form-select:invalid:not([multiple]):not([size]),.was-validated .form-select:invalid:not([multiple])[size="1"],.form-select.is-invalid:not([multiple]):not([size]),.form-select.is-invalid:not([multiple])[size="1"]{--bs-form-select-bg-icon: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");padding-right:4.125rem;background-position:right .75rem center,center right 2.25rem;background-size:16px 12px,calc(0.75em + 0.375rem) calc(0.75em + 0.375rem)}.was-validated .form-select:invalid:focus,.form-select.is-invalid:focus{border-color:var(--bs-form-invalid-border-color);box-shadow:0 0 0 .25rem rgba(var(--bs-danger-rgb), 0.25)}.was-validated .form-control-color:invalid,.form-control-color.is-invalid{width:calc(3rem + calc(1.5em + 0.75rem))}.was-validated .form-check-input:invalid,.form-check-input.is-invalid{border-color:var(--bs-form-invalid-border-color)}.was-validated .form-check-input:invalid:checked,.form-check-input.is-invalid:checked{background-color:var(--bs-form-invalid-color)}.was-validated .form-check-input:invalid:focus,.form-check-input.is-invalid:focus{box-shadow:0 0 0 .25rem rgba(var(--bs-danger-rgb), 0.25)}.was-validated .form-check-input:invalid~.form-check-label,.form-check-input.is-invalid~.form-check-label{color:var(--bs-form-invalid-color)}.form-check-inline .form-check-input~.invalid-feedback{margin-left:.5em}.was-validated .input-group>.form-control:not(:focus):invalid,.input-group>.form-control:not(:focus).is-invalid,.was-validated .input-group>.form-select:not(:focus):invalid,.input-group>.form-select:not(:focus).is-invalid,.was-validated .input-group>.form-floating:not(:focus-within):invalid,.input-group>.form-floating:not(:focus-within).is-invalid{z-index:4}.btn{--bs-btn-padding-x: 0.75rem;--bs-btn-padding-y: 0.375rem;--bs-btn-font-family: ;--bs-btn-font-size:1rem;--bs-btn-font-weight: 400;--bs-btn-line-height: 1.5;--bs-btn-color: var(--bs-body-color);--bs-btn-bg: transparent;--bs-btn-border-width: var(--bs-border-width);--bs-btn-border-color: transparent;--bs-btn-border-radius: var(--bs-border-radius);--bs-btn-hover-border-color: transparent;--bs-btn-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 1px rgba(0, 0, 0, 0.075);--bs-btn-disabled-opacity: 0.65;--bs-btn-focus-box-shadow: 0 0 0 0.25rem rgba(var(--bs-btn-focus-shadow-rgb), .5);display:inline-block;padding:var(--bs-btn-padding-y) var(--bs-btn-padding-x);font-family:var(--bs-btn-font-family);font-size:var(--bs-btn-font-size);font-weight:var(--bs-btn-font-weight);line-height:var(--bs-btn-line-height);color:var(--bs-btn-color);text-align:center;text-decoration:none;vertical-align:middle;cursor:pointer;user-select:none;border:var(--bs-btn-border-width) solid var(--bs-btn-border-color);border-radius:var(--bs-btn-border-radius);background-color:var(--bs-btn-bg);transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media(prefers-reduced-motion: reduce){.btn{transition:none}}.btn:hover{color:var(--bs-btn-hover-color);background-color:var(--bs-btn-hover-bg);border-color:var(--bs-btn-hover-border-color)}.btn-check+.btn:hover{color:var(--bs-btn-color);background-color:var(--bs-btn-bg);border-color:var(--bs-btn-border-color)}.btn:focus-visible{color:var(--bs-btn-hover-color);background-color:var(--bs-btn-hover-bg);border-color:var(--bs-btn-hover-border-color);outline:0;box-shadow:var(--bs-btn-focus-box-shadow)}.btn-check:focus-visible+.btn{border-color:var(--bs-btn-hover-border-color);outline:0;box-shadow:var(--bs-btn-focus-box-shadow)}.btn-check:checked+.btn,:not(.btn-check)+.btn:active,.btn:first-child:active,.btn.active,.btn.show{color:var(--bs-btn-active-color);background-color:var(--bs-btn-active-bg);border-color:var(--bs-btn-active-border-color)}.btn-check:checked+.btn:focus-visible,:not(.btn-check)+.btn:active:focus-visible,.btn:first-child:active:focus-visible,.btn.active:focus-visible,.btn.show:focus-visible{box-shadow:var(--bs-btn-focus-box-shadow)}.btn:disabled,.btn.disabled,fieldset:disabled .btn{color:var(--bs-btn-disabled-color);pointer-events:none;background-color:var(--bs-btn-disabled-bg);border-color:var(--bs-btn-disabled-border-color);opacity:var(--bs-btn-disabled-opacity)}.btn-primary{--bs-btn-color: #fff;--bs-btn-bg: #0d6efd;--bs-btn-border-color: #0d6efd;--bs-btn-hover-color: #fff;--bs-btn-hover-bg: #0b5ed7;--bs-btn-hover-border-color: #0a58ca;--bs-btn-focus-shadow-rgb: 49, 132, 253;--bs-btn-active-color: #fff;--bs-btn-active-bg: #0a58ca;--bs-btn-active-border-color: #0a53be;--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);--bs-btn-disabled-color: #fff;--bs-btn-disabled-bg: #0d6efd;--bs-btn-disabled-border-color: #0d6efd}.btn-secondary{--bs-btn-color: #fff;--bs-btn-bg: #6c757d;--bs-btn-border-color: #6c757d;--bs-btn-hover-color: #fff;--bs-btn-hover-bg: #5c636a;--bs-btn-hover-border-color: #565e64;--bs-btn-focus-shadow-rgb: 130, 138, 145;--bs-btn-active-color: #fff;--bs-btn-active-bg: #565e64;--bs-btn-active-border-color: #51585e;--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);--bs-btn-disabled-color: #fff;--bs-btn-disabled-bg: #6c757d;--bs-btn-disabled-border-color: #6c757d}.btn-success{--bs-btn-color: #fff;--bs-btn-bg: #198754;--bs-btn-border-color: #198754;--bs-btn-hover-color: #fff;--bs-btn-hover-bg: #157347;--bs-btn-hover-border-color: #146c43;--bs-btn-focus-shadow-rgb: 60, 153, 110;--bs-btn-active-color: #fff;--bs-btn-active-bg: #146c43;--bs-btn-active-border-color: #13653f;--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);--bs-btn-disabled-color: #fff;--bs-btn-disabled-bg: #198754;--bs-btn-disabled-border-color: #198754}.btn-info{--bs-btn-color: #000;--bs-btn-bg: #0dcaf0;--bs-btn-border-color: #0dcaf0;--bs-btn-hover-color: #000;--bs-btn-hover-bg: #31d2f2;--bs-btn-hover-border-color: #25cff2;--bs-btn-focus-shadow-rgb: 11, 172, 204;--bs-btn-active-color: #000;--bs-btn-active-bg: #3dd5f3;--bs-btn-active-border-color: #25cff2;--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);--bs-btn-disabled-color: #000;--bs-btn-disabled-bg: #0dcaf0;--bs-btn-disabled-border-color: #0dcaf0}.btn-warning{--bs-btn-color: #000;--bs-btn-bg: #ffc107;--bs-btn-border-color: #ffc107;--bs-btn-hover-color: #000;--bs-btn-hover-bg: #ffca2c;--bs-btn-hover-border-color: #ffc720;--bs-btn-focus-shadow-rgb: 217, 164, 6;--bs-btn-active-color: #000;--bs-btn-active-bg: #ffcd39;--bs-btn-active-border-color: #ffc720;--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);--bs-btn-disabled-color: #000;--bs-btn-disabled-bg: #ffc107;--bs-btn-disabled-border-color: #ffc107}.btn-danger{--bs-btn-color: #fff;--bs-btn-bg: #dc3545;--bs-btn-border-color: #dc3545;--bs-btn-hover-color: #fff;--bs-btn-hover-bg: #bb2d3b;--bs-btn-hover-border-color: #b02a37;--bs-btn-focus-shadow-rgb: 225, 83, 97;--bs-btn-active-color: #fff;--bs-btn-active-bg: #b02a37;--bs-btn-active-border-color: #a52834;--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);--bs-btn-disabled-color: #fff;--bs-btn-disabled-bg: #dc3545;--bs-btn-disabled-border-color: #dc3545}.btn-light{--bs-btn-color: #000;--bs-btn-bg: #f8f9fa;--bs-btn-border-color: #f8f9fa;--bs-btn-hover-color: #000;--bs-btn-hover-bg: #d3d4d5;--bs-btn-hover-border-color: #c6c7c8;--bs-btn-focus-shadow-rgb: 211, 212, 213;--bs-btn-active-color: #000;--bs-btn-active-bg: #c6c7c8;--bs-btn-active-border-color: #babbbc;--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);--bs-btn-disabled-color: #000;--bs-btn-disabled-bg: #f8f9fa;--bs-btn-disabled-border-color: #f8f9fa}.btn-dark{--bs-btn-color: #fff;--bs-btn-bg: #212529;--bs-btn-border-color: #212529;--bs-btn-hover-color: #fff;--bs-btn-hover-bg: #424649;--bs-btn-hover-border-color: #373b3e;--bs-btn-focus-shadow-rgb: 66, 70, 73;--bs-btn-active-color: #fff;--bs-btn-active-bg: #4d5154;--bs-btn-active-border-color: #373b3e;--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);--bs-btn-disabled-color: #fff;--bs-btn-disabled-bg: #212529;--bs-btn-disabled-border-color: #212529}.btn-outline-primary{--bs-btn-color: #0d6efd;--bs-btn-border-color: #0d6efd;--bs-btn-hover-color: #fff;--bs-btn-hover-bg: #0d6efd;--bs-btn-hover-border-color: #0d6efd;--bs-btn-focus-shadow-rgb: 13, 110, 253;--bs-btn-active-color: #fff;--bs-btn-active-bg: #0d6efd;--bs-btn-active-border-color: #0d6efd;--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);--bs-btn-disabled-color: #0d6efd;--bs-btn-disabled-bg: transparent;--bs-btn-disabled-border-color: #0d6efd;--bs-gradient: none}.btn-outline-secondary{--bs-btn-color: #6c757d;--bs-btn-border-color: #6c757d;--bs-btn-hover-color: #fff;--bs-btn-hover-bg: #6c757d;--bs-btn-hover-border-color: #6c757d;--bs-btn-focus-shadow-rgb: 108, 117, 125;--bs-btn-active-color: #fff;--bs-btn-active-bg: #6c757d;--bs-btn-active-border-color: #6c757d;--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);--bs-btn-disabled-color: #6c757d;--bs-btn-disabled-bg: transparent;--bs-btn-disabled-border-color: #6c757d;--bs-gradient: none}.btn-outline-success{--bs-btn-color: #198754;--bs-btn-border-color: #198754;--bs-btn-hover-color: #fff;--bs-btn-hover-bg: #198754;--bs-btn-hover-border-color: #198754;--bs-btn-focus-shadow-rgb: 25, 135, 84;--bs-btn-active-color: #fff;--bs-btn-active-bg: #198754;--bs-btn-active-border-color: #198754;--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);--bs-btn-disabled-color: #198754;--bs-btn-disabled-bg: transparent;--bs-btn-disabled-border-color: #198754;--bs-gradient: none}.btn-outline-info{--bs-btn-color: #0dcaf0;--bs-btn-border-color: #0dcaf0;--bs-btn-hover-color: #000;--bs-btn-hover-bg: #0dcaf0;--bs-btn-hover-border-color: #0dcaf0;--bs-btn-focus-shadow-rgb: 13, 202, 240;--bs-btn-active-color: #000;--bs-btn-active-bg: #0dcaf0;--bs-btn-active-border-color: #0dcaf0;--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);--bs-btn-disabled-color: #0dcaf0;--bs-btn-disabled-bg: transparent;--bs-btn-disabled-border-color: #0dcaf0;--bs-gradient: none}.btn-outline-warning{--bs-btn-color: #ffc107;--bs-btn-border-color: #ffc107;--bs-btn-hover-color: #000;--bs-btn-hover-bg: #ffc107;--bs-btn-hover-border-color: #ffc107;--bs-btn-focus-shadow-rgb: 255, 193, 7;--bs-btn-active-color: #000;--bs-btn-active-bg: #ffc107;--bs-btn-active-border-color: #ffc107;--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);--bs-btn-disabled-color: #ffc107;--bs-btn-disabled-bg: transparent;--bs-btn-disabled-border-color: #ffc107;--bs-gradient: none}.btn-outline-danger{--bs-btn-color: #dc3545;--bs-btn-border-color: #dc3545;--bs-btn-hover-color: #fff;--bs-btn-hover-bg: #dc3545;--bs-btn-hover-border-color: #dc3545;--bs-btn-focus-shadow-rgb: 220, 53, 69;--bs-btn-active-color: #fff;--bs-btn-active-bg: #dc3545;--bs-btn-active-border-color: #dc3545;--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);--bs-btn-disabled-color: #dc3545;--bs-btn-disabled-bg: transparent;--bs-btn-disabled-border-color: #dc3545;--bs-gradient: none}.btn-outline-light{--bs-btn-color: #f8f9fa;--bs-btn-border-color: #f8f9fa;--bs-btn-hover-color: #000;--bs-btn-hover-bg: #f8f9fa;--bs-btn-hover-border-color: #f8f9fa;--bs-btn-focus-shadow-rgb: 248, 249, 250;--bs-btn-active-color: #000;--bs-btn-active-bg: #f8f9fa;--bs-btn-active-border-color: #f8f9fa;--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);--bs-btn-disabled-color: #f8f9fa;--bs-btn-disabled-bg: transparent;--bs-btn-disabled-border-color: #f8f9fa;--bs-gradient: none}.btn-outline-dark{--bs-btn-color: #212529;--bs-btn-border-color: #212529;--bs-btn-hover-color: #fff;--bs-btn-hover-bg: #212529;--bs-btn-hover-border-color: #212529;--bs-btn-focus-shadow-rgb: 33, 37, 41;--bs-btn-active-color: #fff;--bs-btn-active-bg: #212529;--bs-btn-active-border-color: #212529;--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);--bs-btn-disabled-color: #212529;--bs-btn-disabled-bg: transparent;--bs-btn-disabled-border-color: #212529;--bs-gradient: none}.btn-link{--bs-btn-font-weight: 400;--bs-btn-color: var(--bs-link-color);--bs-btn-bg: transparent;--bs-btn-border-color: transparent;--bs-btn-hover-color: var(--bs-link-hover-color);--bs-btn-hover-border-color: transparent;--bs-btn-active-color: var(--bs-link-hover-color);--bs-btn-active-border-color: transparent;--bs-btn-disabled-color: #6c757d;--bs-btn-disabled-border-color: transparent;--bs-btn-box-shadow: 0 0 0 #000;--bs-btn-focus-shadow-rgb: 49, 132, 253;text-decoration:underline}.btn-link:focus-visible{color:var(--bs-btn-color)}.btn-link:hover{color:var(--bs-btn-hover-color)}.btn-lg{--bs-btn-padding-y: 0.5rem;--bs-btn-padding-x: 1rem;--bs-btn-font-size:1.25rem;--bs-btn-border-radius: var(--bs-border-radius-lg)}.btn-sm{--bs-btn-padding-y: 0.25rem;--bs-btn-padding-x: 0.5rem;--bs-btn-font-size:0.875rem;--bs-btn-border-radius: var(--bs-border-radius-sm)}.fade{transition:opacity .15s linear}@media(prefers-reduced-motion: reduce){.fade{transition:none}}.fade:not(.show){opacity:0}.collapse:not(.show){display:none}.collapsing{height:0;overflow:hidden;transition:height .35s ease}@media(prefers-reduced-motion: reduce){.collapsing{transition:none}}.collapsing.collapse-horizontal{width:0;height:auto;transition:width .35s ease}@media(prefers-reduced-motion: reduce){.collapsing.collapse-horizontal{transition:none}}.btn-close{--bs-btn-close-color: #000;--bs-btn-close-bg: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23000'%3e%3cpath d='M.293.293a1 1 0 0 1 1.414 0L8 6.586 14.293.293a1 1 0 1 1 1.414 1.414L9.414 8l6.293 6.293a1 1 0 0 1-1.414 1.414L8 9.414l-6.293 6.293a1 1 0 0 1-1.414-1.414L6.586 8 .293 1.707a1 1 0 0 1 0-1.414z'/%3e%3c/svg%3e");--bs-btn-close-opacity: 0.5;--bs-btn-close-hover-opacity: 0.75;--bs-btn-close-focus-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);--bs-btn-close-focus-opacity: 1;--bs-btn-close-disabled-opacity: 0.25;--bs-btn-close-white-filter: invert(1) grayscale(100%) brightness(200%);box-sizing:content-box;width:1em;height:1em;padding:.25em .25em;color:var(--bs-btn-close-color);background:rgba(0,0,0,0) var(--bs-btn-close-bg) center/1em auto no-repeat;border:0;border-radius:.375rem;opacity:var(--bs-btn-close-opacity)}.btn-close:hover{color:var(--bs-btn-close-color);text-decoration:none;opacity:var(--bs-btn-close-hover-opacity)}.btn-close:focus{outline:0;box-shadow:var(--bs-btn-close-focus-shadow);opacity:var(--bs-btn-close-focus-opacity)}.btn-close:disabled,.btn-close.disabled{pointer-events:none;user-select:none;opacity:var(--bs-btn-close-disabled-opacity)}.btn-close-white{filter:var(--bs-btn-close-white-filter)}[data-bs-theme=dark] .btn-close{filter:var(--bs-btn-close-white-filter)}.clearfix::after{display:block;clear:both;content:""}.text-bg-primary{color:#fff !important;background-color:RGBA(var(--bs-primary-rgb), var(--bs-bg-opacity, 1)) !important}.text-bg-secondary{color:#fff !important;background-color:RGBA(var(--bs-secondary-rgb), var(--bs-bg-opacity, 1)) !important}.text-bg-success{color:#fff !important;background-color:RGBA(var(--bs-success-rgb), var(--bs-bg-opacity, 1)) !important}.text-bg-info{color:#000 !important;background-color:RGBA(var(--bs-info-rgb), var(--bs-bg-opacity, 1)) !important}.text-bg-warning{color:#000 !important;background-color:RGBA(var(--bs-warning-rgb), var(--bs-bg-opacity, 1)) !important}.text-bg-danger{color:#fff !important;background-color:RGBA(var(--bs-danger-rgb), var(--bs-bg-opacity, 1)) !important}.text-bg-light{color:#000 !important;background-color:RGBA(var(--bs-light-rgb), var(--bs-bg-opacity, 1)) !important}.text-bg-dark{color:#fff !important;background-color:RGBA(var(--bs-dark-rgb), var(--bs-bg-opacity, 1)) !important}.link-primary{color:RGBA(var(--bs-primary-rgb), var(--bs-link-opacity, 1)) !important;text-decoration-color:RGBA(var(--bs-primary-rgb), var(--bs-link-underline-opacity, 1)) !important}.link-primary:hover,.link-primary:focus{color:RGBA(10, 88, 202, var(--bs-link-opacity, 1)) !important;text-decoration-color:RGBA(10, 88, 202, var(--bs-link-underline-opacity, 1)) !important}.link-secondary{color:RGBA(var(--bs-secondary-rgb), var(--bs-link-opacity, 1)) !important;text-decoration-color:RGBA(var(--bs-secondary-rgb), var(--bs-link-underline-opacity, 1)) !important}.link-secondary:hover,.link-secondary:focus{color:RGBA(86, 94, 100, var(--bs-link-opacity, 1)) !important;text-decoration-color:RGBA(86, 94, 100, var(--bs-link-underline-opacity, 1)) !important}.link-success{color:RGBA(var(--bs-success-rgb), var(--bs-link-opacity, 1)) !important;text-decoration-color:RGBA(var(--bs-success-rgb), var(--bs-link-underline-opacity, 1)) !important}.link-success:hover,.link-success:focus{color:RGBA(20, 108, 67, var(--bs-link-opacity, 1)) !important;text-decoration-color:RGBA(20, 108, 67, var(--bs-link-underline-opacity, 1)) !important}.link-info{color:RGBA(var(--bs-info-rgb), var(--bs-link-opacity, 1)) !important;text-decoration-color:RGBA(var(--bs-info-rgb), var(--bs-link-underline-opacity, 1)) !important}.link-info:hover,.link-info:focus{color:RGBA(61, 213, 243, var(--bs-link-opacity, 1)) !important;text-decoration-color:RGBA(61, 213, 243, var(--bs-link-underline-opacity, 1)) !important}.link-warning{color:RGBA(var(--bs-warning-rgb), var(--bs-link-opacity, 1)) !important;text-decoration-color:RGBA(var(--bs-warning-rgb), var(--bs-link-underline-opacity, 1)) !important}.link-warning:hover,.link-warning:focus{color:RGBA(255, 205, 57, var(--bs-link-opacity, 1)) !important;text-decoration-color:RGBA(255, 205, 57, var(--bs-link-underline-opacity, 1)) !important}.link-danger{color:RGBA(var(--bs-danger-rgb), var(--bs-link-opacity, 1)) !important;text-decoration-color:RGBA(var(--bs-danger-rgb), var(--bs-link-underline-opacity, 1)) !important}.link-danger:hover,.link-danger:focus{color:RGBA(176, 42, 55, var(--bs-link-opacity, 1)) !important;text-decoration-color:RGBA(176, 42, 55, var(--bs-link-underline-opacity, 1)) !important}.link-light{color:RGBA(var(--bs-light-rgb), var(--bs-link-opacity, 1)) !important;text-decoration-color:RGBA(var(--bs-light-rgb), var(--bs-link-underline-opacity, 1)) !important}.link-light:hover,.link-light:focus{color:RGBA(249, 250, 251, var(--bs-link-opacity, 1)) !important;text-decoration-color:RGBA(249, 250, 251, var(--bs-link-underline-opacity, 1)) !important}.link-dark{color:RGBA(var(--bs-dark-rgb), var(--bs-link-opacity, 1)) !important;text-decoration-color:RGBA(var(--bs-dark-rgb), var(--bs-link-underline-opacity, 1)) !important}.link-dark:hover,.link-dark:focus{color:RGBA(26, 30, 33, var(--bs-link-opacity, 1)) !important;text-decoration-color:RGBA(26, 30, 33, var(--bs-link-underline-opacity, 1)) !important}.link-body-emphasis{color:RGBA(var(--bs-emphasis-color-rgb), var(--bs-link-opacity, 1)) !important;text-decoration-color:RGBA(var(--bs-emphasis-color-rgb), var(--bs-link-underline-opacity, 1)) !important}.link-body-emphasis:hover,.link-body-emphasis:focus{color:RGBA(var(--bs-emphasis-color-rgb), var(--bs-link-opacity, 0.75)) !important;text-decoration-color:RGBA(var(--bs-emphasis-color-rgb), var(--bs-link-underline-opacity, 0.75)) !important}.focus-ring:focus{outline:0;box-shadow:var(--bs-focus-ring-x, 0) var(--bs-focus-ring-y, 0) var(--bs-focus-ring-blur, 0) var(--bs-focus-ring-width) var(--bs-focus-ring-color)}.icon-link{display:inline-flex;gap:.375rem;align-items:center;text-decoration-color:rgba(var(--bs-link-color-rgb), var(--bs-link-opacity, 0.5));text-underline-offset:.25em;backface-visibility:hidden}.icon-link>.bi{flex-shrink:0;width:1em;height:1em;fill:currentcolor;transition:.2s ease-in-out transform}@media(prefers-reduced-motion: reduce){.icon-link>.bi{transition:none}}.icon-link-hover:hover>.bi,.icon-link-hover:focus-visible>.bi{transform:var(--bs-icon-link-transform, translate3d(0.25em, 0, 0))}.ratio{position:relative;width:100%}.ratio::before{display:block;padding-top:var(--bs-aspect-ratio);content:""}.ratio>*{position:absolute;top:0;left:0;width:100%;height:100%}.ratio-1x1{--bs-aspect-ratio: 100%}.ratio-4x3{--bs-aspect-ratio: 75%}.ratio-16x9{--bs-aspect-ratio: 56.25%}.ratio-21x9{--bs-aspect-ratio: 42.8571428571%}.fixed-top{position:fixed;top:0;right:0;left:0;z-index:1030}.fixed-bottom{position:fixed;right:0;bottom:0;left:0;z-index:1030}.sticky-top{position:sticky;top:0;z-index:1020}.sticky-bottom{position:sticky;bottom:0;z-index:1020}@media(min-width: 576px){.sticky-sm-top{position:sticky;top:0;z-index:1020}.sticky-sm-bottom{position:sticky;bottom:0;z-index:1020}}@media(min-width: 768px){.sticky-md-top{position:sticky;top:0;z-index:1020}.sticky-md-bottom{position:sticky;bottom:0;z-index:1020}}@media(min-width: 992px){.sticky-lg-top{position:sticky;top:0;z-index:1020}.sticky-lg-bottom{position:sticky;bottom:0;z-index:1020}}@media(min-width: 1200px){.sticky-xl-top{position:sticky;top:0;z-index:1020}.sticky-xl-bottom{position:sticky;bottom:0;z-index:1020}}@media(min-width: 1400px){.sticky-xxl-top{position:sticky;top:0;z-index:1020}.sticky-xxl-bottom{position:sticky;bottom:0;z-index:1020}}.hstack{display:flex;flex-direction:row;align-items:center;align-self:stretch}.vstack{display:flex;flex:1 1 auto;flex-direction:column;align-self:stretch}.visually-hidden,.visually-hidden-focusable:not(:focus):not(:focus-within){width:1px !important;height:1px !important;padding:0 !important;margin:-1px !important;overflow:hidden !important;clip:rect(0, 0, 0, 0) !important;white-space:nowrap !important;border:0 !important}.visually-hidden:not(caption),.visually-hidden-focusable:not(:focus):not(:focus-within):not(caption){position:absolute !important}.stretched-link::after{position:absolute;top:0;right:0;bottom:0;left:0;z-index:1;content:""}.text-truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.vr{display:inline-block;align-self:stretch;width:var(--bs-border-width);min-height:1em;background-color:currentcolor;opacity:.25}.pagination{--bs-pagination-padding-x: 0.75rem;--bs-pagination-padding-y: 0.375rem;--bs-pagination-font-size:1rem;--bs-pagination-color: var(--bs-link-color);--bs-pagination-bg: var(--bs-body-bg);--bs-pagination-border-width: var(--bs-border-width);--bs-pagination-border-color: var(--bs-border-color);--bs-pagination-border-radius: var(--bs-border-radius);--bs-pagination-hover-color: var(--bs-link-hover-color);--bs-pagination-hover-bg: var(--bs-tertiary-bg);--bs-pagination-hover-border-color: var(--bs-border-color);--bs-pagination-focus-color: var(--bs-link-hover-color);--bs-pagination-focus-bg: var(--bs-secondary-bg);--bs-pagination-focus-box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);--bs-pagination-active-color: #fff;--bs-pagination-active-bg: #0d6efd;--bs-pagination-active-border-color: #0d6efd;--bs-pagination-disabled-color: var(--bs-secondary-color);--bs-pagination-disabled-bg: var(--bs-secondary-bg);--bs-pagination-disabled-border-color: var(--bs-border-color);display:flex;padding-left:0;list-style:none}.page-link{position:relative;display:block;padding:var(--bs-pagination-padding-y) var(--bs-pagination-padding-x);font-size:var(--bs-pagination-font-size);color:var(--bs-pagination-color);text-decoration:none;background-color:var(--bs-pagination-bg);border:var(--bs-pagination-border-width) solid var(--bs-pagination-border-color);transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media(prefers-reduced-motion: reduce){.page-link{transition:none}}.page-link:hover{z-index:2;color:var(--bs-pagination-hover-color);background-color:var(--bs-pagination-hover-bg);border-color:var(--bs-pagination-hover-border-color)}.page-link:focus{z-index:3;color:var(--bs-pagination-focus-color);background-color:var(--bs-pagination-focus-bg);outline:0;box-shadow:var(--bs-pagination-focus-box-shadow)}.page-link.active,.active>.page-link{z-index:3;color:var(--bs-pagination-active-color);background-color:var(--bs-pagination-active-bg);border-color:var(--bs-pagination-active-border-color)}.page-link.disabled,.disabled>.page-link{color:var(--bs-pagination-disabled-color);pointer-events:none;background-color:var(--bs-pagination-disabled-bg);border-color:var(--bs-pagination-disabled-border-color)}.page-item:not(:first-child) .page-link{margin-left:calc(var(--bs-border-width)*-1)}.page-item:first-child .page-link{border-top-left-radius:var(--bs-pagination-border-radius);border-bottom-left-radius:var(--bs-pagination-border-radius)}.page-item:last-child .page-link{border-top-right-radius:var(--bs-pagination-border-radius);border-bottom-right-radius:var(--bs-pagination-border-radius)}.pagination-lg{--bs-pagination-padding-x: 1.5rem;--bs-pagination-padding-y: 0.75rem;--bs-pagination-font-size:1.25rem;--bs-pagination-border-radius: var(--bs-border-radius-lg)}.pagination-sm{--bs-pagination-padding-x: 0.5rem;--bs-pagination-padding-y: 0.25rem;--bs-pagination-font-size:0.875rem;--bs-pagination-border-radius: var(--bs-border-radius-sm)}.d-inline{display:inline !important}.d-inline-block{display:inline-block !important}.d-block{display:block !important}.d-grid{display:grid !important}.d-inline-grid{display:inline-grid !important}.d-table{display:table !important}.d-table-row{display:table-row !important}.d-table-cell{display:table-cell !important}.d-flex{display:flex !important}.d-inline-flex{display:inline-flex !important}.d-none{display:none !important}.flex-fill{flex:1 1 auto !important}.flex-row{flex-direction:row !important}.flex-column{flex-direction:column !important}.flex-row-reverse{flex-direction:row-reverse !important}.flex-column-reverse{flex-direction:column-reverse !important}.justify-content-start{justify-content:flex-start !important}.justify-content-end{justify-content:flex-end !important}.justify-content-center{justify-content:center !important}.justify-content-between{justify-content:space-between !important}.justify-content-around{justify-content:space-around !important}.justify-content-evenly{justify-content:space-evenly !important}.align-items-start{align-items:flex-start !important}.align-items-end{align-items:flex-end !important}.align-items-center{align-items:center !important}.align-items-baseline{align-items:baseline !important}.align-items-stretch{align-items:stretch !important}.text-start{text-align:left !important}.text-end{text-align:right !important}.text-center{text-align:center !important}.visible{visibility:visible !important}.invisible{visibility:hidden !important}@media(min-width: 576px){.d-sm-inline{display:inline !important}.d-sm-inline-block{display:inline-block !important}.d-sm-block{display:block !important}.d-sm-grid{display:grid !important}.d-sm-inline-grid{display:inline-grid !important}.d-sm-table{display:table !important}.d-sm-table-row{display:table-row !important}.d-sm-table-cell{display:table-cell !important}.d-sm-flex{display:flex !important}.d-sm-inline-flex{display:inline-flex !important}.d-sm-none{display:none !important}.flex-sm-fill{flex:1 1 auto !important}.flex-sm-row{flex-direction:row !important}.flex-sm-column{flex-direction:column !important}.flex-sm-row-reverse{flex-direction:row-reverse !important}.flex-sm-column-reverse{flex-direction:column-reverse !important}.justify-content-sm-start{justify-content:flex-start !important}.justify-content-sm-end{justify-content:flex-end !important}.justify-content-sm-center{justify-content:center !important}.justify-content-sm-between{justify-content:space-between !important}.justify-content-sm-around{justify-content:space-around !important}.justify-content-sm-evenly{justify-content:space-evenly !important}.align-items-sm-start{align-items:flex-start !important}.align-items-sm-end{align-items:flex-end !important}.align-items-sm-center{align-items:center !important}.align-items-sm-baseline{align-items:baseline !important}.align-items-sm-stretch{align-items:stretch !important}.text-sm-start{text-align:left !important}.text-sm-end{text-align:right !important}.text-sm-center{text-align:center !important}}@media(min-width: 768px){.d-md-inline{display:inline !important}.d-md-inline-block{display:inline-block !important}.d-md-block{display:block !important}.d-md-grid{display:grid !important}.d-md-inline-grid{display:inline-grid !important}.d-md-table{display:table !important}.d-md-table-row{display:table-row !important}.d-md-table-cell{display:table-cell !important}.d-md-flex{display:flex !important}.d-md-inline-flex{display:inline-flex !important}.d-md-none{display:none !important}.flex-md-fill{flex:1 1 auto !important}.flex-md-row{flex-direction:row !important}.flex-md-column{flex-direction:column !important}.flex-md-row-reverse{flex-direction:row-reverse !important}.flex-md-column-reverse{flex-direction:column-reverse !important}.justify-content-md-start{justify-content:flex-start !important}.justify-content-md-end{justify-content:flex-end !important}.justify-content-md-center{justify-content:center !important}.justify-content-md-between{justify-content:space-between !important}.justify-content-md-around{justify-content:space-around !important}.justify-content-md-evenly{justify-content:space-evenly !important}.align-items-md-start{align-items:flex-start !important}.align-items-md-end{align-items:flex-end !important}.align-items-md-center{align-items:center !important}.align-items-md-baseline{align-items:baseline !important}.align-items-md-stretch{align-items:stretch !important}.text-md-start{text-align:left !important}.text-md-end{text-align:right !important}.text-md-center{text-align:center !important}}@media(min-width: 992px){.d-lg-inline{display:inline !important}.d-lg-inline-block{display:inline-block !important}.d-lg-block{display:block !important}.d-lg-grid{display:grid !important}.d-lg-inline-grid{display:inline-grid !important}.d-lg-table{display:table !important}.d-lg-table-row{display:table-row !important}.d-lg-table-cell{display:table-cell !important}.d-lg-flex{display:flex !important}.d-lg-inline-flex{display:inline-flex !important}.d-lg-none{display:none !important}.flex-lg-fill{flex:1 1 auto !important}.flex-lg-row{flex-direction:row !important}.flex-lg-column{flex-direction:column !important}.flex-lg-row-reverse{flex-direction:row-reverse !important}.flex-lg-column-reverse{flex-direction:column-reverse !important}.justify-content-lg-start{justify-content:flex-start !important}.justify-content-lg-end{justify-content:flex-end !important}.justify-content-lg-center{justify-content:center !important}.justify-content-lg-between{justify-content:space-between !important}.justify-content-lg-around{justify-content:space-around !important}.justify-content-lg-evenly{justify-content:space-evenly !important}.align-items-lg-start{align-items:flex-start !important}.align-items-lg-end{align-items:flex-end !important}.align-items-lg-center{align-items:center !important}.align-items-lg-baseline{align-items:baseline !important}.align-items-lg-stretch{align-items:stretch !important}.text-lg-start{text-align:left !important}.text-lg-end{text-align:right !important}.text-lg-center{text-align:center !important}}@media(min-width: 1200px){.d-xl-inline{display:inline !important}.d-xl-inline-block{display:inline-block !important}.d-xl-block{display:block !important}.d-xl-grid{display:grid !important}.d-xl-inline-grid{display:inline-grid !important}.d-xl-table{display:table !important}.d-xl-table-row{display:table-row !important}.d-xl-table-cell{display:table-cell !important}.d-xl-flex{display:flex !important}.d-xl-inline-flex{display:inline-flex !important}.d-xl-none{display:none !important}.flex-xl-fill{flex:1 1 auto !important}.flex-xl-row{flex-direction:row !important}.flex-xl-column{flex-direction:column !important}.flex-xl-row-reverse{flex-direction:row-reverse !important}.flex-xl-column-reverse{flex-direction:column-reverse !important}.justify-content-xl-start{justify-content:flex-start !important}.justify-content-xl-end{justify-content:flex-end !important}.justify-content-xl-center{justify-content:center !important}.justify-content-xl-between{justify-content:space-between !important}.justify-content-xl-around{justify-content:space-around !important}.justify-content-xl-evenly{justify-content:space-evenly !important}.align-items-xl-start{align-items:flex-start !important}.align-items-xl-end{align-items:flex-end !important}.align-items-xl-center{align-items:center !important}.align-items-xl-baseline{align-items:baseline !important}.align-items-xl-stretch{align-items:stretch !important}.text-xl-start{text-align:left !important}.text-xl-end{text-align:right !important}.text-xl-center{text-align:center !important}}@media(min-width: 1400px){.d-xxl-inline{display:inline !important}.d-xxl-inline-block{display:inline-block !important}.d-xxl-block{display:block !important}.d-xxl-grid{display:grid !important}.d-xxl-inline-grid{display:inline-grid !important}.d-xxl-table{display:table !important}.d-xxl-table-row{display:table-row !important}.d-xxl-table-cell{display:table-cell !important}.d-xxl-flex{display:flex !important}.d-xxl-inline-flex{display:inline-flex !important}.d-xxl-none{display:none !important}.flex-xxl-fill{flex:1 1 auto !important}.flex-xxl-row{flex-direction:row !important}.flex-xxl-column{flex-direction:column !important}.flex-xxl-row-reverse{flex-direction:row-reverse !important}.flex-xxl-column-reverse{flex-direction:column-reverse !important}.justify-content-xxl-start{justify-content:flex-start !important}.justify-content-xxl-end{justify-content:flex-end !important}.justify-content-xxl-center{justify-content:center !important}.justify-content-xxl-between{justify-content:space-between !important}.justify-content-xxl-around{justify-content:space-around !important}.justify-content-xxl-evenly{justify-content:space-evenly !important}.align-items-xxl-start{align-items:flex-start !important}.align-items-xxl-end{align-items:flex-end !important}.align-items-xxl-center{align-items:center !important}.align-items-xxl-baseline{align-items:baseline !important}.align-items-xxl-stretch{align-items:stretch !important}.text-xxl-start{text-align:left !important}.text-xxl-end{text-align:right !important}.text-xxl-center{text-align:center !important}}@media print{.d-print-inline{display:inline !important}.d-print-inline-block{display:inline-block !important}.d-print-block{display:block !important}.d-print-grid{display:grid !important}.d-print-inline-grid{display:inline-grid !important}.d-print-table{display:table !important}.d-print-table-row{display:table-row !important}.d-print-table-cell{display:table-cell !important}.d-print-flex{display:flex !important}.d-print-inline-flex{display:inline-flex !important}.d-print-none{display:none !important}} diff --git a/examples/anlian-mq/public/vendor/bootstrap.bundle.min.js b/examples/anlian-mq/public/vendor/bootstrap.bundle.min.js deleted file mode 100644 index b1999d9..0000000 --- a/examples/anlian-mq/public/vendor/bootstrap.bundle.min.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! - * Bootstrap v5.3.2 (https://getbootstrap.com/) - * Copyright 2011-2023 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors) - * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) - */ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).bootstrap=e()}(this,(function(){"use strict";const t=new Map,e={set(e,i,n){t.has(e)||t.set(e,new Map);const s=t.get(e);s.has(i)||0===s.size?s.set(i,n):console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(s.keys())[0]}.`)},get:(e,i)=>t.has(e)&&t.get(e).get(i)||null,remove(e,i){if(!t.has(e))return;const n=t.get(e);n.delete(i),0===n.size&&t.delete(e)}},i="transitionend",n=t=>(t&&window.CSS&&window.CSS.escape&&(t=t.replace(/#([^\s"#']+)/g,((t,e)=>`#${CSS.escape(e)}`))),t),s=t=>{t.dispatchEvent(new Event(i))},o=t=>!(!t||"object"!=typeof t)&&(void 0!==t.jquery&&(t=t[0]),void 0!==t.nodeType),r=t=>o(t)?t.jquery?t[0]:t:"string"==typeof t&&t.length>0?document.querySelector(n(t)):null,a=t=>{if(!o(t)||0===t.getClientRects().length)return!1;const e="visible"===getComputedStyle(t).getPropertyValue("visibility"),i=t.closest("details:not([open])");if(!i)return e;if(i!==t){const e=t.closest("summary");if(e&&e.parentNode!==i)return!1;if(null===e)return!1}return e},l=t=>!t||t.nodeType!==Node.ELEMENT_NODE||!!t.classList.contains("disabled")||(void 0!==t.disabled?t.disabled:t.hasAttribute("disabled")&&"false"!==t.getAttribute("disabled")),c=t=>{if(!document.documentElement.attachShadow)return null;if("function"==typeof t.getRootNode){const e=t.getRootNode();return e instanceof ShadowRoot?e:null}return t instanceof ShadowRoot?t:t.parentNode?c(t.parentNode):null},h=()=>{},d=t=>{t.offsetHeight},u=()=>window.jQuery&&!document.body.hasAttribute("data-bs-no-jquery")?window.jQuery:null,f=[],p=()=>"rtl"===document.documentElement.dir,m=t=>{var e;e=()=>{const e=u();if(e){const i=t.NAME,n=e.fn[i];e.fn[i]=t.jQueryInterface,e.fn[i].Constructor=t,e.fn[i].noConflict=()=>(e.fn[i]=n,t.jQueryInterface)}},"loading"===document.readyState?(f.length||document.addEventListener("DOMContentLoaded",(()=>{for(const t of f)t()})),f.push(e)):e()},g=(t,e=[],i=t)=>"function"==typeof t?t(...e):i,_=(t,e,n=!0)=>{if(!n)return void g(t);const o=(t=>{if(!t)return 0;let{transitionDuration:e,transitionDelay:i}=window.getComputedStyle(t);const n=Number.parseFloat(e),s=Number.parseFloat(i);return n||s?(e=e.split(",")[0],i=i.split(",")[0],1e3*(Number.parseFloat(e)+Number.parseFloat(i))):0})(e)+5;let r=!1;const a=({target:n})=>{n===e&&(r=!0,e.removeEventListener(i,a),g(t))};e.addEventListener(i,a),setTimeout((()=>{r||s(e)}),o)},b=(t,e,i,n)=>{const s=t.length;let o=t.indexOf(e);return-1===o?!i&&n?t[s-1]:t[0]:(o+=i?1:-1,n&&(o=(o+s)%s),t[Math.max(0,Math.min(o,s-1))])},v=/[^.]*(?=\..*)\.|.*/,y=/\..*/,w=/::\d+$/,A={};let E=1;const T={mouseenter:"mouseover",mouseleave:"mouseout"},C=new Set(["click","dblclick","mouseup","mousedown","contextmenu","mousewheel","DOMMouseScroll","mouseover","mouseout","mousemove","selectstart","selectend","keydown","keypress","keyup","orientationchange","touchstart","touchmove","touchend","touchcancel","pointerdown","pointermove","pointerup","pointerleave","pointercancel","gesturestart","gesturechange","gestureend","focus","blur","change","reset","select","submit","focusin","focusout","load","unload","beforeunload","resize","move","DOMContentLoaded","readystatechange","error","abort","scroll"]);function O(t,e){return e&&`${e}::${E++}`||t.uidEvent||E++}function x(t){const e=O(t);return t.uidEvent=e,A[e]=A[e]||{},A[e]}function k(t,e,i=null){return Object.values(t).find((t=>t.callable===e&&t.delegationSelector===i))}function L(t,e,i){const n="string"==typeof e,s=n?i:e||i;let o=I(t);return C.has(o)||(o=t),[n,s,o]}function S(t,e,i,n,s){if("string"!=typeof e||!t)return;let[o,r,a]=L(e,i,n);if(e in T){const t=t=>function(e){if(!e.relatedTarget||e.relatedTarget!==e.delegateTarget&&!e.delegateTarget.contains(e.relatedTarget))return t.call(this,e)};r=t(r)}const l=x(t),c=l[a]||(l[a]={}),h=k(c,r,o?i:null);if(h)return void(h.oneOff=h.oneOff&&s);const d=O(r,e.replace(v,"")),u=o?function(t,e,i){return function n(s){const o=t.querySelectorAll(e);for(let{target:r}=s;r&&r!==this;r=r.parentNode)for(const a of o)if(a===r)return P(s,{delegateTarget:r}),n.oneOff&&N.off(t,s.type,e,i),i.apply(r,[s])}}(t,i,r):function(t,e){return function i(n){return P(n,{delegateTarget:t}),i.oneOff&&N.off(t,n.type,e),e.apply(t,[n])}}(t,r);u.delegationSelector=o?i:null,u.callable=r,u.oneOff=s,u.uidEvent=d,c[d]=u,t.addEventListener(a,u,o)}function D(t,e,i,n,s){const o=k(e[i],n,s);o&&(t.removeEventListener(i,o,Boolean(s)),delete e[i][o.uidEvent])}function $(t,e,i,n){const s=e[i]||{};for(const[o,r]of Object.entries(s))o.includes(n)&&D(t,e,i,r.callable,r.delegationSelector)}function I(t){return t=t.replace(y,""),T[t]||t}const N={on(t,e,i,n){S(t,e,i,n,!1)},one(t,e,i,n){S(t,e,i,n,!0)},off(t,e,i,n){if("string"!=typeof e||!t)return;const[s,o,r]=L(e,i,n),a=r!==e,l=x(t),c=l[r]||{},h=e.startsWith(".");if(void 0===o){if(h)for(const i of Object.keys(l))$(t,l,i,e.slice(1));for(const[i,n]of Object.entries(c)){const s=i.replace(w,"");a&&!e.includes(s)||D(t,l,r,n.callable,n.delegationSelector)}}else{if(!Object.keys(c).length)return;D(t,l,r,o,s?i:null)}},trigger(t,e,i){if("string"!=typeof e||!t)return null;const n=u();let s=null,o=!0,r=!0,a=!1;e!==I(e)&&n&&(s=n.Event(e,i),n(t).trigger(s),o=!s.isPropagationStopped(),r=!s.isImmediatePropagationStopped(),a=s.isDefaultPrevented());const l=P(new Event(e,{bubbles:o,cancelable:!0}),i);return a&&l.preventDefault(),r&&t.dispatchEvent(l),l.defaultPrevented&&s&&s.preventDefault(),l}};function P(t,e={}){for(const[i,n]of Object.entries(e))try{t[i]=n}catch(e){Object.defineProperty(t,i,{configurable:!0,get:()=>n})}return t}function M(t){if("true"===t)return!0;if("false"===t)return!1;if(t===Number(t).toString())return Number(t);if(""===t||"null"===t)return null;if("string"!=typeof t)return t;try{return JSON.parse(decodeURIComponent(t))}catch(e){return t}}function j(t){return t.replace(/[A-Z]/g,(t=>`-${t.toLowerCase()}`))}const F={setDataAttribute(t,e,i){t.setAttribute(`data-bs-${j(e)}`,i)},removeDataAttribute(t,e){t.removeAttribute(`data-bs-${j(e)}`)},getDataAttributes(t){if(!t)return{};const e={},i=Object.keys(t.dataset).filter((t=>t.startsWith("bs")&&!t.startsWith("bsConfig")));for(const n of i){let i=n.replace(/^bs/,"");i=i.charAt(0).toLowerCase()+i.slice(1,i.length),e[i]=M(t.dataset[n])}return e},getDataAttribute:(t,e)=>M(t.getAttribute(`data-bs-${j(e)}`))};class H{static get Default(){return{}}static get DefaultType(){return{}}static get NAME(){throw new Error('You have to implement the static method "NAME", for each component!')}_getConfig(t){return t=this._mergeConfigObj(t),t=this._configAfterMerge(t),this._typeCheckConfig(t),t}_configAfterMerge(t){return t}_mergeConfigObj(t,e){const i=o(e)?F.getDataAttribute(e,"config"):{};return{...this.constructor.Default,..."object"==typeof i?i:{},...o(e)?F.getDataAttributes(e):{},..."object"==typeof t?t:{}}}_typeCheckConfig(t,e=this.constructor.DefaultType){for(const[n,s]of Object.entries(e)){const e=t[n],r=o(e)?"element":null==(i=e)?`${i}`:Object.prototype.toString.call(i).match(/\s([a-z]+)/i)[1].toLowerCase();if(!new RegExp(s).test(r))throw new TypeError(`${this.constructor.NAME.toUpperCase()}: Option "${n}" provided type "${r}" but expected type "${s}".`)}var i}}class W extends H{constructor(t,i){super(),(t=r(t))&&(this._element=t,this._config=this._getConfig(i),e.set(this._element,this.constructor.DATA_KEY,this))}dispose(){e.remove(this._element,this.constructor.DATA_KEY),N.off(this._element,this.constructor.EVENT_KEY);for(const t of Object.getOwnPropertyNames(this))this[t]=null}_queueCallback(t,e,i=!0){_(t,e,i)}_getConfig(t){return t=this._mergeConfigObj(t,this._element),t=this._configAfterMerge(t),this._typeCheckConfig(t),t}static getInstance(t){return e.get(r(t),this.DATA_KEY)}static getOrCreateInstance(t,e={}){return this.getInstance(t)||new this(t,"object"==typeof e?e:null)}static get VERSION(){return"5.3.2"}static get DATA_KEY(){return`bs.${this.NAME}`}static get EVENT_KEY(){return`.${this.DATA_KEY}`}static eventName(t){return`${t}${this.EVENT_KEY}`}}const B=t=>{let e=t.getAttribute("data-bs-target");if(!e||"#"===e){let i=t.getAttribute("href");if(!i||!i.includes("#")&&!i.startsWith("."))return null;i.includes("#")&&!i.startsWith("#")&&(i=`#${i.split("#")[1]}`),e=i&&"#"!==i?n(i.trim()):null}return e},z={find:(t,e=document.documentElement)=>[].concat(...Element.prototype.querySelectorAll.call(e,t)),findOne:(t,e=document.documentElement)=>Element.prototype.querySelector.call(e,t),children:(t,e)=>[].concat(...t.children).filter((t=>t.matches(e))),parents(t,e){const i=[];let n=t.parentNode.closest(e);for(;n;)i.push(n),n=n.parentNode.closest(e);return i},prev(t,e){let i=t.previousElementSibling;for(;i;){if(i.matches(e))return[i];i=i.previousElementSibling}return[]},next(t,e){let i=t.nextElementSibling;for(;i;){if(i.matches(e))return[i];i=i.nextElementSibling}return[]},focusableChildren(t){const e=["a","button","input","textarea","select","details","[tabindex]",'[contenteditable="true"]'].map((t=>`${t}:not([tabindex^="-"])`)).join(",");return this.find(e,t).filter((t=>!l(t)&&a(t)))},getSelectorFromElement(t){const e=B(t);return e&&z.findOne(e)?e:null},getElementFromSelector(t){const e=B(t);return e?z.findOne(e):null},getMultipleElementsFromSelector(t){const e=B(t);return e?z.find(e):[]}},R=(t,e="hide")=>{const i=`click.dismiss${t.EVENT_KEY}`,n=t.NAME;N.on(document,i,`[data-bs-dismiss="${n}"]`,(function(i){if(["A","AREA"].includes(this.tagName)&&i.preventDefault(),l(this))return;const s=z.getElementFromSelector(this)||this.closest(`.${n}`);t.getOrCreateInstance(s)[e]()}))},q=".bs.alert",V=`close${q}`,K=`closed${q}`;class Q extends W{static get NAME(){return"alert"}close(){if(N.trigger(this._element,V).defaultPrevented)return;this._element.classList.remove("show");const t=this._element.classList.contains("fade");this._queueCallback((()=>this._destroyElement()),this._element,t)}_destroyElement(){this._element.remove(),N.trigger(this._element,K),this.dispose()}static jQueryInterface(t){return this.each((function(){const e=Q.getOrCreateInstance(this);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}R(Q,"close"),m(Q);const X='[data-bs-toggle="button"]';class Y extends W{static get NAME(){return"button"}toggle(){this._element.setAttribute("aria-pressed",this._element.classList.toggle("active"))}static jQueryInterface(t){return this.each((function(){const e=Y.getOrCreateInstance(this);"toggle"===t&&e[t]()}))}}N.on(document,"click.bs.button.data-api",X,(t=>{t.preventDefault();const e=t.target.closest(X);Y.getOrCreateInstance(e).toggle()})),m(Y);const U=".bs.swipe",G=`touchstart${U}`,J=`touchmove${U}`,Z=`touchend${U}`,tt=`pointerdown${U}`,et=`pointerup${U}`,it={endCallback:null,leftCallback:null,rightCallback:null},nt={endCallback:"(function|null)",leftCallback:"(function|null)",rightCallback:"(function|null)"};class st extends H{constructor(t,e){super(),this._element=t,t&&st.isSupported()&&(this._config=this._getConfig(e),this._deltaX=0,this._supportPointerEvents=Boolean(window.PointerEvent),this._initEvents())}static get Default(){return it}static get DefaultType(){return nt}static get NAME(){return"swipe"}dispose(){N.off(this._element,U)}_start(t){this._supportPointerEvents?this._eventIsPointerPenTouch(t)&&(this._deltaX=t.clientX):this._deltaX=t.touches[0].clientX}_end(t){this._eventIsPointerPenTouch(t)&&(this._deltaX=t.clientX-this._deltaX),this._handleSwipe(),g(this._config.endCallback)}_move(t){this._deltaX=t.touches&&t.touches.length>1?0:t.touches[0].clientX-this._deltaX}_handleSwipe(){const t=Math.abs(this._deltaX);if(t<=40)return;const e=t/this._deltaX;this._deltaX=0,e&&g(e>0?this._config.rightCallback:this._config.leftCallback)}_initEvents(){this._supportPointerEvents?(N.on(this._element,tt,(t=>this._start(t))),N.on(this._element,et,(t=>this._end(t))),this._element.classList.add("pointer-event")):(N.on(this._element,G,(t=>this._start(t))),N.on(this._element,J,(t=>this._move(t))),N.on(this._element,Z,(t=>this._end(t))))}_eventIsPointerPenTouch(t){return this._supportPointerEvents&&("pen"===t.pointerType||"touch"===t.pointerType)}static isSupported(){return"ontouchstart"in document.documentElement||navigator.maxTouchPoints>0}}const ot=".bs.carousel",rt=".data-api",at="next",lt="prev",ct="left",ht="right",dt=`slide${ot}`,ut=`slid${ot}`,ft=`keydown${ot}`,pt=`mouseenter${ot}`,mt=`mouseleave${ot}`,gt=`dragstart${ot}`,_t=`load${ot}${rt}`,bt=`click${ot}${rt}`,vt="carousel",yt="active",wt=".active",At=".carousel-item",Et=wt+At,Tt={ArrowLeft:ht,ArrowRight:ct},Ct={interval:5e3,keyboard:!0,pause:"hover",ride:!1,touch:!0,wrap:!0},Ot={interval:"(number|boolean)",keyboard:"boolean",pause:"(string|boolean)",ride:"(boolean|string)",touch:"boolean",wrap:"boolean"};class xt extends W{constructor(t,e){super(t,e),this._interval=null,this._activeElement=null,this._isSliding=!1,this.touchTimeout=null,this._swipeHelper=null,this._indicatorsElement=z.findOne(".carousel-indicators",this._element),this._addEventListeners(),this._config.ride===vt&&this.cycle()}static get Default(){return Ct}static get DefaultType(){return Ot}static get NAME(){return"carousel"}next(){this._slide(at)}nextWhenVisible(){!document.hidden&&a(this._element)&&this.next()}prev(){this._slide(lt)}pause(){this._isSliding&&s(this._element),this._clearInterval()}cycle(){this._clearInterval(),this._updateInterval(),this._interval=setInterval((()=>this.nextWhenVisible()),this._config.interval)}_maybeEnableCycle(){this._config.ride&&(this._isSliding?N.one(this._element,ut,(()=>this.cycle())):this.cycle())}to(t){const e=this._getItems();if(t>e.length-1||t<0)return;if(this._isSliding)return void N.one(this._element,ut,(()=>this.to(t)));const i=this._getItemIndex(this._getActive());if(i===t)return;const n=t>i?at:lt;this._slide(n,e[t])}dispose(){this._swipeHelper&&this._swipeHelper.dispose(),super.dispose()}_configAfterMerge(t){return t.defaultInterval=t.interval,t}_addEventListeners(){this._config.keyboard&&N.on(this._element,ft,(t=>this._keydown(t))),"hover"===this._config.pause&&(N.on(this._element,pt,(()=>this.pause())),N.on(this._element,mt,(()=>this._maybeEnableCycle()))),this._config.touch&&st.isSupported()&&this._addTouchEventListeners()}_addTouchEventListeners(){for(const t of z.find(".carousel-item img",this._element))N.on(t,gt,(t=>t.preventDefault()));const t={leftCallback:()=>this._slide(this._directionToOrder(ct)),rightCallback:()=>this._slide(this._directionToOrder(ht)),endCallback:()=>{"hover"===this._config.pause&&(this.pause(),this.touchTimeout&&clearTimeout(this.touchTimeout),this.touchTimeout=setTimeout((()=>this._maybeEnableCycle()),500+this._config.interval))}};this._swipeHelper=new st(this._element,t)}_keydown(t){if(/input|textarea/i.test(t.target.tagName))return;const e=Tt[t.key];e&&(t.preventDefault(),this._slide(this._directionToOrder(e)))}_getItemIndex(t){return this._getItems().indexOf(t)}_setActiveIndicatorElement(t){if(!this._indicatorsElement)return;const e=z.findOne(wt,this._indicatorsElement);e.classList.remove(yt),e.removeAttribute("aria-current");const i=z.findOne(`[data-bs-slide-to="${t}"]`,this._indicatorsElement);i&&(i.classList.add(yt),i.setAttribute("aria-current","true"))}_updateInterval(){const t=this._activeElement||this._getActive();if(!t)return;const e=Number.parseInt(t.getAttribute("data-bs-interval"),10);this._config.interval=e||this._config.defaultInterval}_slide(t,e=null){if(this._isSliding)return;const i=this._getActive(),n=t===at,s=e||b(this._getItems(),i,n,this._config.wrap);if(s===i)return;const o=this._getItemIndex(s),r=e=>N.trigger(this._element,e,{relatedTarget:s,direction:this._orderToDirection(t),from:this._getItemIndex(i),to:o});if(r(dt).defaultPrevented)return;if(!i||!s)return;const a=Boolean(this._interval);this.pause(),this._isSliding=!0,this._setActiveIndicatorElement(o),this._activeElement=s;const l=n?"carousel-item-start":"carousel-item-end",c=n?"carousel-item-next":"carousel-item-prev";s.classList.add(c),d(s),i.classList.add(l),s.classList.add(l),this._queueCallback((()=>{s.classList.remove(l,c),s.classList.add(yt),i.classList.remove(yt,c,l),this._isSliding=!1,r(ut)}),i,this._isAnimated()),a&&this.cycle()}_isAnimated(){return this._element.classList.contains("slide")}_getActive(){return z.findOne(Et,this._element)}_getItems(){return z.find(At,this._element)}_clearInterval(){this._interval&&(clearInterval(this._interval),this._interval=null)}_directionToOrder(t){return p()?t===ct?lt:at:t===ct?at:lt}_orderToDirection(t){return p()?t===lt?ct:ht:t===lt?ht:ct}static jQueryInterface(t){return this.each((function(){const e=xt.getOrCreateInstance(this,t);if("number"!=typeof t){if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t]()}}else e.to(t)}))}}N.on(document,bt,"[data-bs-slide], [data-bs-slide-to]",(function(t){const e=z.getElementFromSelector(this);if(!e||!e.classList.contains(vt))return;t.preventDefault();const i=xt.getOrCreateInstance(e),n=this.getAttribute("data-bs-slide-to");return n?(i.to(n),void i._maybeEnableCycle()):"next"===F.getDataAttribute(this,"slide")?(i.next(),void i._maybeEnableCycle()):(i.prev(),void i._maybeEnableCycle())})),N.on(window,_t,(()=>{const t=z.find('[data-bs-ride="carousel"]');for(const e of t)xt.getOrCreateInstance(e)})),m(xt);const kt=".bs.collapse",Lt=`show${kt}`,St=`shown${kt}`,Dt=`hide${kt}`,$t=`hidden${kt}`,It=`click${kt}.data-api`,Nt="show",Pt="collapse",Mt="collapsing",jt=`:scope .${Pt} .${Pt}`,Ft='[data-bs-toggle="collapse"]',Ht={parent:null,toggle:!0},Wt={parent:"(null|element)",toggle:"boolean"};class Bt extends W{constructor(t,e){super(t,e),this._isTransitioning=!1,this._triggerArray=[];const i=z.find(Ft);for(const t of i){const e=z.getSelectorFromElement(t),i=z.find(e).filter((t=>t===this._element));null!==e&&i.length&&this._triggerArray.push(t)}this._initializeChildren(),this._config.parent||this._addAriaAndCollapsedClass(this._triggerArray,this._isShown()),this._config.toggle&&this.toggle()}static get Default(){return Ht}static get DefaultType(){return Wt}static get NAME(){return"collapse"}toggle(){this._isShown()?this.hide():this.show()}show(){if(this._isTransitioning||this._isShown())return;let t=[];if(this._config.parent&&(t=this._getFirstLevelChildren(".collapse.show, .collapse.collapsing").filter((t=>t!==this._element)).map((t=>Bt.getOrCreateInstance(t,{toggle:!1})))),t.length&&t[0]._isTransitioning)return;if(N.trigger(this._element,Lt).defaultPrevented)return;for(const e of t)e.hide();const e=this._getDimension();this._element.classList.remove(Pt),this._element.classList.add(Mt),this._element.style[e]=0,this._addAriaAndCollapsedClass(this._triggerArray,!0),this._isTransitioning=!0;const i=`scroll${e[0].toUpperCase()+e.slice(1)}`;this._queueCallback((()=>{this._isTransitioning=!1,this._element.classList.remove(Mt),this._element.classList.add(Pt,Nt),this._element.style[e]="",N.trigger(this._element,St)}),this._element,!0),this._element.style[e]=`${this._element[i]}px`}hide(){if(this._isTransitioning||!this._isShown())return;if(N.trigger(this._element,Dt).defaultPrevented)return;const t=this._getDimension();this._element.style[t]=`${this._element.getBoundingClientRect()[t]}px`,d(this._element),this._element.classList.add(Mt),this._element.classList.remove(Pt,Nt);for(const t of this._triggerArray){const e=z.getElementFromSelector(t);e&&!this._isShown(e)&&this._addAriaAndCollapsedClass([t],!1)}this._isTransitioning=!0,this._element.style[t]="",this._queueCallback((()=>{this._isTransitioning=!1,this._element.classList.remove(Mt),this._element.classList.add(Pt),N.trigger(this._element,$t)}),this._element,!0)}_isShown(t=this._element){return t.classList.contains(Nt)}_configAfterMerge(t){return t.toggle=Boolean(t.toggle),t.parent=r(t.parent),t}_getDimension(){return this._element.classList.contains("collapse-horizontal")?"width":"height"}_initializeChildren(){if(!this._config.parent)return;const t=this._getFirstLevelChildren(Ft);for(const e of t){const t=z.getElementFromSelector(e);t&&this._addAriaAndCollapsedClass([e],this._isShown(t))}}_getFirstLevelChildren(t){const e=z.find(jt,this._config.parent);return z.find(t,this._config.parent).filter((t=>!e.includes(t)))}_addAriaAndCollapsedClass(t,e){if(t.length)for(const i of t)i.classList.toggle("collapsed",!e),i.setAttribute("aria-expanded",e)}static jQueryInterface(t){const e={};return"string"==typeof t&&/show|hide/.test(t)&&(e.toggle=!1),this.each((function(){const i=Bt.getOrCreateInstance(this,e);if("string"==typeof t){if(void 0===i[t])throw new TypeError(`No method named "${t}"`);i[t]()}}))}}N.on(document,It,Ft,(function(t){("A"===t.target.tagName||t.delegateTarget&&"A"===t.delegateTarget.tagName)&&t.preventDefault();for(const t of z.getMultipleElementsFromSelector(this))Bt.getOrCreateInstance(t,{toggle:!1}).toggle()})),m(Bt);var zt="top",Rt="bottom",qt="right",Vt="left",Kt="auto",Qt=[zt,Rt,qt,Vt],Xt="start",Yt="end",Ut="clippingParents",Gt="viewport",Jt="popper",Zt="reference",te=Qt.reduce((function(t,e){return t.concat([e+"-"+Xt,e+"-"+Yt])}),[]),ee=[].concat(Qt,[Kt]).reduce((function(t,e){return t.concat([e,e+"-"+Xt,e+"-"+Yt])}),[]),ie="beforeRead",ne="read",se="afterRead",oe="beforeMain",re="main",ae="afterMain",le="beforeWrite",ce="write",he="afterWrite",de=[ie,ne,se,oe,re,ae,le,ce,he];function ue(t){return t?(t.nodeName||"").toLowerCase():null}function fe(t){if(null==t)return window;if("[object Window]"!==t.toString()){var e=t.ownerDocument;return e&&e.defaultView||window}return t}function pe(t){return t instanceof fe(t).Element||t instanceof Element}function me(t){return t instanceof fe(t).HTMLElement||t instanceof HTMLElement}function ge(t){return"undefined"!=typeof ShadowRoot&&(t instanceof fe(t).ShadowRoot||t instanceof ShadowRoot)}const _e={name:"applyStyles",enabled:!0,phase:"write",fn:function(t){var e=t.state;Object.keys(e.elements).forEach((function(t){var i=e.styles[t]||{},n=e.attributes[t]||{},s=e.elements[t];me(s)&&ue(s)&&(Object.assign(s.style,i),Object.keys(n).forEach((function(t){var e=n[t];!1===e?s.removeAttribute(t):s.setAttribute(t,!0===e?"":e)})))}))},effect:function(t){var e=t.state,i={popper:{position:e.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(e.elements.popper.style,i.popper),e.styles=i,e.elements.arrow&&Object.assign(e.elements.arrow.style,i.arrow),function(){Object.keys(e.elements).forEach((function(t){var n=e.elements[t],s=e.attributes[t]||{},o=Object.keys(e.styles.hasOwnProperty(t)?e.styles[t]:i[t]).reduce((function(t,e){return t[e]="",t}),{});me(n)&&ue(n)&&(Object.assign(n.style,o),Object.keys(s).forEach((function(t){n.removeAttribute(t)})))}))}},requires:["computeStyles"]};function be(t){return t.split("-")[0]}var ve=Math.max,ye=Math.min,we=Math.round;function Ae(){var t=navigator.userAgentData;return null!=t&&t.brands&&Array.isArray(t.brands)?t.brands.map((function(t){return t.brand+"/"+t.version})).join(" "):navigator.userAgent}function Ee(){return!/^((?!chrome|android).)*safari/i.test(Ae())}function Te(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=!1);var n=t.getBoundingClientRect(),s=1,o=1;e&&me(t)&&(s=t.offsetWidth>0&&we(n.width)/t.offsetWidth||1,o=t.offsetHeight>0&&we(n.height)/t.offsetHeight||1);var r=(pe(t)?fe(t):window).visualViewport,a=!Ee()&&i,l=(n.left+(a&&r?r.offsetLeft:0))/s,c=(n.top+(a&&r?r.offsetTop:0))/o,h=n.width/s,d=n.height/o;return{width:h,height:d,top:c,right:l+h,bottom:c+d,left:l,x:l,y:c}}function Ce(t){var e=Te(t),i=t.offsetWidth,n=t.offsetHeight;return Math.abs(e.width-i)<=1&&(i=e.width),Math.abs(e.height-n)<=1&&(n=e.height),{x:t.offsetLeft,y:t.offsetTop,width:i,height:n}}function Oe(t,e){var i=e.getRootNode&&e.getRootNode();if(t.contains(e))return!0;if(i&&ge(i)){var n=e;do{if(n&&t.isSameNode(n))return!0;n=n.parentNode||n.host}while(n)}return!1}function xe(t){return fe(t).getComputedStyle(t)}function ke(t){return["table","td","th"].indexOf(ue(t))>=0}function Le(t){return((pe(t)?t.ownerDocument:t.document)||window.document).documentElement}function Se(t){return"html"===ue(t)?t:t.assignedSlot||t.parentNode||(ge(t)?t.host:null)||Le(t)}function De(t){return me(t)&&"fixed"!==xe(t).position?t.offsetParent:null}function $e(t){for(var e=fe(t),i=De(t);i&&ke(i)&&"static"===xe(i).position;)i=De(i);return i&&("html"===ue(i)||"body"===ue(i)&&"static"===xe(i).position)?e:i||function(t){var e=/firefox/i.test(Ae());if(/Trident/i.test(Ae())&&me(t)&&"fixed"===xe(t).position)return null;var i=Se(t);for(ge(i)&&(i=i.host);me(i)&&["html","body"].indexOf(ue(i))<0;){var n=xe(i);if("none"!==n.transform||"none"!==n.perspective||"paint"===n.contain||-1!==["transform","perspective"].indexOf(n.willChange)||e&&"filter"===n.willChange||e&&n.filter&&"none"!==n.filter)return i;i=i.parentNode}return null}(t)||e}function Ie(t){return["top","bottom"].indexOf(t)>=0?"x":"y"}function Ne(t,e,i){return ve(t,ye(e,i))}function Pe(t){return Object.assign({},{top:0,right:0,bottom:0,left:0},t)}function Me(t,e){return e.reduce((function(e,i){return e[i]=t,e}),{})}const je={name:"arrow",enabled:!0,phase:"main",fn:function(t){var e,i=t.state,n=t.name,s=t.options,o=i.elements.arrow,r=i.modifiersData.popperOffsets,a=be(i.placement),l=Ie(a),c=[Vt,qt].indexOf(a)>=0?"height":"width";if(o&&r){var h=function(t,e){return Pe("number"!=typeof(t="function"==typeof t?t(Object.assign({},e.rects,{placement:e.placement})):t)?t:Me(t,Qt))}(s.padding,i),d=Ce(o),u="y"===l?zt:Vt,f="y"===l?Rt:qt,p=i.rects.reference[c]+i.rects.reference[l]-r[l]-i.rects.popper[c],m=r[l]-i.rects.reference[l],g=$e(o),_=g?"y"===l?g.clientHeight||0:g.clientWidth||0:0,b=p/2-m/2,v=h[u],y=_-d[c]-h[f],w=_/2-d[c]/2+b,A=Ne(v,w,y),E=l;i.modifiersData[n]=((e={})[E]=A,e.centerOffset=A-w,e)}},effect:function(t){var e=t.state,i=t.options.element,n=void 0===i?"[data-popper-arrow]":i;null!=n&&("string"!=typeof n||(n=e.elements.popper.querySelector(n)))&&Oe(e.elements.popper,n)&&(e.elements.arrow=n)},requires:["popperOffsets"],requiresIfExists:["preventOverflow"]};function Fe(t){return t.split("-")[1]}var He={top:"auto",right:"auto",bottom:"auto",left:"auto"};function We(t){var e,i=t.popper,n=t.popperRect,s=t.placement,o=t.variation,r=t.offsets,a=t.position,l=t.gpuAcceleration,c=t.adaptive,h=t.roundOffsets,d=t.isFixed,u=r.x,f=void 0===u?0:u,p=r.y,m=void 0===p?0:p,g="function"==typeof h?h({x:f,y:m}):{x:f,y:m};f=g.x,m=g.y;var _=r.hasOwnProperty("x"),b=r.hasOwnProperty("y"),v=Vt,y=zt,w=window;if(c){var A=$e(i),E="clientHeight",T="clientWidth";A===fe(i)&&"static"!==xe(A=Le(i)).position&&"absolute"===a&&(E="scrollHeight",T="scrollWidth"),(s===zt||(s===Vt||s===qt)&&o===Yt)&&(y=Rt,m-=(d&&A===w&&w.visualViewport?w.visualViewport.height:A[E])-n.height,m*=l?1:-1),s!==Vt&&(s!==zt&&s!==Rt||o!==Yt)||(v=qt,f-=(d&&A===w&&w.visualViewport?w.visualViewport.width:A[T])-n.width,f*=l?1:-1)}var C,O=Object.assign({position:a},c&&He),x=!0===h?function(t,e){var i=t.x,n=t.y,s=e.devicePixelRatio||1;return{x:we(i*s)/s||0,y:we(n*s)/s||0}}({x:f,y:m},fe(i)):{x:f,y:m};return f=x.x,m=x.y,l?Object.assign({},O,((C={})[y]=b?"0":"",C[v]=_?"0":"",C.transform=(w.devicePixelRatio||1)<=1?"translate("+f+"px, "+m+"px)":"translate3d("+f+"px, "+m+"px, 0)",C)):Object.assign({},O,((e={})[y]=b?m+"px":"",e[v]=_?f+"px":"",e.transform="",e))}const Be={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:function(t){var e=t.state,i=t.options,n=i.gpuAcceleration,s=void 0===n||n,o=i.adaptive,r=void 0===o||o,a=i.roundOffsets,l=void 0===a||a,c={placement:be(e.placement),variation:Fe(e.placement),popper:e.elements.popper,popperRect:e.rects.popper,gpuAcceleration:s,isFixed:"fixed"===e.options.strategy};null!=e.modifiersData.popperOffsets&&(e.styles.popper=Object.assign({},e.styles.popper,We(Object.assign({},c,{offsets:e.modifiersData.popperOffsets,position:e.options.strategy,adaptive:r,roundOffsets:l})))),null!=e.modifiersData.arrow&&(e.styles.arrow=Object.assign({},e.styles.arrow,We(Object.assign({},c,{offsets:e.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:l})))),e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-placement":e.placement})},data:{}};var ze={passive:!0};const Re={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:function(t){var e=t.state,i=t.instance,n=t.options,s=n.scroll,o=void 0===s||s,r=n.resize,a=void 0===r||r,l=fe(e.elements.popper),c=[].concat(e.scrollParents.reference,e.scrollParents.popper);return o&&c.forEach((function(t){t.addEventListener("scroll",i.update,ze)})),a&&l.addEventListener("resize",i.update,ze),function(){o&&c.forEach((function(t){t.removeEventListener("scroll",i.update,ze)})),a&&l.removeEventListener("resize",i.update,ze)}},data:{}};var qe={left:"right",right:"left",bottom:"top",top:"bottom"};function Ve(t){return t.replace(/left|right|bottom|top/g,(function(t){return qe[t]}))}var Ke={start:"end",end:"start"};function Qe(t){return t.replace(/start|end/g,(function(t){return Ke[t]}))}function Xe(t){var e=fe(t);return{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function Ye(t){return Te(Le(t)).left+Xe(t).scrollLeft}function Ue(t){var e=xe(t),i=e.overflow,n=e.overflowX,s=e.overflowY;return/auto|scroll|overlay|hidden/.test(i+s+n)}function Ge(t){return["html","body","#document"].indexOf(ue(t))>=0?t.ownerDocument.body:me(t)&&Ue(t)?t:Ge(Se(t))}function Je(t,e){var i;void 0===e&&(e=[]);var n=Ge(t),s=n===(null==(i=t.ownerDocument)?void 0:i.body),o=fe(n),r=s?[o].concat(o.visualViewport||[],Ue(n)?n:[]):n,a=e.concat(r);return s?a:a.concat(Je(Se(r)))}function Ze(t){return Object.assign({},t,{left:t.x,top:t.y,right:t.x+t.width,bottom:t.y+t.height})}function ti(t,e,i){return e===Gt?Ze(function(t,e){var i=fe(t),n=Le(t),s=i.visualViewport,o=n.clientWidth,r=n.clientHeight,a=0,l=0;if(s){o=s.width,r=s.height;var c=Ee();(c||!c&&"fixed"===e)&&(a=s.offsetLeft,l=s.offsetTop)}return{width:o,height:r,x:a+Ye(t),y:l}}(t,i)):pe(e)?function(t,e){var i=Te(t,!1,"fixed"===e);return i.top=i.top+t.clientTop,i.left=i.left+t.clientLeft,i.bottom=i.top+t.clientHeight,i.right=i.left+t.clientWidth,i.width=t.clientWidth,i.height=t.clientHeight,i.x=i.left,i.y=i.top,i}(e,i):Ze(function(t){var e,i=Le(t),n=Xe(t),s=null==(e=t.ownerDocument)?void 0:e.body,o=ve(i.scrollWidth,i.clientWidth,s?s.scrollWidth:0,s?s.clientWidth:0),r=ve(i.scrollHeight,i.clientHeight,s?s.scrollHeight:0,s?s.clientHeight:0),a=-n.scrollLeft+Ye(t),l=-n.scrollTop;return"rtl"===xe(s||i).direction&&(a+=ve(i.clientWidth,s?s.clientWidth:0)-o),{width:o,height:r,x:a,y:l}}(Le(t)))}function ei(t){var e,i=t.reference,n=t.element,s=t.placement,o=s?be(s):null,r=s?Fe(s):null,a=i.x+i.width/2-n.width/2,l=i.y+i.height/2-n.height/2;switch(o){case zt:e={x:a,y:i.y-n.height};break;case Rt:e={x:a,y:i.y+i.height};break;case qt:e={x:i.x+i.width,y:l};break;case Vt:e={x:i.x-n.width,y:l};break;default:e={x:i.x,y:i.y}}var c=o?Ie(o):null;if(null!=c){var h="y"===c?"height":"width";switch(r){case Xt:e[c]=e[c]-(i[h]/2-n[h]/2);break;case Yt:e[c]=e[c]+(i[h]/2-n[h]/2)}}return e}function ii(t,e){void 0===e&&(e={});var i=e,n=i.placement,s=void 0===n?t.placement:n,o=i.strategy,r=void 0===o?t.strategy:o,a=i.boundary,l=void 0===a?Ut:a,c=i.rootBoundary,h=void 0===c?Gt:c,d=i.elementContext,u=void 0===d?Jt:d,f=i.altBoundary,p=void 0!==f&&f,m=i.padding,g=void 0===m?0:m,_=Pe("number"!=typeof g?g:Me(g,Qt)),b=u===Jt?Zt:Jt,v=t.rects.popper,y=t.elements[p?b:u],w=function(t,e,i,n){var s="clippingParents"===e?function(t){var e=Je(Se(t)),i=["absolute","fixed"].indexOf(xe(t).position)>=0&&me(t)?$e(t):t;return pe(i)?e.filter((function(t){return pe(t)&&Oe(t,i)&&"body"!==ue(t)})):[]}(t):[].concat(e),o=[].concat(s,[i]),r=o[0],a=o.reduce((function(e,i){var s=ti(t,i,n);return e.top=ve(s.top,e.top),e.right=ye(s.right,e.right),e.bottom=ye(s.bottom,e.bottom),e.left=ve(s.left,e.left),e}),ti(t,r,n));return a.width=a.right-a.left,a.height=a.bottom-a.top,a.x=a.left,a.y=a.top,a}(pe(y)?y:y.contextElement||Le(t.elements.popper),l,h,r),A=Te(t.elements.reference),E=ei({reference:A,element:v,strategy:"absolute",placement:s}),T=Ze(Object.assign({},v,E)),C=u===Jt?T:A,O={top:w.top-C.top+_.top,bottom:C.bottom-w.bottom+_.bottom,left:w.left-C.left+_.left,right:C.right-w.right+_.right},x=t.modifiersData.offset;if(u===Jt&&x){var k=x[s];Object.keys(O).forEach((function(t){var e=[qt,Rt].indexOf(t)>=0?1:-1,i=[zt,Rt].indexOf(t)>=0?"y":"x";O[t]+=k[i]*e}))}return O}function ni(t,e){void 0===e&&(e={});var i=e,n=i.placement,s=i.boundary,o=i.rootBoundary,r=i.padding,a=i.flipVariations,l=i.allowedAutoPlacements,c=void 0===l?ee:l,h=Fe(n),d=h?a?te:te.filter((function(t){return Fe(t)===h})):Qt,u=d.filter((function(t){return c.indexOf(t)>=0}));0===u.length&&(u=d);var f=u.reduce((function(e,i){return e[i]=ii(t,{placement:i,boundary:s,rootBoundary:o,padding:r})[be(i)],e}),{});return Object.keys(f).sort((function(t,e){return f[t]-f[e]}))}const si={name:"flip",enabled:!0,phase:"main",fn:function(t){var e=t.state,i=t.options,n=t.name;if(!e.modifiersData[n]._skip){for(var s=i.mainAxis,o=void 0===s||s,r=i.altAxis,a=void 0===r||r,l=i.fallbackPlacements,c=i.padding,h=i.boundary,d=i.rootBoundary,u=i.altBoundary,f=i.flipVariations,p=void 0===f||f,m=i.allowedAutoPlacements,g=e.options.placement,_=be(g),b=l||(_!==g&&p?function(t){if(be(t)===Kt)return[];var e=Ve(t);return[Qe(t),e,Qe(e)]}(g):[Ve(g)]),v=[g].concat(b).reduce((function(t,i){return t.concat(be(i)===Kt?ni(e,{placement:i,boundary:h,rootBoundary:d,padding:c,flipVariations:p,allowedAutoPlacements:m}):i)}),[]),y=e.rects.reference,w=e.rects.popper,A=new Map,E=!0,T=v[0],C=0;C=0,S=L?"width":"height",D=ii(e,{placement:O,boundary:h,rootBoundary:d,altBoundary:u,padding:c}),$=L?k?qt:Vt:k?Rt:zt;y[S]>w[S]&&($=Ve($));var I=Ve($),N=[];if(o&&N.push(D[x]<=0),a&&N.push(D[$]<=0,D[I]<=0),N.every((function(t){return t}))){T=O,E=!1;break}A.set(O,N)}if(E)for(var P=function(t){var e=v.find((function(e){var i=A.get(e);if(i)return i.slice(0,t).every((function(t){return t}))}));if(e)return T=e,"break"},M=p?3:1;M>0&&"break"!==P(M);M--);e.placement!==T&&(e.modifiersData[n]._skip=!0,e.placement=T,e.reset=!0)}},requiresIfExists:["offset"],data:{_skip:!1}};function oi(t,e,i){return void 0===i&&(i={x:0,y:0}),{top:t.top-e.height-i.y,right:t.right-e.width+i.x,bottom:t.bottom-e.height+i.y,left:t.left-e.width-i.x}}function ri(t){return[zt,qt,Rt,Vt].some((function(e){return t[e]>=0}))}const ai={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:function(t){var e=t.state,i=t.name,n=e.rects.reference,s=e.rects.popper,o=e.modifiersData.preventOverflow,r=ii(e,{elementContext:"reference"}),a=ii(e,{altBoundary:!0}),l=oi(r,n),c=oi(a,s,o),h=ri(l),d=ri(c);e.modifiersData[i]={referenceClippingOffsets:l,popperEscapeOffsets:c,isReferenceHidden:h,hasPopperEscaped:d},e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-reference-hidden":h,"data-popper-escaped":d})}},li={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:function(t){var e=t.state,i=t.options,n=t.name,s=i.offset,o=void 0===s?[0,0]:s,r=ee.reduce((function(t,i){return t[i]=function(t,e,i){var n=be(t),s=[Vt,zt].indexOf(n)>=0?-1:1,o="function"==typeof i?i(Object.assign({},e,{placement:t})):i,r=o[0],a=o[1];return r=r||0,a=(a||0)*s,[Vt,qt].indexOf(n)>=0?{x:a,y:r}:{x:r,y:a}}(i,e.rects,o),t}),{}),a=r[e.placement],l=a.x,c=a.y;null!=e.modifiersData.popperOffsets&&(e.modifiersData.popperOffsets.x+=l,e.modifiersData.popperOffsets.y+=c),e.modifiersData[n]=r}},ci={name:"popperOffsets",enabled:!0,phase:"read",fn:function(t){var e=t.state,i=t.name;e.modifiersData[i]=ei({reference:e.rects.reference,element:e.rects.popper,strategy:"absolute",placement:e.placement})},data:{}},hi={name:"preventOverflow",enabled:!0,phase:"main",fn:function(t){var e=t.state,i=t.options,n=t.name,s=i.mainAxis,o=void 0===s||s,r=i.altAxis,a=void 0!==r&&r,l=i.boundary,c=i.rootBoundary,h=i.altBoundary,d=i.padding,u=i.tether,f=void 0===u||u,p=i.tetherOffset,m=void 0===p?0:p,g=ii(e,{boundary:l,rootBoundary:c,padding:d,altBoundary:h}),_=be(e.placement),b=Fe(e.placement),v=!b,y=Ie(_),w="x"===y?"y":"x",A=e.modifiersData.popperOffsets,E=e.rects.reference,T=e.rects.popper,C="function"==typeof m?m(Object.assign({},e.rects,{placement:e.placement})):m,O="number"==typeof C?{mainAxis:C,altAxis:C}:Object.assign({mainAxis:0,altAxis:0},C),x=e.modifiersData.offset?e.modifiersData.offset[e.placement]:null,k={x:0,y:0};if(A){if(o){var L,S="y"===y?zt:Vt,D="y"===y?Rt:qt,$="y"===y?"height":"width",I=A[y],N=I+g[S],P=I-g[D],M=f?-T[$]/2:0,j=b===Xt?E[$]:T[$],F=b===Xt?-T[$]:-E[$],H=e.elements.arrow,W=f&&H?Ce(H):{width:0,height:0},B=e.modifiersData["arrow#persistent"]?e.modifiersData["arrow#persistent"].padding:{top:0,right:0,bottom:0,left:0},z=B[S],R=B[D],q=Ne(0,E[$],W[$]),V=v?E[$]/2-M-q-z-O.mainAxis:j-q-z-O.mainAxis,K=v?-E[$]/2+M+q+R+O.mainAxis:F+q+R+O.mainAxis,Q=e.elements.arrow&&$e(e.elements.arrow),X=Q?"y"===y?Q.clientTop||0:Q.clientLeft||0:0,Y=null!=(L=null==x?void 0:x[y])?L:0,U=I+K-Y,G=Ne(f?ye(N,I+V-Y-X):N,I,f?ve(P,U):P);A[y]=G,k[y]=G-I}if(a){var J,Z="x"===y?zt:Vt,tt="x"===y?Rt:qt,et=A[w],it="y"===w?"height":"width",nt=et+g[Z],st=et-g[tt],ot=-1!==[zt,Vt].indexOf(_),rt=null!=(J=null==x?void 0:x[w])?J:0,at=ot?nt:et-E[it]-T[it]-rt+O.altAxis,lt=ot?et+E[it]+T[it]-rt-O.altAxis:st,ct=f&&ot?function(t,e,i){var n=Ne(t,e,i);return n>i?i:n}(at,et,lt):Ne(f?at:nt,et,f?lt:st);A[w]=ct,k[w]=ct-et}e.modifiersData[n]=k}},requiresIfExists:["offset"]};function di(t,e,i){void 0===i&&(i=!1);var n,s,o=me(e),r=me(e)&&function(t){var e=t.getBoundingClientRect(),i=we(e.width)/t.offsetWidth||1,n=we(e.height)/t.offsetHeight||1;return 1!==i||1!==n}(e),a=Le(e),l=Te(t,r,i),c={scrollLeft:0,scrollTop:0},h={x:0,y:0};return(o||!o&&!i)&&(("body"!==ue(e)||Ue(a))&&(c=(n=e)!==fe(n)&&me(n)?{scrollLeft:(s=n).scrollLeft,scrollTop:s.scrollTop}:Xe(n)),me(e)?((h=Te(e,!0)).x+=e.clientLeft,h.y+=e.clientTop):a&&(h.x=Ye(a))),{x:l.left+c.scrollLeft-h.x,y:l.top+c.scrollTop-h.y,width:l.width,height:l.height}}function ui(t){var e=new Map,i=new Set,n=[];function s(t){i.add(t.name),[].concat(t.requires||[],t.requiresIfExists||[]).forEach((function(t){if(!i.has(t)){var n=e.get(t);n&&s(n)}})),n.push(t)}return t.forEach((function(t){e.set(t.name,t)})),t.forEach((function(t){i.has(t.name)||s(t)})),n}var fi={placement:"bottom",modifiers:[],strategy:"absolute"};function pi(){for(var t=arguments.length,e=new Array(t),i=0;iNumber.parseInt(t,10))):"function"==typeof t?e=>t(e,this._element):t}_getPopperConfig(){const t={placement:this._getPlacement(),modifiers:[{name:"preventOverflow",options:{boundary:this._config.boundary}},{name:"offset",options:{offset:this._getOffset()}}]};return(this._inNavbar||"static"===this._config.display)&&(F.setDataAttribute(this._menu,"popper","static"),t.modifiers=[{name:"applyStyles",enabled:!1}]),{...t,...g(this._config.popperConfig,[t])}}_selectMenuItem({key:t,target:e}){const i=z.find(".dropdown-menu .dropdown-item:not(.disabled):not(:disabled)",this._menu).filter((t=>a(t)));i.length&&b(i,e,t===Ti,!i.includes(e)).focus()}static jQueryInterface(t){return this.each((function(){const e=qi.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}static clearMenus(t){if(2===t.button||"keyup"===t.type&&"Tab"!==t.key)return;const e=z.find(Ni);for(const i of e){const e=qi.getInstance(i);if(!e||!1===e._config.autoClose)continue;const n=t.composedPath(),s=n.includes(e._menu);if(n.includes(e._element)||"inside"===e._config.autoClose&&!s||"outside"===e._config.autoClose&&s)continue;if(e._menu.contains(t.target)&&("keyup"===t.type&&"Tab"===t.key||/input|select|option|textarea|form/i.test(t.target.tagName)))continue;const o={relatedTarget:e._element};"click"===t.type&&(o.clickEvent=t),e._completeHide(o)}}static dataApiKeydownHandler(t){const e=/input|textarea/i.test(t.target.tagName),i="Escape"===t.key,n=[Ei,Ti].includes(t.key);if(!n&&!i)return;if(e&&!i)return;t.preventDefault();const s=this.matches(Ii)?this:z.prev(this,Ii)[0]||z.next(this,Ii)[0]||z.findOne(Ii,t.delegateTarget.parentNode),o=qi.getOrCreateInstance(s);if(n)return t.stopPropagation(),o.show(),void o._selectMenuItem(t);o._isShown()&&(t.stopPropagation(),o.hide(),s.focus())}}N.on(document,Si,Ii,qi.dataApiKeydownHandler),N.on(document,Si,Pi,qi.dataApiKeydownHandler),N.on(document,Li,qi.clearMenus),N.on(document,Di,qi.clearMenus),N.on(document,Li,Ii,(function(t){t.preventDefault(),qi.getOrCreateInstance(this).toggle()})),m(qi);const Vi="backdrop",Ki="show",Qi=`mousedown.bs.${Vi}`,Xi={className:"modal-backdrop",clickCallback:null,isAnimated:!1,isVisible:!0,rootElement:"body"},Yi={className:"string",clickCallback:"(function|null)",isAnimated:"boolean",isVisible:"boolean",rootElement:"(element|string)"};class Ui extends H{constructor(t){super(),this._config=this._getConfig(t),this._isAppended=!1,this._element=null}static get Default(){return Xi}static get DefaultType(){return Yi}static get NAME(){return Vi}show(t){if(!this._config.isVisible)return void g(t);this._append();const e=this._getElement();this._config.isAnimated&&d(e),e.classList.add(Ki),this._emulateAnimation((()=>{g(t)}))}hide(t){this._config.isVisible?(this._getElement().classList.remove(Ki),this._emulateAnimation((()=>{this.dispose(),g(t)}))):g(t)}dispose(){this._isAppended&&(N.off(this._element,Qi),this._element.remove(),this._isAppended=!1)}_getElement(){if(!this._element){const t=document.createElement("div");t.className=this._config.className,this._config.isAnimated&&t.classList.add("fade"),this._element=t}return this._element}_configAfterMerge(t){return t.rootElement=r(t.rootElement),t}_append(){if(this._isAppended)return;const t=this._getElement();this._config.rootElement.append(t),N.on(t,Qi,(()=>{g(this._config.clickCallback)})),this._isAppended=!0}_emulateAnimation(t){_(t,this._getElement(),this._config.isAnimated)}}const Gi=".bs.focustrap",Ji=`focusin${Gi}`,Zi=`keydown.tab${Gi}`,tn="backward",en={autofocus:!0,trapElement:null},nn={autofocus:"boolean",trapElement:"element"};class sn extends H{constructor(t){super(),this._config=this._getConfig(t),this._isActive=!1,this._lastTabNavDirection=null}static get Default(){return en}static get DefaultType(){return nn}static get NAME(){return"focustrap"}activate(){this._isActive||(this._config.autofocus&&this._config.trapElement.focus(),N.off(document,Gi),N.on(document,Ji,(t=>this._handleFocusin(t))),N.on(document,Zi,(t=>this._handleKeydown(t))),this._isActive=!0)}deactivate(){this._isActive&&(this._isActive=!1,N.off(document,Gi))}_handleFocusin(t){const{trapElement:e}=this._config;if(t.target===document||t.target===e||e.contains(t.target))return;const i=z.focusableChildren(e);0===i.length?e.focus():this._lastTabNavDirection===tn?i[i.length-1].focus():i[0].focus()}_handleKeydown(t){"Tab"===t.key&&(this._lastTabNavDirection=t.shiftKey?tn:"forward")}}const on=".fixed-top, .fixed-bottom, .is-fixed, .sticky-top",rn=".sticky-top",an="padding-right",ln="margin-right";class cn{constructor(){this._element=document.body}getWidth(){const t=document.documentElement.clientWidth;return Math.abs(window.innerWidth-t)}hide(){const t=this.getWidth();this._disableOverFlow(),this._setElementAttributes(this._element,an,(e=>e+t)),this._setElementAttributes(on,an,(e=>e+t)),this._setElementAttributes(rn,ln,(e=>e-t))}reset(){this._resetElementAttributes(this._element,"overflow"),this._resetElementAttributes(this._element,an),this._resetElementAttributes(on,an),this._resetElementAttributes(rn,ln)}isOverflowing(){return this.getWidth()>0}_disableOverFlow(){this._saveInitialAttribute(this._element,"overflow"),this._element.style.overflow="hidden"}_setElementAttributes(t,e,i){const n=this.getWidth();this._applyManipulationCallback(t,(t=>{if(t!==this._element&&window.innerWidth>t.clientWidth+n)return;this._saveInitialAttribute(t,e);const s=window.getComputedStyle(t).getPropertyValue(e);t.style.setProperty(e,`${i(Number.parseFloat(s))}px`)}))}_saveInitialAttribute(t,e){const i=t.style.getPropertyValue(e);i&&F.setDataAttribute(t,e,i)}_resetElementAttributes(t,e){this._applyManipulationCallback(t,(t=>{const i=F.getDataAttribute(t,e);null!==i?(F.removeDataAttribute(t,e),t.style.setProperty(e,i)):t.style.removeProperty(e)}))}_applyManipulationCallback(t,e){if(o(t))e(t);else for(const i of z.find(t,this._element))e(i)}}const hn=".bs.modal",dn=`hide${hn}`,un=`hidePrevented${hn}`,fn=`hidden${hn}`,pn=`show${hn}`,mn=`shown${hn}`,gn=`resize${hn}`,_n=`click.dismiss${hn}`,bn=`mousedown.dismiss${hn}`,vn=`keydown.dismiss${hn}`,yn=`click${hn}.data-api`,wn="modal-open",An="show",En="modal-static",Tn={backdrop:!0,focus:!0,keyboard:!0},Cn={backdrop:"(boolean|string)",focus:"boolean",keyboard:"boolean"};class On extends W{constructor(t,e){super(t,e),this._dialog=z.findOne(".modal-dialog",this._element),this._backdrop=this._initializeBackDrop(),this._focustrap=this._initializeFocusTrap(),this._isShown=!1,this._isTransitioning=!1,this._scrollBar=new cn,this._addEventListeners()}static get Default(){return Tn}static get DefaultType(){return Cn}static get NAME(){return"modal"}toggle(t){return this._isShown?this.hide():this.show(t)}show(t){this._isShown||this._isTransitioning||N.trigger(this._element,pn,{relatedTarget:t}).defaultPrevented||(this._isShown=!0,this._isTransitioning=!0,this._scrollBar.hide(),document.body.classList.add(wn),this._adjustDialog(),this._backdrop.show((()=>this._showElement(t))))}hide(){this._isShown&&!this._isTransitioning&&(N.trigger(this._element,dn).defaultPrevented||(this._isShown=!1,this._isTransitioning=!0,this._focustrap.deactivate(),this._element.classList.remove(An),this._queueCallback((()=>this._hideModal()),this._element,this._isAnimated())))}dispose(){N.off(window,hn),N.off(this._dialog,hn),this._backdrop.dispose(),this._focustrap.deactivate(),super.dispose()}handleUpdate(){this._adjustDialog()}_initializeBackDrop(){return new Ui({isVisible:Boolean(this._config.backdrop),isAnimated:this._isAnimated()})}_initializeFocusTrap(){return new sn({trapElement:this._element})}_showElement(t){document.body.contains(this._element)||document.body.append(this._element),this._element.style.display="block",this._element.removeAttribute("aria-hidden"),this._element.setAttribute("aria-modal",!0),this._element.setAttribute("role","dialog"),this._element.scrollTop=0;const e=z.findOne(".modal-body",this._dialog);e&&(e.scrollTop=0),d(this._element),this._element.classList.add(An),this._queueCallback((()=>{this._config.focus&&this._focustrap.activate(),this._isTransitioning=!1,N.trigger(this._element,mn,{relatedTarget:t})}),this._dialog,this._isAnimated())}_addEventListeners(){N.on(this._element,vn,(t=>{"Escape"===t.key&&(this._config.keyboard?this.hide():this._triggerBackdropTransition())})),N.on(window,gn,(()=>{this._isShown&&!this._isTransitioning&&this._adjustDialog()})),N.on(this._element,bn,(t=>{N.one(this._element,_n,(e=>{this._element===t.target&&this._element===e.target&&("static"!==this._config.backdrop?this._config.backdrop&&this.hide():this._triggerBackdropTransition())}))}))}_hideModal(){this._element.style.display="none",this._element.setAttribute("aria-hidden",!0),this._element.removeAttribute("aria-modal"),this._element.removeAttribute("role"),this._isTransitioning=!1,this._backdrop.hide((()=>{document.body.classList.remove(wn),this._resetAdjustments(),this._scrollBar.reset(),N.trigger(this._element,fn)}))}_isAnimated(){return this._element.classList.contains("fade")}_triggerBackdropTransition(){if(N.trigger(this._element,un).defaultPrevented)return;const t=this._element.scrollHeight>document.documentElement.clientHeight,e=this._element.style.overflowY;"hidden"===e||this._element.classList.contains(En)||(t||(this._element.style.overflowY="hidden"),this._element.classList.add(En),this._queueCallback((()=>{this._element.classList.remove(En),this._queueCallback((()=>{this._element.style.overflowY=e}),this._dialog)}),this._dialog),this._element.focus())}_adjustDialog(){const t=this._element.scrollHeight>document.documentElement.clientHeight,e=this._scrollBar.getWidth(),i=e>0;if(i&&!t){const t=p()?"paddingLeft":"paddingRight";this._element.style[t]=`${e}px`}if(!i&&t){const t=p()?"paddingRight":"paddingLeft";this._element.style[t]=`${e}px`}}_resetAdjustments(){this._element.style.paddingLeft="",this._element.style.paddingRight=""}static jQueryInterface(t,e){return this.each((function(){const i=On.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===i[t])throw new TypeError(`No method named "${t}"`);i[t](e)}}))}}N.on(document,yn,'[data-bs-toggle="modal"]',(function(t){const e=z.getElementFromSelector(this);["A","AREA"].includes(this.tagName)&&t.preventDefault(),N.one(e,pn,(t=>{t.defaultPrevented||N.one(e,fn,(()=>{a(this)&&this.focus()}))}));const i=z.findOne(".modal.show");i&&On.getInstance(i).hide(),On.getOrCreateInstance(e).toggle(this)})),R(On),m(On);const xn=".bs.offcanvas",kn=".data-api",Ln=`load${xn}${kn}`,Sn="show",Dn="showing",$n="hiding",In=".offcanvas.show",Nn=`show${xn}`,Pn=`shown${xn}`,Mn=`hide${xn}`,jn=`hidePrevented${xn}`,Fn=`hidden${xn}`,Hn=`resize${xn}`,Wn=`click${xn}${kn}`,Bn=`keydown.dismiss${xn}`,zn={backdrop:!0,keyboard:!0,scroll:!1},Rn={backdrop:"(boolean|string)",keyboard:"boolean",scroll:"boolean"};class qn extends W{constructor(t,e){super(t,e),this._isShown=!1,this._backdrop=this._initializeBackDrop(),this._focustrap=this._initializeFocusTrap(),this._addEventListeners()}static get Default(){return zn}static get DefaultType(){return Rn}static get NAME(){return"offcanvas"}toggle(t){return this._isShown?this.hide():this.show(t)}show(t){this._isShown||N.trigger(this._element,Nn,{relatedTarget:t}).defaultPrevented||(this._isShown=!0,this._backdrop.show(),this._config.scroll||(new cn).hide(),this._element.setAttribute("aria-modal",!0),this._element.setAttribute("role","dialog"),this._element.classList.add(Dn),this._queueCallback((()=>{this._config.scroll&&!this._config.backdrop||this._focustrap.activate(),this._element.classList.add(Sn),this._element.classList.remove(Dn),N.trigger(this._element,Pn,{relatedTarget:t})}),this._element,!0))}hide(){this._isShown&&(N.trigger(this._element,Mn).defaultPrevented||(this._focustrap.deactivate(),this._element.blur(),this._isShown=!1,this._element.classList.add($n),this._backdrop.hide(),this._queueCallback((()=>{this._element.classList.remove(Sn,$n),this._element.removeAttribute("aria-modal"),this._element.removeAttribute("role"),this._config.scroll||(new cn).reset(),N.trigger(this._element,Fn)}),this._element,!0)))}dispose(){this._backdrop.dispose(),this._focustrap.deactivate(),super.dispose()}_initializeBackDrop(){const t=Boolean(this._config.backdrop);return new Ui({className:"offcanvas-backdrop",isVisible:t,isAnimated:!0,rootElement:this._element.parentNode,clickCallback:t?()=>{"static"!==this._config.backdrop?this.hide():N.trigger(this._element,jn)}:null})}_initializeFocusTrap(){return new sn({trapElement:this._element})}_addEventListeners(){N.on(this._element,Bn,(t=>{"Escape"===t.key&&(this._config.keyboard?this.hide():N.trigger(this._element,jn))}))}static jQueryInterface(t){return this.each((function(){const e=qn.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}N.on(document,Wn,'[data-bs-toggle="offcanvas"]',(function(t){const e=z.getElementFromSelector(this);if(["A","AREA"].includes(this.tagName)&&t.preventDefault(),l(this))return;N.one(e,Fn,(()=>{a(this)&&this.focus()}));const i=z.findOne(In);i&&i!==e&&qn.getInstance(i).hide(),qn.getOrCreateInstance(e).toggle(this)})),N.on(window,Ln,(()=>{for(const t of z.find(In))qn.getOrCreateInstance(t).show()})),N.on(window,Hn,(()=>{for(const t of z.find("[aria-modal][class*=show][class*=offcanvas-]"))"fixed"!==getComputedStyle(t).position&&qn.getOrCreateInstance(t).hide()})),R(qn),m(qn);const Vn={"*":["class","dir","id","lang","role",/^aria-[\w-]*$/i],a:["target","href","title","rel"],area:[],b:[],br:[],col:[],code:[],div:[],em:[],hr:[],h1:[],h2:[],h3:[],h4:[],h5:[],h6:[],i:[],img:["src","srcset","alt","title","width","height"],li:[],ol:[],p:[],pre:[],s:[],small:[],span:[],sub:[],sup:[],strong:[],u:[],ul:[]},Kn=new Set(["background","cite","href","itemtype","longdesc","poster","src","xlink:href"]),Qn=/^(?!javascript:)(?:[a-z0-9+.-]+:|[^&:/?#]*(?:[/?#]|$))/i,Xn=(t,e)=>{const i=t.nodeName.toLowerCase();return e.includes(i)?!Kn.has(i)||Boolean(Qn.test(t.nodeValue)):e.filter((t=>t instanceof RegExp)).some((t=>t.test(i)))},Yn={allowList:Vn,content:{},extraClass:"",html:!1,sanitize:!0,sanitizeFn:null,template:"
    "},Un={allowList:"object",content:"object",extraClass:"(string|function)",html:"boolean",sanitize:"boolean",sanitizeFn:"(null|function)",template:"string"},Gn={entry:"(string|element|function|null)",selector:"(string|element)"};class Jn extends H{constructor(t){super(),this._config=this._getConfig(t)}static get Default(){return Yn}static get DefaultType(){return Un}static get NAME(){return"TemplateFactory"}getContent(){return Object.values(this._config.content).map((t=>this._resolvePossibleFunction(t))).filter(Boolean)}hasContent(){return this.getContent().length>0}changeContent(t){return this._checkContent(t),this._config.content={...this._config.content,...t},this}toHtml(){const t=document.createElement("div");t.innerHTML=this._maybeSanitize(this._config.template);for(const[e,i]of Object.entries(this._config.content))this._setContent(t,i,e);const e=t.children[0],i=this._resolvePossibleFunction(this._config.extraClass);return i&&e.classList.add(...i.split(" ")),e}_typeCheckConfig(t){super._typeCheckConfig(t),this._checkContent(t.content)}_checkContent(t){for(const[e,i]of Object.entries(t))super._typeCheckConfig({selector:e,entry:i},Gn)}_setContent(t,e,i){const n=z.findOne(i,t);n&&((e=this._resolvePossibleFunction(e))?o(e)?this._putElementInTemplate(r(e),n):this._config.html?n.innerHTML=this._maybeSanitize(e):n.textContent=e:n.remove())}_maybeSanitize(t){return this._config.sanitize?function(t,e,i){if(!t.length)return t;if(i&&"function"==typeof i)return i(t);const n=(new window.DOMParser).parseFromString(t,"text/html"),s=[].concat(...n.body.querySelectorAll("*"));for(const t of s){const i=t.nodeName.toLowerCase();if(!Object.keys(e).includes(i)){t.remove();continue}const n=[].concat(...t.attributes),s=[].concat(e["*"]||[],e[i]||[]);for(const e of n)Xn(e,s)||t.removeAttribute(e.nodeName)}return n.body.innerHTML}(t,this._config.allowList,this._config.sanitizeFn):t}_resolvePossibleFunction(t){return g(t,[this])}_putElementInTemplate(t,e){if(this._config.html)return e.innerHTML="",void e.append(t);e.textContent=t.textContent}}const Zn=new Set(["sanitize","allowList","sanitizeFn"]),ts="fade",es="show",is=".modal",ns="hide.bs.modal",ss="hover",os="focus",rs={AUTO:"auto",TOP:"top",RIGHT:p()?"left":"right",BOTTOM:"bottom",LEFT:p()?"right":"left"},as={allowList:Vn,animation:!0,boundary:"clippingParents",container:!1,customClass:"",delay:0,fallbackPlacements:["top","right","bottom","left"],html:!1,offset:[0,6],placement:"top",popperConfig:null,sanitize:!0,sanitizeFn:null,selector:!1,template:'',title:"",trigger:"hover focus"},ls={allowList:"object",animation:"boolean",boundary:"(string|element)",container:"(string|element|boolean)",customClass:"(string|function)",delay:"(number|object)",fallbackPlacements:"array",html:"boolean",offset:"(array|string|function)",placement:"(string|function)",popperConfig:"(null|object|function)",sanitize:"boolean",sanitizeFn:"(null|function)",selector:"(string|boolean)",template:"string",title:"(string|element|function)",trigger:"string"};class cs extends W{constructor(t,e){if(void 0===vi)throw new TypeError("Bootstrap's tooltips require Popper (https://popper.js.org)");super(t,e),this._isEnabled=!0,this._timeout=0,this._isHovered=null,this._activeTrigger={},this._popper=null,this._templateFactory=null,this._newContent=null,this.tip=null,this._setListeners(),this._config.selector||this._fixTitle()}static get Default(){return as}static get DefaultType(){return ls}static get NAME(){return"tooltip"}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}toggleEnabled(){this._isEnabled=!this._isEnabled}toggle(){this._isEnabled&&(this._activeTrigger.click=!this._activeTrigger.click,this._isShown()?this._leave():this._enter())}dispose(){clearTimeout(this._timeout),N.off(this._element.closest(is),ns,this._hideModalHandler),this._element.getAttribute("data-bs-original-title")&&this._element.setAttribute("title",this._element.getAttribute("data-bs-original-title")),this._disposePopper(),super.dispose()}show(){if("none"===this._element.style.display)throw new Error("Please use show on visible elements");if(!this._isWithContent()||!this._isEnabled)return;const t=N.trigger(this._element,this.constructor.eventName("show")),e=(c(this._element)||this._element.ownerDocument.documentElement).contains(this._element);if(t.defaultPrevented||!e)return;this._disposePopper();const i=this._getTipElement();this._element.setAttribute("aria-describedby",i.getAttribute("id"));const{container:n}=this._config;if(this._element.ownerDocument.documentElement.contains(this.tip)||(n.append(i),N.trigger(this._element,this.constructor.eventName("inserted"))),this._popper=this._createPopper(i),i.classList.add(es),"ontouchstart"in document.documentElement)for(const t of[].concat(...document.body.children))N.on(t,"mouseover",h);this._queueCallback((()=>{N.trigger(this._element,this.constructor.eventName("shown")),!1===this._isHovered&&this._leave(),this._isHovered=!1}),this.tip,this._isAnimated())}hide(){if(this._isShown()&&!N.trigger(this._element,this.constructor.eventName("hide")).defaultPrevented){if(this._getTipElement().classList.remove(es),"ontouchstart"in document.documentElement)for(const t of[].concat(...document.body.children))N.off(t,"mouseover",h);this._activeTrigger.click=!1,this._activeTrigger[os]=!1,this._activeTrigger[ss]=!1,this._isHovered=null,this._queueCallback((()=>{this._isWithActiveTrigger()||(this._isHovered||this._disposePopper(),this._element.removeAttribute("aria-describedby"),N.trigger(this._element,this.constructor.eventName("hidden")))}),this.tip,this._isAnimated())}}update(){this._popper&&this._popper.update()}_isWithContent(){return Boolean(this._getTitle())}_getTipElement(){return this.tip||(this.tip=this._createTipElement(this._newContent||this._getContentForTemplate())),this.tip}_createTipElement(t){const e=this._getTemplateFactory(t).toHtml();if(!e)return null;e.classList.remove(ts,es),e.classList.add(`bs-${this.constructor.NAME}-auto`);const i=(t=>{do{t+=Math.floor(1e6*Math.random())}while(document.getElementById(t));return t})(this.constructor.NAME).toString();return e.setAttribute("id",i),this._isAnimated()&&e.classList.add(ts),e}setContent(t){this._newContent=t,this._isShown()&&(this._disposePopper(),this.show())}_getTemplateFactory(t){return this._templateFactory?this._templateFactory.changeContent(t):this._templateFactory=new Jn({...this._config,content:t,extraClass:this._resolvePossibleFunction(this._config.customClass)}),this._templateFactory}_getContentForTemplate(){return{".tooltip-inner":this._getTitle()}}_getTitle(){return this._resolvePossibleFunction(this._config.title)||this._element.getAttribute("data-bs-original-title")}_initializeOnDelegatedTarget(t){return this.constructor.getOrCreateInstance(t.delegateTarget,this._getDelegateConfig())}_isAnimated(){return this._config.animation||this.tip&&this.tip.classList.contains(ts)}_isShown(){return this.tip&&this.tip.classList.contains(es)}_createPopper(t){const e=g(this._config.placement,[this,t,this._element]),i=rs[e.toUpperCase()];return bi(this._element,t,this._getPopperConfig(i))}_getOffset(){const{offset:t}=this._config;return"string"==typeof t?t.split(",").map((t=>Number.parseInt(t,10))):"function"==typeof t?e=>t(e,this._element):t}_resolvePossibleFunction(t){return g(t,[this._element])}_getPopperConfig(t){const e={placement:t,modifiers:[{name:"flip",options:{fallbackPlacements:this._config.fallbackPlacements}},{name:"offset",options:{offset:this._getOffset()}},{name:"preventOverflow",options:{boundary:this._config.boundary}},{name:"arrow",options:{element:`.${this.constructor.NAME}-arrow`}},{name:"preSetPlacement",enabled:!0,phase:"beforeMain",fn:t=>{this._getTipElement().setAttribute("data-popper-placement",t.state.placement)}}]};return{...e,...g(this._config.popperConfig,[e])}}_setListeners(){const t=this._config.trigger.split(" ");for(const e of t)if("click"===e)N.on(this._element,this.constructor.eventName("click"),this._config.selector,(t=>{this._initializeOnDelegatedTarget(t).toggle()}));else if("manual"!==e){const t=e===ss?this.constructor.eventName("mouseenter"):this.constructor.eventName("focusin"),i=e===ss?this.constructor.eventName("mouseleave"):this.constructor.eventName("focusout");N.on(this._element,t,this._config.selector,(t=>{const e=this._initializeOnDelegatedTarget(t);e._activeTrigger["focusin"===t.type?os:ss]=!0,e._enter()})),N.on(this._element,i,this._config.selector,(t=>{const e=this._initializeOnDelegatedTarget(t);e._activeTrigger["focusout"===t.type?os:ss]=e._element.contains(t.relatedTarget),e._leave()}))}this._hideModalHandler=()=>{this._element&&this.hide()},N.on(this._element.closest(is),ns,this._hideModalHandler)}_fixTitle(){const t=this._element.getAttribute("title");t&&(this._element.getAttribute("aria-label")||this._element.textContent.trim()||this._element.setAttribute("aria-label",t),this._element.setAttribute("data-bs-original-title",t),this._element.removeAttribute("title"))}_enter(){this._isShown()||this._isHovered?this._isHovered=!0:(this._isHovered=!0,this._setTimeout((()=>{this._isHovered&&this.show()}),this._config.delay.show))}_leave(){this._isWithActiveTrigger()||(this._isHovered=!1,this._setTimeout((()=>{this._isHovered||this.hide()}),this._config.delay.hide))}_setTimeout(t,e){clearTimeout(this._timeout),this._timeout=setTimeout(t,e)}_isWithActiveTrigger(){return Object.values(this._activeTrigger).includes(!0)}_getConfig(t){const e=F.getDataAttributes(this._element);for(const t of Object.keys(e))Zn.has(t)&&delete e[t];return t={...e,..."object"==typeof t&&t?t:{}},t=this._mergeConfigObj(t),t=this._configAfterMerge(t),this._typeCheckConfig(t),t}_configAfterMerge(t){return t.container=!1===t.container?document.body:r(t.container),"number"==typeof t.delay&&(t.delay={show:t.delay,hide:t.delay}),"number"==typeof t.title&&(t.title=t.title.toString()),"number"==typeof t.content&&(t.content=t.content.toString()),t}_getDelegateConfig(){const t={};for(const[e,i]of Object.entries(this._config))this.constructor.Default[e]!==i&&(t[e]=i);return t.selector=!1,t.trigger="manual",t}_disposePopper(){this._popper&&(this._popper.destroy(),this._popper=null),this.tip&&(this.tip.remove(),this.tip=null)}static jQueryInterface(t){return this.each((function(){const e=cs.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}}m(cs);const hs={...cs.Default,content:"",offset:[0,8],placement:"right",template:'',trigger:"click"},ds={...cs.DefaultType,content:"(null|string|element|function)"};class us extends cs{static get Default(){return hs}static get DefaultType(){return ds}static get NAME(){return"popover"}_isWithContent(){return this._getTitle()||this._getContent()}_getContentForTemplate(){return{".popover-header":this._getTitle(),".popover-body":this._getContent()}}_getContent(){return this._resolvePossibleFunction(this._config.content)}static jQueryInterface(t){return this.each((function(){const e=us.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}}m(us);const fs=".bs.scrollspy",ps=`activate${fs}`,ms=`click${fs}`,gs=`load${fs}.data-api`,_s="active",bs="[href]",vs=".nav-link",ys=`${vs}, .nav-item > ${vs}, .list-group-item`,ws={offset:null,rootMargin:"0px 0px -25%",smoothScroll:!1,target:null,threshold:[.1,.5,1]},As={offset:"(number|null)",rootMargin:"string",smoothScroll:"boolean",target:"element",threshold:"array"};class Es extends W{constructor(t,e){super(t,e),this._targetLinks=new Map,this._observableSections=new Map,this._rootElement="visible"===getComputedStyle(this._element).overflowY?null:this._element,this._activeTarget=null,this._observer=null,this._previousScrollData={visibleEntryTop:0,parentScrollTop:0},this.refresh()}static get Default(){return ws}static get DefaultType(){return As}static get NAME(){return"scrollspy"}refresh(){this._initializeTargetsAndObservables(),this._maybeEnableSmoothScroll(),this._observer?this._observer.disconnect():this._observer=this._getNewObserver();for(const t of this._observableSections.values())this._observer.observe(t)}dispose(){this._observer.disconnect(),super.dispose()}_configAfterMerge(t){return t.target=r(t.target)||document.body,t.rootMargin=t.offset?`${t.offset}px 0px -30%`:t.rootMargin,"string"==typeof t.threshold&&(t.threshold=t.threshold.split(",").map((t=>Number.parseFloat(t)))),t}_maybeEnableSmoothScroll(){this._config.smoothScroll&&(N.off(this._config.target,ms),N.on(this._config.target,ms,bs,(t=>{const e=this._observableSections.get(t.target.hash);if(e){t.preventDefault();const i=this._rootElement||window,n=e.offsetTop-this._element.offsetTop;if(i.scrollTo)return void i.scrollTo({top:n,behavior:"smooth"});i.scrollTop=n}})))}_getNewObserver(){const t={root:this._rootElement,threshold:this._config.threshold,rootMargin:this._config.rootMargin};return new IntersectionObserver((t=>this._observerCallback(t)),t)}_observerCallback(t){const e=t=>this._targetLinks.get(`#${t.target.id}`),i=t=>{this._previousScrollData.visibleEntryTop=t.target.offsetTop,this._process(e(t))},n=(this._rootElement||document.documentElement).scrollTop,s=n>=this._previousScrollData.parentScrollTop;this._previousScrollData.parentScrollTop=n;for(const o of t){if(!o.isIntersecting){this._activeTarget=null,this._clearActiveClass(e(o));continue}const t=o.target.offsetTop>=this._previousScrollData.visibleEntryTop;if(s&&t){if(i(o),!n)return}else s||t||i(o)}}_initializeTargetsAndObservables(){this._targetLinks=new Map,this._observableSections=new Map;const t=z.find(bs,this._config.target);for(const e of t){if(!e.hash||l(e))continue;const t=z.findOne(decodeURI(e.hash),this._element);a(t)&&(this._targetLinks.set(decodeURI(e.hash),e),this._observableSections.set(e.hash,t))}}_process(t){this._activeTarget!==t&&(this._clearActiveClass(this._config.target),this._activeTarget=t,t.classList.add(_s),this._activateParents(t),N.trigger(this._element,ps,{relatedTarget:t}))}_activateParents(t){if(t.classList.contains("dropdown-item"))z.findOne(".dropdown-toggle",t.closest(".dropdown")).classList.add(_s);else for(const e of z.parents(t,".nav, .list-group"))for(const t of z.prev(e,ys))t.classList.add(_s)}_clearActiveClass(t){t.classList.remove(_s);const e=z.find(`${bs}.${_s}`,t);for(const t of e)t.classList.remove(_s)}static jQueryInterface(t){return this.each((function(){const e=Es.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t]()}}))}}N.on(window,gs,(()=>{for(const t of z.find('[data-bs-spy="scroll"]'))Es.getOrCreateInstance(t)})),m(Es);const Ts=".bs.tab",Cs=`hide${Ts}`,Os=`hidden${Ts}`,xs=`show${Ts}`,ks=`shown${Ts}`,Ls=`click${Ts}`,Ss=`keydown${Ts}`,Ds=`load${Ts}`,$s="ArrowLeft",Is="ArrowRight",Ns="ArrowUp",Ps="ArrowDown",Ms="Home",js="End",Fs="active",Hs="fade",Ws="show",Bs=".dropdown-toggle",zs=`:not(${Bs})`,Rs='[data-bs-toggle="tab"], [data-bs-toggle="pill"], [data-bs-toggle="list"]',qs=`.nav-link${zs}, .list-group-item${zs}, [role="tab"]${zs}, ${Rs}`,Vs=`.${Fs}[data-bs-toggle="tab"], .${Fs}[data-bs-toggle="pill"], .${Fs}[data-bs-toggle="list"]`;class Ks extends W{constructor(t){super(t),this._parent=this._element.closest('.list-group, .nav, [role="tablist"]'),this._parent&&(this._setInitialAttributes(this._parent,this._getChildren()),N.on(this._element,Ss,(t=>this._keydown(t))))}static get NAME(){return"tab"}show(){const t=this._element;if(this._elemIsActive(t))return;const e=this._getActiveElem(),i=e?N.trigger(e,Cs,{relatedTarget:t}):null;N.trigger(t,xs,{relatedTarget:e}).defaultPrevented||i&&i.defaultPrevented||(this._deactivate(e,t),this._activate(t,e))}_activate(t,e){t&&(t.classList.add(Fs),this._activate(z.getElementFromSelector(t)),this._queueCallback((()=>{"tab"===t.getAttribute("role")?(t.removeAttribute("tabindex"),t.setAttribute("aria-selected",!0),this._toggleDropDown(t,!0),N.trigger(t,ks,{relatedTarget:e})):t.classList.add(Ws)}),t,t.classList.contains(Hs)))}_deactivate(t,e){t&&(t.classList.remove(Fs),t.blur(),this._deactivate(z.getElementFromSelector(t)),this._queueCallback((()=>{"tab"===t.getAttribute("role")?(t.setAttribute("aria-selected",!1),t.setAttribute("tabindex","-1"),this._toggleDropDown(t,!1),N.trigger(t,Os,{relatedTarget:e})):t.classList.remove(Ws)}),t,t.classList.contains(Hs)))}_keydown(t){if(![$s,Is,Ns,Ps,Ms,js].includes(t.key))return;t.stopPropagation(),t.preventDefault();const e=this._getChildren().filter((t=>!l(t)));let i;if([Ms,js].includes(t.key))i=e[t.key===Ms?0:e.length-1];else{const n=[Is,Ps].includes(t.key);i=b(e,t.target,n,!0)}i&&(i.focus({preventScroll:!0}),Ks.getOrCreateInstance(i).show())}_getChildren(){return z.find(qs,this._parent)}_getActiveElem(){return this._getChildren().find((t=>this._elemIsActive(t)))||null}_setInitialAttributes(t,e){this._setAttributeIfNotExists(t,"role","tablist");for(const t of e)this._setInitialAttributesOnChild(t)}_setInitialAttributesOnChild(t){t=this._getInnerElement(t);const e=this._elemIsActive(t),i=this._getOuterElement(t);t.setAttribute("aria-selected",e),i!==t&&this._setAttributeIfNotExists(i,"role","presentation"),e||t.setAttribute("tabindex","-1"),this._setAttributeIfNotExists(t,"role","tab"),this._setInitialAttributesOnTargetPanel(t)}_setInitialAttributesOnTargetPanel(t){const e=z.getElementFromSelector(t);e&&(this._setAttributeIfNotExists(e,"role","tabpanel"),t.id&&this._setAttributeIfNotExists(e,"aria-labelledby",`${t.id}`))}_toggleDropDown(t,e){const i=this._getOuterElement(t);if(!i.classList.contains("dropdown"))return;const n=(t,n)=>{const s=z.findOne(t,i);s&&s.classList.toggle(n,e)};n(Bs,Fs),n(".dropdown-menu",Ws),i.setAttribute("aria-expanded",e)}_setAttributeIfNotExists(t,e,i){t.hasAttribute(e)||t.setAttribute(e,i)}_elemIsActive(t){return t.classList.contains(Fs)}_getInnerElement(t){return t.matches(qs)?t:z.findOne(qs,t)}_getOuterElement(t){return t.closest(".nav-item, .list-group-item")||t}static jQueryInterface(t){return this.each((function(){const e=Ks.getOrCreateInstance(this);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t]()}}))}}N.on(document,Ls,Rs,(function(t){["A","AREA"].includes(this.tagName)&&t.preventDefault(),l(this)||Ks.getOrCreateInstance(this).show()})),N.on(window,Ds,(()=>{for(const t of z.find(Vs))Ks.getOrCreateInstance(t)})),m(Ks);const Qs=".bs.toast",Xs=`mouseover${Qs}`,Ys=`mouseout${Qs}`,Us=`focusin${Qs}`,Gs=`focusout${Qs}`,Js=`hide${Qs}`,Zs=`hidden${Qs}`,to=`show${Qs}`,eo=`shown${Qs}`,io="hide",no="show",so="showing",oo={animation:"boolean",autohide:"boolean",delay:"number"},ro={animation:!0,autohide:!0,delay:5e3};class ao extends W{constructor(t,e){super(t,e),this._timeout=null,this._hasMouseInteraction=!1,this._hasKeyboardInteraction=!1,this._setListeners()}static get Default(){return ro}static get DefaultType(){return oo}static get NAME(){return"toast"}show(){N.trigger(this._element,to).defaultPrevented||(this._clearTimeout(),this._config.animation&&this._element.classList.add("fade"),this._element.classList.remove(io),d(this._element),this._element.classList.add(no,so),this._queueCallback((()=>{this._element.classList.remove(so),N.trigger(this._element,eo),this._maybeScheduleHide()}),this._element,this._config.animation))}hide(){this.isShown()&&(N.trigger(this._element,Js).defaultPrevented||(this._element.classList.add(so),this._queueCallback((()=>{this._element.classList.add(io),this._element.classList.remove(so,no),N.trigger(this._element,Zs)}),this._element,this._config.animation)))}dispose(){this._clearTimeout(),this.isShown()&&this._element.classList.remove(no),super.dispose()}isShown(){return this._element.classList.contains(no)}_maybeScheduleHide(){this._config.autohide&&(this._hasMouseInteraction||this._hasKeyboardInteraction||(this._timeout=setTimeout((()=>{this.hide()}),this._config.delay)))}_onInteraction(t,e){switch(t.type){case"mouseover":case"mouseout":this._hasMouseInteraction=e;break;case"focusin":case"focusout":this._hasKeyboardInteraction=e}if(e)return void this._clearTimeout();const i=t.relatedTarget;this._element===i||this._element.contains(i)||this._maybeScheduleHide()}_setListeners(){N.on(this._element,Xs,(t=>this._onInteraction(t,!0))),N.on(this._element,Ys,(t=>this._onInteraction(t,!1))),N.on(this._element,Us,(t=>this._onInteraction(t,!0))),N.on(this._element,Gs,(t=>this._onInteraction(t,!1)))}_clearTimeout(){clearTimeout(this._timeout),this._timeout=null}static jQueryInterface(t){return this.each((function(){const e=ao.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}return R(ao),m(ao),{Alert:Q,Button:Y,Carousel:xt,Collapse:Bt,Dropdown:qi,Modal:On,Offcanvas:qn,Popover:us,ScrollSpy:Es,Tab:Ks,Toast:ao,Tooltip:cs}})); -//# sourceMappingURL=bootstrap.bundle.min.js.map \ No newline at end of file diff --git a/examples/anlian-mq/smoke.sh b/examples/anlian-mq/smoke.sh deleted file mode 100755 index dfe1bd9..0000000 --- a/examples/anlian-mq/smoke.sh +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env bash -# 暗恋见君 Marqdo 切片冒烟(需先启动 index.mq.md)。 -set -uo pipefail -BASE="http://127.0.0.1:18180" -PASS=0; FAIL=0 -ok() { echo " ok: $1"; PASS=$((PASS+1)); } -bad() { echo " FAIL: $1"; FAIL=$((FAIL+1)); } - -echo "== 首页 ==" -code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/") -[ "$code" = "200" ] && ok "GET /" || bad "GET / -> $code" -curl -s "$BASE/" | grep -q '暗恋见君' && ok "品牌" || bad "品牌" -curl -s "$BASE/" | grep -q 'class="hero"' && ok "Hero" || bad "Hero" -curl -s "$BASE/" | grep -q 'notice-title\|公告信息' && ok "公告" || bad "公告" -curl -s "$BASE/" | grep -q 'news-timeline\|新闻动态' && ok "新闻时间线" || bad "新闻时间线" -curl -s "$BASE/" | grep -q 'home-posts\|论坛交流' && ok "帖子区" || bad "帖子区" -curl -s "$BASE/" | grep -q 'bg-body-960\|/static/css/base.css' && ok "原站 CSS/背景" || bad "原站 CSS/背景" -curl -s -o /dev/null -w "%{http_code}" "$BASE/static/css/base.css" | grep -q 200 && ok "base.css" || bad "base.css" - -echo "== 列表 / 详情 ==" -curl -s "$BASE/post" | grep -q 'welcome\|欢迎\|论坛交流' && ok "帖子列表" || bad "帖子列表" -code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/post/welcome") -[ "$code" = "200" ] && ok "帖子详情" || bad "帖子详情 -> $code" -curl -s "$BASE/news" | grep -q 'migrate\|迁往\|新闻' && ok "新闻列表" || bad "新闻列表" - -echo "== 片段 API ==" -curl -s "$BASE/post/ten" | grep -q 'home-post-card\|欢迎' && ok "/post/ten" || bad "/post/ten" -curl -s "$BASE/news/five" | grep -q 'news-timeline\|迁往\|站点' && ok "/news/five" || bad "/news/five" - -echo "== 其它页 ==" -code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/topics") -[ "$code" = "200" ] && ok "专题" || bad "专题 -> $code" -code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/chat") -[ "$code" = "200" ] && ok "聊天列表" || bad "聊天列表 -> $code" -code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/guide/automation-api") -[ "$code" = "200" ] && ok "API 指南" || bad "API 指南 -> $code" -code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/sitemap.xml") -[ "$code" = "200" ] && ok "sitemap" || bad "sitemap -> $code" - -echo "== 门禁 / 登录 ==" -code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/post/public") -[ "$code" = "303" ] || [ "$code" = "302" ] && ok "未登录发帖重定向" || bad "发帖 -> $code" -rm -f /tmp/anlian_mq_hdr.txt -curl -s -D /tmp/anlian_mq_hdr.txt -o /dev/null -d "username=admin&password=anlian" "$BASE/accounts/login" -sid=$(grep -i "set-cookie" /tmp/anlian_mq_hdr.txt | sed 's/.*marqdo_sid=\([^;]*\).*/\1/' | head -1) -[ -n "$sid" ] && ok "会话 cookie" || bad "无 cookie" -code=$(curl -s -b "marqdo_sid=$sid" -o /dev/null -w "%{http_code}" "$BASE/post/public") -[ "$code" = "200" ] && ok "登录后发帖" || bad "登录后发帖 -> $code" - -echo "== WS ==" -wsok=$(python3 -c " -import socket, base64, os -s = socket.create_connection(('127.0.0.1', 18180), timeout=3) -key = base64.b64encode(os.urandom(16)).decode() -s.sendall((f'GET /chat/ws HTTP/1.1\r\nHost: x\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode()) -r = s.recv(1024).decode(errors='replace') -print('OK' if '101' in r.split('\r\n')[0] else 'NO') -s.close() -" 2>/dev/null) -[ "$wsok" = "OK" ] && ok "WebSocket" || bad "WebSocket $wsok" - -echo -echo "通过 $PASS / $((PASS+FAIL))" -[ "$FAIL" = "0" ] || exit 1 diff --git a/examples/anlian-mq/styles/shell.mq.md b/examples/anlian-mq/styles/shell.mq.md deleted file mode 100644 index 8247f0e..0000000 --- a/examples/anlian-mq/styles/shell.mq.md +++ /dev/null @@ -1,431 +0,0 @@ ---- -markup: occlusion -title: styles/shell -description: 暗恋见君壳样式——对照 Django 原站粉玻璃 + 动效,用表格声明。 -导入: - 网页: ext/web/网页.mq.md - text: lib/text.mq.md ---- - -对照原站 `config/static/front/css/{base,feed_common,footer,index/hero}.css`: -固定背景图、毛玻璃顶栏、Logo 呼吸、Hero 漂浮、粉玻璃卡片与页脚。 - -## 基础 - -品牌色与全站底:固定摄影背景 + 粉玻璃变量。 - -`基础` = - -| 选择器 | 属性 | 值 | -|--------|------|-----| -| :root | --ink | #333333 | -| :root | --ink-strong | #111111 | -| :root | --muted | #666666 | -| :root | --paper | #f8f9fa | -| :root | --glass | rgba(255,255,255,0.28) | -| :root | --glass-strong | rgba(255,255,255,0.42) | -| :root | --glass-border | rgba(255,255,255,0.5) | -| :root | --accent | #fdbbdb | -| :root | --accent-deep | #f0a8c4 | -| :root | --accent-text | #a85878 | -| :root | --accent-muted | #c97a96 | -| :root | --accent-bg | rgba(253,189,219,0.48) | -| :root | --hero-pink | #ffd0d0 | -| :root | --radius | 14px | -| :root | --sans | "Noto Sans SC", "IBM Plex Sans", system-ui, sans-serif | -| * | box-sizing | border-box | -| html | scroll-behavior | smooth | -| body | margin | "0" | -| body | min-height | 100vh | -| body | font-family | var(--sans) | -| body | color | var(--ink) | -| body | line-height | "1.6" | -| body | background-color | var(--paper) | -| body | background-image | url("/static/bg-body-960.webp") | -| body | background-repeat | no-repeat | -| body | background-size | cover | -| body | background-position | center center | -| body | background-attachment | fixed | -| body | overflow-x | hidden | -| a | color | var(--accent-text) | -| a | text-decoration | none | -| a:hover | color | var(--accent-deep) | -| ::selection | background | rgba(253,189,219,0.45) | -| main.main | padding | 0 0 3rem | -| .main-intro | max-width | 72rem | -| .main-intro | margin | 0 auto | -| .main-intro | padding | 1.25rem 1.5rem 0 | - -*`基础`* - -## 动效 - -原站 `pulse`(Logo)与 `heroImageFloat`(主图);尊重减动偏好。 - -`动效` = - -| 选择器 | 属性 | 值 | -|--------|------|-----| -| @keyframes pulse 0% | transform | scale(1) | -| @keyframes pulse 50% | transform | scale(1.05) | -| @keyframes pulse 100% | transform | scale(1) | -| @keyframes heroImageFloat 0% | transform | scale(1) | -| @keyframes heroImageFloat 50% | transform | scale(1.04) | -| @keyframes heroImageFloat 100% | transform | scale(1) | -| @keyframes cardRise 0% | opacity | "0" | -| @keyframes cardRise 0% | transform | translateY(10px) | -| @keyframes cardRise 100% | opacity | "1" | -| @keyframes cardRise 100% | transform | translateY(0) | - -*`动效`* - -## 顶栏 - -毛玻璃导航;首项品牌带 Logo 呼吸动画。 - -`顶栏` = - -| 选择器 | 属性 | 值 | -|--------|------|-----| -| header.topnav | grid-area | top | -| header.topnav | position | sticky | -| header.topnav | top | "0" | -| header.topnav | z-index | "1000" | -| header.topnav | width | 100% | -| header.topnav | padding | 0.75rem 1.25rem | -| header.topnav | background | rgba(255,255,255,0.2) | -| header.topnav | backdrop-filter | blur(24px) | -| header.topnav | -webkit-backdrop-filter | blur(24px) | -| header.topnav | border-bottom | 1px solid rgba(255,255,255,0.2) | -| header.topnav | box-shadow | inset 0 0 5px rgba(255,255,255,0.1) | -| ul.nav | list-style | none | -| ul.nav | margin | "0" | -| ul.nav | padding | "0" | -| ul.nav | display | flex | -| ul.nav | flex-wrap | wrap | -| ul.nav | align-items | center | -| ul.nav | gap | 0.35rem 0.5rem | -| ul.nav a | display | inline-flex | -| ul.nav a | align-items | center | -| ul.nav a | gap | 0.45rem | -| ul.nav a | padding | 0.4rem 0.85rem | -| ul.nav a | border-radius | 999px | -| ul.nav a | color | var(--ink) | -| ul.nav a | font-weight | "600" | -| ul.nav a | transition | color 0.2s ease, transform 0.2s ease, background 0.2s ease | -| ul.nav a:hover | color | var(--accent-text) | -| ul.nav a:hover | transform | translateY(-2px) | -| ul.nav a:hover | background | rgba(253,189,219,0.22) | -| ul.nav li:first-child a | font-size | 1.05rem | -| ul.nav li:first-child a | font-weight | "700" | -| ul.nav li:first-child a | letter-spacing | 0.04em | -| ul.nav li:first-child a | padding-left | 0.35rem | -| ul.nav li:first-child a::before | content | "" | -| ul.nav li:first-child a::before | width | 28px | -| ul.nav li:first-child a::before | height | 28px | -| ul.nav li:first-child a::before | background | url("/static/logo.svg") center / contain no-repeat | -| ul.nav li:first-child a::before | animation | pulse 3s ease-in-out infinite | -| ul.nav li:first-child a:hover | transform | none | -| ul.nav li:first-child a:hover | background | transparent | - -*`顶栏`* - -## Hero - -首页双栏英雄区:大标题粉强调 + 主图漂浮。 - -`Hero` = - -| 选择器 | 属性 | 值 | -|--------|------|-----| -| .hero | max-width | 72rem | -| .hero | margin | 0 auto 1.5rem | -| .hero | padding | 1.5rem 0.5rem 0.5rem | -| .hero-content | display | grid | -| .hero-content | grid-template-columns | minmax(0,1fr) minmax(0,1fr) | -| .hero-content | align-items | center | -| .hero-content | gap | 2rem | -| .hero-left | display | flex | -| .hero-left | flex-direction | column | -| .hero-left | align-items | flex-start | -| .hero-brand | display | inline-flex | -| .hero-brand | align-items | center | -| .hero-brand | gap | 0.55rem | -| .hero-brand | margin | 0 0 1rem | -| .hero-brand | font-size | 1.35rem | -| .hero-brand | font-weight | "700" | -| .hero-brand | letter-spacing | 0.08em | -| .hero-brand | text-transform | uppercase | -| .hero-brand | color | var(--ink-strong) | -| .hero-logo | width | 30px | -| .hero-logo | height | 30px | -| .hero-logo | animation | pulse 3s ease-in-out infinite | -| .hero-pink | color | var(--hero-pink) | -| .main-text | margin | 0 0 1.25rem | -| .main-text | font-size | clamp(2.4rem, 5.5vw, 5.2rem) | -| .main-text | font-weight | "800" | -| .main-text | line-height | "1.15" | -| .main-text | color | var(--ink-strong) | -| .sub-text | margin | 0 0 1.75rem | -| .sub-text | max-width | 34rem | -| .sub-text | font-size | 1.05rem | -| .sub-text | letter-spacing | 0.02em | -| .sub-text | color | rgba(60,60,60,0.85) | -| .hero-cta | display | flex | -| .hero-cta | flex-wrap | wrap | -| .hero-cta | gap | 0.65rem | -| .hero-btn | display | inline-flex | -| .hero-btn | align-items | center | -| .hero-btn | padding | 0.55rem 1.2rem | -| .hero-btn | border-radius | 999px | -| .hero-btn | font-weight | "600" | -| .hero-btn | color | #fff | -| .hero-btn | background | linear-gradient(120deg, var(--accent-deep), var(--accent)) | -| .hero-btn | box-shadow | 0 6px 18px rgba(253,189,219,0.45) | -| .hero-btn | transition | transform 0.2s ease, box-shadow 0.2s ease | -| .hero-btn:hover | transform | translateY(-2px) | -| .hero-btn:hover | color | #fff | -| .hero-btn:hover | box-shadow | 0 10px 24px rgba(253,189,219,0.55) | -| .hero-btn.ghost | background | rgba(255,255,255,0.35) | -| .hero-btn.ghost | color | var(--accent-text) | -| .hero-btn.ghost | border | 1px solid var(--glass-border) | -| .hero-btn.ghost | box-shadow | none | -| .hero-btn.ghost:hover | background | rgba(255,255,255,0.55) | -| .hero-btn.ghost:hover | color | var(--accent-text) | -| .hero-right | display | flex | -| .hero-right | align-items | center | -| .hero-right | justify-content | center | -| .hero-art | display | block | -| .hero-art | width | 85% | -| .hero-art | max-width | 420px | -| .hero-art | height | auto | -| .hero-art | filter | drop-shadow(0 0 20px rgba(255,208,208,0.45)) | -| .hero-art | animation | heroImageFloat 30s linear infinite | -| .hero-art | pointer-events | none | -| .home-feed-head | max-width | 52rem | -| .home-feed-head | margin | 0.5rem auto 0 | -| .home-feed-head | padding | 0 1.25rem | -| .home-feed-head h2 | margin | 0 0 0.35rem | -| .home-feed-head h2 | font-size | 1.35rem | -| .home-feed-head h2 | color | var(--accent-text) | -| .home-feed-head p | margin | "0" | -| .home-feed-head p | color | var(--muted) | -| .home-feed-head p | font-size | 0.92rem | -| .page-stage | max-width | 52rem | -| .page-stage | margin | 1.25rem auto 0 | -| .page-stage | padding | 1.25rem 1.35rem | -| .page-stage | border-radius | var(--radius) | -| .page-stage | background | var(--glass) | -| .page-stage | backdrop-filter | blur(14px) | -| .page-stage | -webkit-backdrop-filter | blur(14px) | -| .page-stage | border | 1px solid var(--glass-border) | -| .page-stage h1 | margin | 0 0 0.35rem | -| .page-stage h1 | font-size | 1.6rem | -| .page-stage h1 | color | var(--ink-strong) | -| .page-stage p | margin | "0" | -| .page-stage p | color | var(--muted) | - -*`Hero`* - -## 卡片 - -粉玻璃帖子/新闻卡:悬停上浮(对齐 `.home-post-card`)。 - -`卡片` = - -| 选择器 | 属性 | 值 | -|--------|------|-----| -| .content.cards | max-width | 52rem | -| .content.cards | margin | 1rem auto 0 | -| .content.cards | padding | 0 1.25rem | -| .content.cards | display | flex | -| .content.cards | flex-direction | column | -| .content.cards | gap | 0.65rem | -| article.card | border-radius | var(--radius) | -| article.card | background | rgba(255,255,255,0.32) | -| article.card | backdrop-filter | blur(12px) | -| article.card | -webkit-backdrop-filter | blur(12px) | -| article.card | border | 1px solid rgba(255,255,255,0.42) | -| article.card | box-shadow | 0 4px 16px rgba(253,189,219,0.08) | -| article.card | transition | transform 0.2s ease, box-shadow 0.2s ease, background 0.2s ease | -| article.card | animation | cardRise 0.45s ease both | -| article.card:nth-child(2) | animation-delay | 0.05s | -| article.card:nth-child(3) | animation-delay | 0.1s | -| article.card:nth-child(4) | animation-delay | 0.15s | -| article.card:hover | transform | translateY(-2px) | -| article.card:hover | background | rgba(255,255,255,0.42) | -| article.card:hover | box-shadow | 0 8px 24px rgba(253,189,219,0.18) | -| a.card-link | display | grid | -| a.card-link | grid-template-columns | auto 1fr | -| a.card-link | grid-template-areas | "meta title" "meta body" | -| a.card-link | gap | 0.35rem 1rem | -| a.card-link | align-items | start | -| a.card-link | padding | 0.85rem 1rem | -| a.card-link | color | inherit | -| a.card-link | text-decoration | none | -| .card-meta | grid-area | meta | -| .card-meta | align-self | center | -| .card-meta | padding | 0.2rem 0.55rem | -| .card-meta | border-radius | 6px | -| .card-meta | font-size | 0.6875rem | -| .card-meta | font-weight | "600" | -| .card-meta | color | var(--accent-text) | -| .card-meta | background | rgba(253,189,219,0.28) | -| .card-meta | white-space | nowrap | -| .card-meta | max-width | 5rem | -| .card-meta | overflow | hidden | -| .card-meta | text-overflow | ellipsis | -| article.card h2 | grid-area | title | -| article.card h2 | margin | "0" | -| article.card h2 | font-size | 0.95rem | -| article.card h2 | font-weight | "600" | -| article.card h2 | color | #222 | -| article.card h2 | line-height | "1.35" | -| article.card p | grid-area | body | -| article.card p | margin | "0" | -| article.card p | font-size | 0.82rem | -| article.card p | color | #666 | -| article.card p | line-height | "1.45" | -| article.article | max-width | 42rem | -| article.article | margin | 1.5rem auto | -| article.article | padding | 1.5rem 1.6rem | -| article.article | border-radius | var(--radius) | -| article.article | background | rgba(255,255,255,0.55) | -| article.article | backdrop-filter | blur(16px) | -| article.article | -webkit-backdrop-filter | blur(16px) | -| article.article | border | 1px solid var(--glass-border) | -| article.article | box-shadow | 0 8px 28px rgba(253,189,219,0.12) | -| .article-meta | color | var(--accent-text) | -| .article-meta | font-size | 0.85rem | -| .article-meta | font-weight | "600" | -| .article-meta | margin-bottom | 0.5rem | -| .article-title | margin | 0 0 1rem | -| .article-title | font-size | 1.75rem | -| .article-title | color | var(--ink-strong) | -| .article-body | color | var(--ink) | -| .article-body | line-height | "1.75" | -| .site-form | max-width | 34rem | -| .site-form | margin | 1.5rem auto | -| .site-form | padding | 1.5rem | -| .site-form | border-radius | var(--radius) | -| .site-form | background | rgba(255,255,255,0.45) | -| .site-form | backdrop-filter | blur(14px) | -| .site-form | border | 1px solid var(--glass-border) | -| .chat-box | max-width | 42rem | -| .chat-box | margin | 1rem auto | -| .chat-box | padding | 1rem 1.15rem | -| .chat-box | border-radius | var(--radius) | -| .chat-box | background | rgba(255,255,255,0.4) | -| .chat-box | backdrop-filter | blur(12px) | -| .chat-box | border | 1px solid var(--glass-border) | -| .chat-log | min-height | 12rem | -| .chat-log | font-family | ui-monospace, monospace | -| .chat-log | font-size | 0.9rem | -| .chat-log | white-space | pre-wrap | -| .search-bar | display | flex | -| .search-bar | gap | 0.5rem | -| .search-bar | margin-top | 0.85rem | -| .search-bar input | flex | "1" | -| .search-bar input | padding | 0.55rem 0.8rem | -| .search-bar input | border-radius | 999px | -| .search-bar input | border | 1px solid rgba(253,189,219,0.55) | -| .search-bar input | background | rgba(255,255,255,0.65) | -| .search-bar button | padding | 0.55rem 1.1rem | -| .search-bar button | border | "0" | -| .search-bar button | border-radius | 999px | -| .search-bar button | background | var(--accent) | -| .search-bar button | color | var(--accent-text) | -| .search-bar button | font-weight | "600" | -| .search-bar button | cursor | pointer | - -*`卡片`* - -## 页脚 - -双栏粉玻璃页脚。 - -`页脚` = - -| 选择器 | 属性 | 值 | -|--------|------|-----| -| footer.foot | grid-area | foot | -| footer.foot | margin-top | 2rem | -| footer.foot | padding | 2rem 1.5rem 2.5rem | -| footer.foot | background | rgba(255,255,255,0.28) | -| footer.foot | backdrop-filter | blur(14px) | -| footer.foot | -webkit-backdrop-filter | blur(14px) | -| footer.foot | border-top | 1px solid rgba(255,255,255,0.45) | -| footer.foot | box-shadow | inset 0 1px 0 rgba(255,255,255,0.35) | -| ul.foot-nav | list-style | none | -| ul.foot-nav | margin | 0 auto | -| ul.foot-nav | padding | "0" | -| ul.foot-nav | max-width | 52rem | -| ul.foot-nav | display | flex | -| ul.foot-nav | flex-wrap | wrap | -| ul.foot-nav | justify-content | center | -| ul.foot-nav | gap | 0.75rem 1.5rem | -| ul.foot-nav a | color | #444 | -| ul.foot-nav a | font-weight | "500" | -| ul.foot-nav a:hover | color | var(--accent-text) | - -*`页脚`* - -## 响应式 - -平板收窄标题;手机 Hero 单栏。 - -`响应式` = - -| 媒体 | 选择器 | 属性 | 值 | -|------|--------|------|-----| -| (max-width: 1024px) | .hero-content | gap | 1.25rem | -| (max-width: 1024px) | .main-text | font-size | clamp(2.2rem, 4.5vw, 3.6rem) | -| (max-width: 1024px) | .hero-art | width | min(90%, 340px) | -| (max-width: 767px) | .hero-content | grid-template-columns | 1fr | -| (max-width: 767px) | .hero-left | align-items | center | -| (max-width: 767px) | .hero-left | text-align | center | -| (max-width: 767px) | .sub-text | text-align | center | -| (max-width: 767px) | .hero-cta | justify-content | center | -| (max-width: 767px) | .hero-right | order | "2" | -| (max-width: 767px) | .hero-left | order | "1" | -| (max-width: 767px) | header.topnav | padding | 0.65rem 0.85rem | -| (max-width: 767px) | ul.nav | gap | 0.25rem | -| (prefers-reduced-motion: reduce) | .hero-art | animation | none | -| (prefers-reduced-motion: reduce) | .hero-logo | animation | none | -| (prefers-reduced-motion: reduce) | ul.nav li:first-child a::before | animation | none | -| (prefers-reduced-motion: reduce) | article.card | animation | none | - -*`响应式`* - -## 全局 - -**基础表 = > 基础** -**动效表 = > 动效** -**顶栏表 = > 顶栏** -**Hero表 = > Hero** -**卡片表 = > 卡片** -**页脚表 = > 页脚** -**响应式表 = > 响应式** - -**css基础 = > 网页.样式装配 名="基础" 表=`基础表`** -**css动效 = > 网页.样式装配 名="动效" 表=`动效表`** -**css顶栏 = > 网页.样式装配 名="顶栏" 表=`顶栏表`** -**cssHero = > 网页.样式装配 名="Hero" 表=`Hero表`** -**css卡片 = > 网页.样式装配 名="卡片" 表=`卡片表`** -**css页脚 = > 网页.样式装配 名="页脚" 表=`页脚表`** -**css响应式 = > 网页.样式装配 名="响应式" 表=`响应式表`** - -`css段` = - -| css | -|-----| -| `css基础` | -| `css动效` | -| `css顶栏` | -| `cssHero` | -| `css卡片` | -| `css页脚` | -| `css响应式` | - -**css = > text.str_join xs=`css段` sep=""** -*css* diff --git a/examples/browser-app/README.md b/examples/browser-app/README.md index 26b6b26..ca840ae 100644 --- a/examples/browser-app/README.md +++ b/examples/browser-app/README.md @@ -1,21 +1,33 @@ -# browser-app(路线 E) +# browser-app:可读源码中的浏览器工程 -作者**零业务 JS**;逻辑用 **GFM 表格 + `lib/browser`**(无 `json.set` 链)。 +从 [index.mq.md](index.mq.md) 开始阅读和执行,再沿 [组件入口](components/index.mq.md) 查看布局。首页拆成列表与计时,网络页再拆成输出、批量请求和 WebSocket 控件;内容在 content 中保留普通 Markdown,控件叶子使用原生 View 节点。 -| 能力 | 演示 | -|------|------| -| 列表 CRUD | 添加 / 委托删除(`bag` + `set_html`) | -| storage | 草稿 localStorage | -| navigate | `/` `/about` `/net` + `popstate` | -| interval | 计时起停 | -| fetch_all | 并行两个 uuid | -| ws | `wss://echo.websocket.events`(依赖外网) | -| clipboard / download | 复制/下载列表文本 | +浏览器程序是 [static/app.mq.md](static/app.mq.md)。事件表、参数与返回契约就在回调旁边;操作用可读标签表达,列表文本始终保留为数据。样式入口为 [styles/index.mq.md](styles/index.mq.md),旁边的字面表保留旧页面全部 59 条声明,并给出 View 包装层的几何适配。 -```bash -cargo build -p marqdo --release -./target/release/marqdo wasm build -o examples/browser-app -cd examples/browser-app && python3 -m http.server 8766 +| 能力 | 实际行为与边界 | +|---|---| +| 列表 | 原生记录保留独立 ID;重复内容可单独删除,特殊字符使用 text,删除按钮使用 children | +| 草稿 | localStorage 保存输入框文本;完成回调确认保存,缺失值与空草稿分别处理;条目不跨刷新保存 | +| 历史 | 三个面板使用真实 pathname;popstate 只反映现有位置,不重复 push;直接打开 /about 或 /net 返回首页 | +| 计时 | 同名计时器替换,停止保留已累计次数 | +| 批量请求 | 两个公开 UUID 请求可能失败;输出每项真实状态、响应体或错误 | +| WebSocket | 本地 /live 原生回声资源;展示实际打开、消息、错误与关闭回调 | +| 剪贴板与下载 | 导出当前列表文本;即时提示仅确认已发起,浏览器策略仍可能阻止完成 | + +在仓库根目录构建当前官方运行时,再启动原生服务器。需要已经可用的 Rust/WASM 工具链和本仓库工程、网络插件;缺少 WASM 标准库时先阅读 [工作区工具链手册](../../skills/marqdo-dev/toolchain.mq.md),并将返回的 compiler 传给 build_browser。生成资源与编译样式不作为业务源码提交。 + +```sh +marqdo call skills/marqdo-dev/index.mq.md build_browser 'out="examples/browser-app/static"' --effects plugin,process.exec,fs.write --fs-root . --require-ok --json +marqdo call examples/browser-app/index.mq.md serve --effects plugin,fs.write,network.write --fs-root examples/browser-app --require-ok --json ``` -写法:[marqdo-dev](../../.cursor/skills/marqdo-dev/SKILL.md) · 路线图:[browser-wasm-e.md](../../doc/roadmap/browser-wasm-e.md)。 +打开 http://127.0.0.1:18095。控件等待实际启动成功后启用;缺失资源返回明确失败,不能把加载说明当作已运行。服务只监听本机,示例不引入数据库、认证或持久条目存储。 + +开发验证同样通过可执行手册完成。下列浏览器任务原生复制当前运行时,并运行真实页面交互;它覆盖重复项、字面文本、草稿、历史、计时、导出内容、受控批量请求失败与本地 WebSocket 收发。Node/Playwright 是自动化测试的外联边界,文件读写与任务编排仍由 Marqdo 执行。 + +```sh +marqdo call skills/marqdo-dev/index.mq.md check 'path="examples/browser-app/index.mq.md"' --effects plugin --require-ok --json +marqdo call skills/marqdo-dev/index.mq.md test_browser --effects plugin,process.exec,fs.write --fs-root . --require-ok --json +``` + +后续修改先阅读 [编程规范](../../doc/library-development.mq.md),再修改一个职责的组件或回调。需要新的浏览器宿主能力时扩充正式 bridge 与标准库契约,保留真实浏览器验收;不在父组件中重新拼接 HTML 或业务 JavaScript。 diff --git a/examples/browser-app/app.mq.md b/examples/browser-app/app.mq.md deleted file mode 100644 index 344b0bf..0000000 --- a/examples/browser-app/app.mq.md +++ /dev/null @@ -1,285 +0,0 @@ ---- -markup: occlusion -title: browser-app (route E+) -description: list CRUD, storage, navigate, interval, fetch_all, ws — GFM + lib/browser -import: - browser: lib/browser.mq.md - table: lib/table.mq.md - 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 为 item) - 1. `item` != "" - **`html` = html + "
  • " + item + "
  • "** - **`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 为 item) - 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 为 item) - 1. `item` != "" - **`html` = html + "
  • " + item + "
  • "** - **`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* diff --git a/examples/browser-app/components/about.mq.md b/examples/browser-app/components/about.mq.md new file mode 100644 index 0000000..756e97a --- /dev/null +++ b/examples/browser-app/components/about.mq.md @@ -0,0 +1,25 @@ +--- +markup: occlusion +title: About panel Markdown leaf +import: + component: ext/web/component/index.mq.md + fs: lib/fs.mq.md +--- + +## nodes + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Structured View rows for this component | + +About is a terminal Markdown leaf, so further layout splitting would add no useful responsibility. Read its content through the native filesystem under the granted site root. The wrapper supplies only its client visibility id and initial hidden state. The page describes official host capabilities without embedding implementation JavaScript or an HTML shell. + +We **source = [Read the literal About content](fs.read_text(path="content/about.md"))** and **children = [Keep it as ordinary Markdown](component.markdown(text=`source`, slot="about-content"))**. + +`attrs` = + +| id | hidden | +|---|---| +| panel-about | True | + +Return *[Describe the initially hidden About panel](component.wrap(children=`children`, kind="section", attrs=`attrs`, slot="about"))*. diff --git a/examples/browser-app/components/controls.mq.md b/examples/browser-app/components/controls.mq.md new file mode 100644 index 0000000..11813d7 --- /dev/null +++ b/examples/browser-app/components/controls.mq.md @@ -0,0 +1,70 @@ +--- +markup: occlusion +title: Native browser control leaves +import: + component: ext/web/component/index.mq.md + table: lib/table.mq.md +--- + +## button + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | text | required | Event target shared with the client wire table | +| label | text | required | Literal visible action | +| secondary | bool | False | Use the retained secondary palette | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | One disabled native button awaiting successful runtime boot | + +Use `id`, `label` and `secondary`=False for one leaf. The button starts disabled, carries type button and is enabled only after the official runtime boots successfully. Its label remains plain text. The caller chooses placement; this helper neither binds a click handler nor hides a sibling layout. Keep its id aligned with static/app.mq.md. + +`attrs` = + +| id | type | disabled | +|---|---|---| +| `id` | button | True | + +We **style = ""**. +1. `secondary` + We **style = "secondary"**. +Return *[Describe one literal native action](component.element(kind="button", value=`label`, attrs=`attrs`, style=`style`, slot=`id`))*. + +## input + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | text | required | Client value target | +| hint | text | required | Plain placeholder text | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | One disabled text input | + +Use `id` and `hint` for the draft or socket message. A native text input preserves its ordinary editing semantics and starts disabled until WASM is ready. The hint is placeholder text rather than a markup template. The component owns one control; the client selects its value through the wire table when the adjacent action is clicked. + +`attrs` = + +| id | type | placeholder | disabled | +|---|---|---|---| +| `id` | text | `hint` | True | + +Return *[Describe this native value input](component.element(kind="input", attrs=`attrs`, slot=`id`))*. + +## text + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | text | required | Stable output target | +| value | text | required | Literal initial text | +| kind | text | "text" | Native text or pre output | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | One escaped text leaf | + +Use `id`, `value` and `kind`="text" for an output target. Select pre for the runtime log and ordinary text for the path, tick count or network outcome. Initial and later content stays literal: the renderer escapes this value and callbacks use set_text. This leaf declares no timer or network operation; those belong to the browser program. + +We **attrs = [Retain the exact output target](table.put(in=None, at="id", value=`id`))**. +Return *[Describe the literal output leaf](component.element(kind=`kind`, value=`value`, attrs=`attrs`, slot=`id`))*. diff --git a/examples/browser-app/components/home/editor.mq.md b/examples/browser-app/components/home/editor.mq.md new file mode 100644 index 0000000..34f6019 --- /dev/null +++ b/examples/browser-app/components/home/editor.mq.md @@ -0,0 +1,33 @@ +--- +markup: occlusion +title: Draft and list editor +import: + controls: ../controls.mq.md + component: ext/web/component/index.mq.md + table: lib/table.mq.md +--- + +## nodes + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Structured View rows for this component | + +The editor contains one draft input, three draft actions, the export actions and an initially empty native list. The client owns records, stable identities and delegated deletion; no authored list HTML is stored here. Save persists only the draft under this origin. Copy and Download export current item text while list state remains in browser session memory. + +We **heading = [Read the plain editor heading](component.markdown(text="## 待办"))** and **input = [Describe the exact draft target](controls.input(id="draft", hint="新项…"))** and **children = [Place input after its heading](table.concat(a=`heading`, b=`input`))**. + +`actions` = + +| @ | id | label | secondary | +|---|---|---|---| +| 1 | add | 添加 | False | +| 2 | save | 存草稿 | True | +| 3 | load | 读草稿 | True | +| 4 | copy-log | 复制列表 | True | +| 5 | dl-list | 下载列表 | True | + +- [Describe each native action leaf](for actions as action) + We **button = [Keep this action separate from state](controls.button(id=access(action, "id"), label=access(action, "label"), secondary=access(action, "secondary")))** and **children = [Preserve the authored action order](table.concat(a=`children`, b=`button`))**. +We **empty = [Start the empty native list](table.empty_list())** and **attrs = [Retain the delegated list target](table.put(in=None, at="id", value="items"))** and **list = [Describe the list container](component.wrap(children=`empty`, kind="list", attrs=`attrs`, slot="items"))**. +Return *[Keep the list after its editing controls](table.concat(a=`children`, b=`list`))*. diff --git a/examples/browser-app/components/home/index.mq.md b/examples/browser-app/components/home/index.mq.md new file mode 100644 index 0000000..a13eaf0 --- /dev/null +++ b/examples/browser-app/components/home/index.mq.md @@ -0,0 +1,20 @@ +--- +markup: occlusion +title: Home panel assembly +import: + editor: editor.mq.md + timer: timer.mq.md + component: ext/web/component/index.mq.md + table: lib/table.mq.md +--- + +## nodes + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Structured View rows for this component | + +Home has two independent children: the list editor and the named timer. This parent expresses only that ordering and the panel identity used by the client. Start with Home visible; About and Network are hidden in their own definitions. State and transport do not belong in layout tables, and changing one child does not require copying the entire page. + +We **list = [Assemble the editor responsibility](editor.nodes())** and **clock = [Assemble the timer responsibility](timer.nodes())** and **children = [Keep the two home regions ordered](table.concat(a=`list`, b=`clock`))** and **attrs = [Name the client visibility target](table.put(in=None, at="id", value="panel-home"))**. +Return *[Describe the initially visible Home panel](component.wrap(children=`children`, kind="section", attrs=`attrs`, slot="home"))*. diff --git a/examples/browser-app/components/home/timer.mq.md b/examples/browser-app/components/home/timer.mq.md new file mode 100644 index 0000000..e93f5db --- /dev/null +++ b/examples/browser-app/components/home/timer.mq.md @@ -0,0 +1,19 @@ +--- +markup: occlusion +title: Named timer controls +import: + controls: ../controls.mq.md + component: ext/web/component/index.mq.md + table: lib/table.mq.md +--- + +## nodes + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Structured View rows for this component | + +This region describes the tick output and its two actions. The client increments retained state only when the named timer actually calls back. Start replaces a timer with the same id; Stop preserves the count. This layout performs no sleeping or counting on the server, and its native text output can be tested independently of timer scheduling. + +We **label = [Describe the timer label](component.markdown(text="计时(秒):"))** and **counter = [Describe the initial count](controls.text(id="tick", value="0"))** and **start = [Describe the explicit start action](controls.button(id="start-tick", label="开始"))** and **stop = [Describe the explicit stop action](controls.button(id="stop-tick", label="停止", secondary=True))** and **content = [Keep label before count](table.concat(a=`label`, b=`counter`))** and **actions = [Keep the two actions together](table.concat(a=`start`, b=`stop`))** and **children = [Place actions beside their output](table.concat(a=`content`, b=`actions`))**. +Return *[Wrap this one timer responsibility](component.wrap(children=`children`, kind="row", slot="timer"))*. diff --git a/examples/browser-app/components/index.mq.md b/examples/browser-app/components/index.mq.md new file mode 100644 index 0000000..a9f7807 --- /dev/null +++ b/examples/browser-app/components/index.mq.md @@ -0,0 +1,50 @@ +--- +markup: occlusion +title: Browser example recursive page assembly +import: + navigation: navigation.mq.md + home: home/index.mq.md + about: about.mq.md + network: network/index.mq.md + controls: controls.mq.md + component: ext/web/component/index.mq.md + fs: lib/fs.mq.md + table: lib/table.mq.md +--- + +## nodes + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Structured View rows for this component | + +Read this root to see the whole page: introduction, path, navigation, three panels, feedback and runtime. Follow one import at a time until a child is a plain Markdown leaf or native control. Business values never become a page HTML string. The official runtime starts only after the server has staged the current built assets and the actual client source. Controls stay disabled until boot succeeds; missing resources therefore remain visible as a loading failure. The readiness target and enable selectors are typed resource metadata, not executable snippets. Styles reference the generated stylesheet produced by serve. Server discovery reads the terminal content leaves under the granted root; the browser receives the same ordered region tree. + +We **source = [Read the plain introduction](fs.read_text(path="content/intro.md"))** and **intro = [Retain its Markdown](component.markdown(text=`source`, slot="intro"))** and **path = [Describe the initial pathname](controls.text(id="path", value="path: /"))** and **nav = [Assemble the authored destinations](navigation.nodes())** and **home = [Assemble list and timer](home.nodes())** and **about = [Read the About leaf](about.nodes())** and **network = [Assemble independent network controls](network.nodes())** and **log = [Describe literal runtime feedback](controls.text(id="log", value="loading…", kind="pre"))** and **style = [Reference the compiled declarative theme](component.asset(url="/static/theme.css", kind="stylesheet"))**. + +`runtime_attrs` = + +| type | data-mq-wasm | data-mq-source-url | data-mq-ready | data-mq-enable | +|---|---|---|---|---| +| module | "/static/marqdo_wasm.wasm" | "/static/app.mq.md" | "#log" | "#draft,#add,#save,#load,#start-tick,#stop-tick,#fetch-all,#ws-open,#ws-msg,#ws-send,#ws-close,#copy-log,#dl-list" | + +We **runtime = [Declare the official module and readiness targets](component.asset(url="/static/marqdo-bridge.js", attrs=`runtime_attrs`, slot="runtime"))**. + +`groups` = + +| rows | +|---| +| `intro` | +| `path` | +| `nav` | +| `home` | +| `about` | +| `network` | +| `log` | +| `style` | +| `runtime` | + +We **children = [Start the complete ordered page](table.empty_list())**. +- [Retain each independently inspectable region](for groups as group) + We **children = [Keep typed children in reading order](table.concat(a=`children`, b=`group`))**. +Return *[Wrap the recursive page once](component.wrap(children=`children`, slot="browser-app", style="browser-app"))*. diff --git a/examples/browser-app/components/navigation.mq.md b/examples/browser-app/components/navigation.mq.md new file mode 100644 index 0000000..2803473 --- /dev/null +++ b/examples/browser-app/components/navigation.mq.md @@ -0,0 +1,36 @@ +--- +markup: occlusion +title: Three browser panel destinations +import: + component: ext/web/component/index.mq.md + table: lib/table.mq.md +--- + +## nodes + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Structured View rows for this component | + +Navigation contains three ordinary links with stable ids. Their fragment destinations leave a readable fallback without issuing a server page request. The official wire table intercepts each click and requests one deliberate history entry. Back and Forward only repaint the already selected panel. This component does not own client state or generate navigation JavaScript. + +`destinations` = + +| @ | id | href | label | +|---|---|---|---| +| 1 | nav-home | "#/" | 首页 | +| 2 | nav-about | "#/about" | 关于 | +| 3 | nav-net | "#/net" | 网络 | + +We **links = [Start the ordered native navigation](table.empty_list())**. +- [Declare each independently named destination](for destinations as destination) + We **label = [Read its literal label](access(destination, "label"))** and **id = [Read its stable event target](access(destination, "id"))** and **href = [Read its fallback destination](access(destination, "href"))**. + + `attrs` = + + | id | href | + |---|---| + | `id` | `href` | + + We **link = [Describe this native destination](component.element(kind="link", value=`label`, attrs=`attrs`))** and **links = [Preserve navigation order](table.concat(a=`links`, b=`link`))**. +Return *[Place those links in a navigation region](component.wrap(children=`links`, kind="nav", slot="navigation"))*. diff --git a/examples/browser-app/components/network/index.mq.md b/examples/browser-app/components/network/index.mq.md new file mode 100644 index 0000000..856ed49 --- /dev/null +++ b/examples/browser-app/components/network/index.mq.md @@ -0,0 +1,27 @@ +--- +markup: occlusion +title: Network panel assembly +import: + socket: socket.mq.md + controls: ../controls.mq.md + component: ext/web/component/index.mq.md + table: lib/table.mq.md +--- + +## nodes + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Structured View rows for this component | + +Network places plain explanatory content, the actual response output, a batch-fetch action and a local echo group. Batch requests retain the original public demonstration endpoint and may fail; ordered callback records show each status and body. Socket transport is local and independent. The panel starts hidden and the browser client alone selects it. + +We **heading = [Describe the network responsibility](component.markdown(text="## 网络\n\n批量请求显示每项的实际状态;WebSocket 使用本机 /live 回声服务。"))** and **output = [Describe literal transport feedback](controls.text(id="net-out", value="idle"))** and **fetch = [Describe the batch request action](controls.button(id="fetch-all", label="fetch_all ×2 uuid"))** and **echo = [Assemble local socket controls](socket.nodes())** and **first = [Place feedback below its explanation](table.concat(a=`heading`, b=`output`))** and **last = [Keep fetch before socket interaction](table.concat(a=`fetch`, b=`echo`))** and **children = [Preserve the two network responsibilities](table.concat(a=`first`, b=`last`))**. + +`attrs` = + +| id | hidden | +|---|---| +| panel-net | True | + +Return *[Describe the initially hidden Network panel](component.wrap(children=`children`, kind="section", attrs=`attrs`, slot="network"))*. diff --git a/examples/browser-app/components/network/socket.mq.md b/examples/browser-app/components/network/socket.mq.md new file mode 100644 index 0000000..9e88af9 --- /dev/null +++ b/examples/browser-app/components/network/socket.mq.md @@ -0,0 +1,18 @@ +--- +markup: occlusion +title: Local echo socket controls +import: + controls: ../controls.mq.md + table: lib/table.mq.md +--- + +## nodes + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Structured View rows for this component | + +The echo group contains Open, the message input, Send and Close as separate native leaves. The server binds /live, and the official bridge sends the browser program’s transport instructions. Actual lifecycle callbacks update the network output. This component performs no handshake itself and does not rely on availability of a public echo service. + +We **open = [Describe the connection action](controls.button(id="ws-open", label="WS 打开"))** and **message = [Describe exact message input](controls.input(id="ws-msg", hint="ws 消息"))** and **send = [Describe the explicit send action](controls.button(id="ws-send", label="WS 发送"))** and **close = [Describe the explicit close action](controls.button(id="ws-close", label="WS 关闭", secondary=True))** and **first = [Keep open before message entry](table.concat(a=`open`, b=`message`))** and **last = [Keep send before close](table.concat(a=`send`, b=`close`))**. +Return *[Keep the local echo interaction ordered](table.concat(a=`first`, b=`last`))*. diff --git a/examples/browser-app/content/about.md b/examples/browser-app/content/about.md new file mode 100644 index 0000000..2c3d352 --- /dev/null +++ b/examples/browser-app/content/about.md @@ -0,0 +1,5 @@ +## 关于 + +从 `index.mq.md` 阅读工程入口,沿 `components/index.mq.md` 逐层查看布局,再阅读 `static/app.mq.md` 的事件与回调。 + +普通内容使用 Markdown,控件使用原生节点,列表保留带独立 ID 的记录。浏览器执行官方 bridge 提供的 DOM、历史、存储与网络能力,无需作者撰写业务 JavaScript。 diff --git a/examples/browser-app/content/intro.md b/examples/browser-app/content/intro.md new file mode 100644 index 0000000..3bd163b --- /dev/null +++ b/examples/browser-app/content/intro.md @@ -0,0 +1,3 @@ +# Marqdo browser-app + +列表、草稿存储、历史导航、计时、批量请求、WebSocket、剪贴板和下载。页面和业务流程均由 Marqdo 源码表达,浏览器宿主能力由官方 bridge 提供。 diff --git a/examples/browser-app/index.html b/examples/browser-app/index.html deleted file mode 100644 index a724168..0000000 --- a/examples/browser-app/index.html +++ /dev/null @@ -1,96 +0,0 @@ - - - - - - Marqdo · browser-app (route E) - - - -

    Marqdo browser-app

    -

    路线 E:列表 CRUD / storage / navigate / interval / fetch_all / ws / clipboard / download — 无作者业务 JS。

    -

    path: /

    - - -
    -

    待办

    - - - - - - -
      -

      计时:0s - - -

      -
      - - - - - -
      loading…
      - - - diff --git a/examples/browser-app/index.mq.md b/examples/browser-app/index.mq.md new file mode 100644 index 0000000..c7e7fda --- /dev/null +++ b/examples/browser-app/index.mq.md @@ -0,0 +1,55 @@ +--- +markup: occlusion +type: web +view: main +route: / +title: Marqdo browser-app +import: + page: components/index.mq.md + styles: styles/index.mq.md + web: ext/web/web.mq.md + http: ext/net/http.mq.md + socket: ext/net/websocket.mq.md + fs: lib/fs.mq.md + result: lib/result.mq.md +--- + +This is the callable engineering entry. Follow components/index.mq.md for recursive layout, static/app.mq.md for browser state and effects, and styles/index.mq.md for the retained theme. Plain content is Markdown; controls and resources remain native structured values. There is no authored HTML host or business JavaScript. Serve runs from the checkout root with --fs-root examples/browser-app. + +## main + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Inspectable native page rows | + +The Document delegates page assembly to its component root. Home, About and Network are client panels within this one page, with their own independently readable components. The client controls visibility and history while ordinary content remains Markdown. This function does not start a server, fetch public endpoints or open a socket. Read the returned tree as layout data, and call serve for a real running application. + +Return *[Assemble the recursive browser demonstration](page.nodes())*. + +## serve + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| root | text | "examples/browser-app" | Explicit site directory relative to the checkout | +| port | number | 18095 | Loopback listen port | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Blocking listener or missing-asset failure | + +Use `root`="examples/browser-app" and `port`=18095 with plugin,fs.write,network.write and the site filesystem root. Build current browser assets through the development handbook first. Both generated assets must exist before theme compilation or listening; missing files produce an actionable Result. The native filesystem writes only the explicit compiled stylesheet. No Python static server or generated shell workflow is needed. + +Discovery prepares the Document and the static mount. Direct /about and /net visits redirect to the entry page, matching the transient panel-state model; Back and Forward inside a live page retain their actual history positions. A separate local network resource binds /live for anonymous demonstration echo. This loopback example does not authenticate or persist item records. Keep every returned app value and listen only after binding all resources. + +`assets` = + +| file | +|---| +| static/marqdo_wasm.wasm | +| static/marqdo-bridge.js | + +- [Require current official browser resources](for assets as file) + 1. not [The required runtime asset exists](fs.exists(path=`file`)) + Return *[Expose the actual build prerequisite](result.error(code="browser_app.assets", message="call build_browser and stage its assets in examples/browser-app/static before serve", operation="serve"))*. +We **css = [Compile the retained declarative theme](styles.css())** and **[Write only the generated stylesheet](fs.atomic_write(path="static/theme.css", text=`css`))** and **app = [Discover the native Document and static assets](web.prepare(root=`root`, host="127.0.0.1", port=`port`, static_dir="static"))** and **app = [Retain a direct About entry](http.redirect(app=`app`, from="/about", to="/", permanent=False))** and **app = [Retain a direct Network entry](http.redirect(app=`app`, from="/net", to="/", permanent=False))** and **app = [Bind the actual local echo resource](socket.route(app=`app`, path="/live", mode="echo", require_auth=False))**. +Return *[Listen after the real resources are ready](web.listen(app=`app`))*. diff --git a/examples/browser-app/marqdo-bridge.js b/examples/browser-app/marqdo-bridge.js deleted file mode 100644 index 631aa59..0000000 --- a/examples/browser-app/marqdo-bridge.js +++ /dev/null @@ -1,1382 +0,0 @@ -/** - * Canonical Marqdo browser bridge (routes C/D/E). Host glue only — not app logic. - * Authors write .mq.md only; this file may grow host mechanisms freely. - * - * ABI: mq_alloc, mq_dealloc, mq_run, mq_boot, mq_call, mq_version - * Effects: set_text, set_value, set_attr, set_class, toggle_class, set_style, - * focus, blur, scroll_into, set_html, replace_children, render_list, - * navigate, storage, ws, fetch, fetch_all, after, interval, clear_interval - */ - -export function readCString(memory, ptr) { - const bytes = new Uint8Array(memory.buffer); - let end = ptr; - while (bytes[end] !== 0) end += 1; - return new TextDecoder().decode(bytes.subarray(ptr, end)); -} - -function decodePacked(exports, outPtr) { - if (!outPtr) throw new Error("null wasm result pointer"); - const view = new DataView(exports.memory.buffer); - const jsonLen = view.getUint32(outPtr, true); - const jsonBytes = new Uint8Array(exports.memory.buffer, outPtr + 4, jsonLen); - const text = new TextDecoder().decode(jsonBytes); - exports.mq_dealloc(outPtr, 4 + jsonLen); - return JSON.parse(text); -} - -function writeUtf8(exports, text) { - const encoded = new TextEncoder().encode(text); - const ptr = exports.mq_alloc(encoded.length || 1); - if (!ptr) throw new Error("mq_alloc failed"); - new Uint8Array(exports.memory.buffer, ptr, encoded.length).set(encoded); - return { ptr, len: encoded.length }; -} - -export function runSource(exports, source) { - const { ptr, len } = writeUtf8(exports, source); - const outPtr = exports.mq_run(ptr, len); - exports.mq_dealloc(ptr, len || 1); - return decodePacked(exports, outPtr); -} - -export function boot(exports, source) { - const { ptr, len } = writeUtf8(exports, source); - const outPtr = exports.mq_boot(ptr, len); - exports.mq_dealloc(ptr, len || 1); - return decodePacked(exports, outPtr); -} - -export function call(exports, name, argsObj = {}) { - const n = writeUtf8(exports, name); - const a = writeUtf8(exports, JSON.stringify(argsObj ?? {})); - const outPtr = exports.mq_call(n.ptr, n.len, a.ptr, a.len); - exports.mq_dealloc(n.ptr, n.len || 1); - exports.mq_dealloc(a.ptr, a.len || 1); - return decodePacked(exports, outPtr); -} - -export async function loadWasm(url = "./marqdo_wasm.wasm") { - const res = await fetch(url); - if (!res.ok) { - throw new Error( - `failed to fetch ${url} (${res.status}). Build with: marqdo wasm build -o .`, - ); - } - const { instance } = await WebAssembly.instantiateStreaming(res, {}); - return instance.exports; -} - -function isPlainObject(v) { - return v != null && typeof v === "object" && !Array.isArray(v); -} - -function asSelList(v) { - if (v == null) return []; - if (Array.isArray(v)) return v.map(String); - return [String(v)]; -} - -/** Normalize mount options from plain object or DOM dataset. */ -export function normalizeMountOptions(raw = {}) { - const o = raw && typeof raw === "object" ? raw : {}; - const dataset = o.dataset || {}; - const wasmUrl = - o.wasmUrl || o.wasm || dataset.mqWasm || dataset.wasm || "./marqdo_wasm.wasm"; - const sourceUrl = - o.sourceUrl || o.source_url || dataset.mqSourceUrl || dataset.sourceUrl || ""; - let source = o.source != null ? o.source : dataset.mqSource || ""; - if (!source && typeof o.sourceInline === "string") source = o.sourceInline; - const playground = o.playground || dataset.mqPlayground || dataset.playground || ""; - const ready = o.ready || o.readySel || dataset.mqReady || ""; - const enable = o.enable || dataset.mqEnable || ""; - const noBoot = - o.noBoot === true || dataset.mqNoBoot === "1" || dataset.mqNoBoot === "true"; - return { - wasmUrl: String(wasmUrl), - sourceUrl: sourceUrl ? String(sourceUrl) : "", - source: source ? String(source) : "", - playground: playground ? String(playground) : "", - ready: ready ? String(ready) : "", - enable: enable ? String(enable) : "", - noBoot, - onError: typeof o.onError === "function" ? o.onError : null, - }; -} - -export function collectMountConfigs(doc = typeof document !== "undefined" ? document : null) { - if (!doc) return []; - const out = []; - const bootEl = doc.getElementById("marqdo-boot"); - if (bootEl) { - try { - out.push(normalizeMountOptions(JSON.parse(bootEl.textContent || "{}"))); - } catch (e) { - console.error("marqdo-boot JSON:", e); - } - } - const scripts = doc.querySelectorAll( - "script[data-mq-source-url], script[data-mq-source], script[data-mq-playground], script[data-mq-wasm]", - ); - for (const el of scripts) { - if (el.dataset.mqNoBoot === "1" || el.dataset.mqNoBoot === "true") continue; - const hasWork = - el.dataset.mqSourceUrl || el.dataset.mqSource || el.dataset.mqPlayground; - if (!hasWork) continue; - out.push( - normalizeMountOptions({ - dataset: el.dataset, - wasmUrl: el.dataset.mqWasm, - sourceUrl: el.dataset.mqSourceUrl, - source: el.dataset.mqSource, - playground: el.dataset.mqPlayground, - ready: el.dataset.mqReady, - enable: el.dataset.mqEnable, - }), - ); - } - return out; -} - -export function eventArgsFromDom(ev, valueFromSel) { - const t = ev && ev.target; - const args = { event: ev && ev.type ? ev.type : "click" }; - if (t && typeof t === "object") { - if ("value" in t && t.value != null && t.type !== "file") args.value = String(t.value); - if ("checked" in t) args.checked = !!t.checked; - if (t.id) args.id = String(t.id); - if (t.getAttribute) { - const did = t.getAttribute("data-id"); - if (did != null) args.data_id = did; - const drag = t.getAttribute("data-drag"); - if (drag != null) args.drag = drag; - } - if (typeof t.textContent === "string" && !("value" in t)) { - args.text = t.textContent; - } - if (ev.key != null) args.key = String(ev.key); - if (ev.code != null) args.code = String(ev.code); - if (t.files && t.files.length) { - const f = t.files[0]; - args.file_name = f.name; - args.file_size = f.size; - args.file_type = f.type || ""; - args.file_count = t.files.length; - } - } - if (ev && ev.type === "popstate") { - args.url = typeof location !== "undefined" ? location.href : ""; - args.path = typeof location !== "undefined" ? location.pathname + location.search : ""; - args.state = ev.state; - } - if (ev && ev.dataTransfer) { - try { - const txt = ev.dataTransfer.getData("text") || ev.dataTransfer.getData("text/plain"); - if (txt) args.drop_text = txt; - } catch (_) { - /* ignore */ - } - } - if (valueFromSel && typeof document !== "undefined") { - const src = document.querySelector(valueFromSel); - if (src) { - if ("value" in src && src.type !== "file") args.value = String(src.value); - else args.value = src.textContent != null ? String(src.textContent) : ""; - } - } - if (ev && ev.type === "submit" && t) { - const form = typeof t.closest === "function" ? t.closest("form") : t; - if (form && typeof FormData !== "undefined") { - try { - ev.preventDefault(); - } catch (_) { - /* ignore */ - } - const fields = {}; - for (const [k, v] of new FormData(form)) fields[k] = String(v); - args.fields = fields; - } - } - return args; -} - -function applyStyle(el, styleVal) { - if (typeof styleVal === "string") { - el.setAttribute("style", styleVal); - return; - } - if (isPlainObject(styleVal)) { - for (const [k, v] of Object.entries(styleVal)) { - if (v === null || v === false) el.style.removeProperty(k); - else el.style.setProperty(k.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase()), String(v)); - } - } -} - -export function renderListItems(spec) { - const tag = String(spec.tag || "li"); - const items = Array.isArray(spec.items) ? spec.items : []; - return items - .map((it) => { - if (it == null) return ""; - if (typeof it === "string" || typeof it === "number") { - return `<${tag}>${escapeHtml(String(it))}`; - } - if (!isPlainObject(it)) return ""; - const text = it.text != null ? String(it.text) : it.html != null ? null : ""; - const cls = it.class != null ? ` class="${escapeAttr(String(it.class))}"` : ""; - let attrs = ""; - if (isPlainObject(it.attrs)) { - for (const [k, v] of Object.entries(it.attrs)) { - if (v === null || v === false) continue; - attrs += ` ${escapeAttr(k)}="${escapeAttr(String(v))}"`; - } - } - const inner = it.html != null ? String(it.html) : escapeHtml(text ?? ""); - return `<${tag}${cls}${attrs}>${inner}`; - }) - .join(""); -} - -function escapeHtml(s) { - return s - .replace(/&/g, "&") - .replace(//g, ">") - .replace(/"/g, """); -} - -function escapeAttr(s) { - return escapeHtml(s).replace(/'/g, "'"); -} - -function qsAll(sel) { - if (typeof document === "undefined") return []; - try { - return [...document.querySelectorAll(sel)]; - } catch (_) { - return []; - } -} - -function qsOne(sel) { - const all = qsAll(sel); - return all[0] || null; -} - -/** Sync DOM patches (E1/E2/E3 navigate is sync too). */ -export function applyDomPatch(value) { - if (!value || typeof value !== "object") return; - if (typeof document === "undefined") return; - - const setText = value.set_text || value.setText; - if (isPlainObject(setText)) { - for (const [sel, text] of Object.entries(setText)) { - for (const el of qsAll(sel)) el.textContent = String(text); - } - } - - const setValue = value.set_value || value.setValue; - if (isPlainObject(setValue)) { - for (const [sel, v] of Object.entries(setValue)) { - for (const el of qsAll(sel)) { - if ("value" in el) el.value = String(v); - } - } - } - - const setAttr = value.set_attr || value.setAttr; - if (isPlainObject(setAttr)) { - for (const [sel, attrs] of Object.entries(setAttr)) { - if (!isPlainObject(attrs)) continue; - for (const el of qsAll(sel)) { - for (const [name, raw] of Object.entries(attrs)) { - if (raw === null || raw === false) el.removeAttribute(name); - else el.setAttribute(name, String(raw)); - } - } - } - } - - const setClass = value.set_class || value.setClass; - if (isPlainObject(setClass)) { - for (const [sel, cls] of Object.entries(setClass)) { - for (const el of qsAll(sel)) el.className = String(cls); - } - } - - const addClass = value.add_class || value.addClass; - if (isPlainObject(addClass)) { - for (const [sel, cls] of Object.entries(addClass)) { - const names = String(cls).split(/\s+/).filter(Boolean); - for (const el of qsAll(sel)) for (const c of names) el.classList.add(c); - } - } - - const removeClass = value.remove_class || value.removeClass; - if (isPlainObject(removeClass)) { - for (const [sel, cls] of Object.entries(removeClass)) { - const names = String(cls).split(/\s+/).filter(Boolean); - for (const el of qsAll(sel)) for (const c of names) el.classList.remove(c); - } - } - - const toggleClass = value.toggle_class || value.toggleClass; - if (isPlainObject(toggleClass)) { - for (const [sel, cls] of Object.entries(toggleClass)) { - for (const el of qsAll(sel)) { - if (cls) el.classList.toggle(String(cls)); - } - } - } - - const setStyle = value.set_style || value.setStyle; - if (isPlainObject(setStyle)) { - for (const [sel, st] of Object.entries(setStyle)) { - for (const el of qsAll(sel)) applyStyle(el, st); - } - } - - for (const sel of asSelList(value.focus)) { - const el = qsOne(sel); - if (el && el.focus) el.focus(); - } - for (const sel of asSelList(value.blur)) { - const el = qsOne(sel); - if (el && el.blur) el.blur(); - } - for (const sel of asSelList(value.scroll_into || value.scrollInto)) { - const el = qsOne(sel); - if (el && el.scrollIntoView) el.scrollIntoView({ block: "nearest", behavior: "smooth" }); - } - - const setHtml = value.set_html || value.setHtml; - if (isPlainObject(setHtml)) { - for (const [sel, html] of Object.entries(setHtml)) { - for (const el of qsAll(sel)) el.innerHTML = String(html); - } - } - - const appendHtml = value.append_html || value.appendHtml; - if (isPlainObject(appendHtml)) { - for (const [sel, html] of Object.entries(appendHtml)) { - for (const el of qsAll(sel)) el.insertAdjacentHTML("beforeend", String(html)); - } - } - - const replaceChildren = value.replace_children || value.replaceChildren; - if (isPlainObject(replaceChildren)) { - for (const [sel, html] of Object.entries(replaceChildren)) { - for (const el of qsAll(sel)) el.innerHTML = String(html); - } - } - - const renderList = value.render_list || value.renderList; - if (isPlainObject(renderList)) { - for (const [sel, spec] of Object.entries(renderList)) { - if (!isPlainObject(spec)) continue; - const html = renderListItems(spec); - for (const el of qsAll(sel)) el.innerHTML = html; - } - } - - const removeSel = value.remove || value.remove_nodes || value.removeNodes; - if (removeSel) { - for (const sel of asSelList(removeSel)) { - for (const el of qsAll(sel)) el.remove(); - } - } - - const nav = value.navigate; - if (isPlainObject(nav) && nav.url != null && typeof history !== "undefined") { - const url = String(nav.url); - if (nav.replace) history.replaceState(nav.state ?? null, "", url); - else history.pushState(nav.state ?? null, "", url); - } - - const clip = value.clipboard || value.copy; - if (clip != null && typeof navigator !== "undefined" && navigator.clipboard?.writeText) { - const text = isPlainObject(clip) ? String(clip.text ?? "") : String(clip); - navigator.clipboard.writeText(text).catch(() => {}); - } - - const dl = value.download; - if (isPlainObject(dl) && dl.body != null) { - const mime = String(dl.mime || "text/plain;charset=utf-8"); - const name = String(dl.filename || "download.txt"); - const blob = new Blob([String(dl.body)], { type: mime }); - const url = URL.createObjectURL(blob); - const a = document.createElement("a"); - a.href = url; - a.download = name; - a.click(); - URL.revokeObjectURL(url); - } - - const canvasSpec = value.canvas; - if (isPlainObject(canvasSpec) && canvasSpec.sel) { - runCanvasCommands(canvasSpec); - } - - const audioSpec = value.audio; - if (isPlainObject(audioSpec) && audioSpec.op) { - runAudioEffect(audioSpec); - } -} - -const intervalHandles = new Map(); -const wsHandles = new Map(); -const audioHandles = new Map(); -const observeHandles = new Map(); -let wsSeq = 0; -let observeSeq = 0; - -/** @param {{ sel: string, commands?: object[], clear?: boolean }} spec */ -export function runCanvasCommands(spec) { - if (typeof document === "undefined") return; - const el = qsOne(String(spec.sel)); - if (!el || typeof el.getContext !== "function") return; - const ctx = el.getContext("2d"); - if (!ctx) return; - if (spec.clear) ctx.clearRect(0, 0, el.width || 0, el.height || 0); - const cmds = Array.isArray(spec.commands) - ? spec.commands - : isPlainObject(spec.commands) - ? Object.keys(spec.commands) - .sort() - .map((k) => spec.commands[k]) - : []; - for (const raw of cmds) { - if (!isPlainObject(raw)) continue; - const op = String(raw.op || raw.cmd || "").toLowerCase(); - try { - if (op === "clear" || op === "clearrect") { - ctx.clearRect( - Number(raw.x) || 0, - Number(raw.y) || 0, - Number(raw.w ?? raw.width ?? el.width) || 0, - Number(raw.h ?? raw.height ?? el.height) || 0, - ); - } else if (op === "fillstyle") { - ctx.fillStyle = String(raw.value ?? raw.color ?? "#000"); - } else if (op === "strokestyle") { - ctx.strokeStyle = String(raw.value ?? raw.color ?? "#000"); - } else if (op === "linewidth") { - ctx.lineWidth = Number(raw.value ?? raw.width) || 1; - } else if (op === "font") { - ctx.font = String(raw.value || "16px sans-serif"); - } else if (op === "fillrect") { - if (raw.fill != null) ctx.fillStyle = String(raw.fill); - ctx.fillRect(Number(raw.x) || 0, Number(raw.y) || 0, Number(raw.w ?? raw.width) || 0, Number(raw.h ?? raw.height) || 0); - } else if (op === "strokerect") { - if (raw.stroke != null) ctx.strokeStyle = String(raw.stroke); - ctx.strokeRect(Number(raw.x) || 0, Number(raw.y) || 0, Number(raw.w ?? raw.width) || 0, Number(raw.h ?? raw.height) || 0); - } else if (op === "beginpath") { - ctx.beginPath(); - } else if (op === "closepath") { - ctx.closePath(); - } else if (op === "moveto") { - ctx.moveTo(Number(raw.x) || 0, Number(raw.y) || 0); - } else if (op === "lineto") { - ctx.lineTo(Number(raw.x) || 0, Number(raw.y) || 0); - } else if (op === "arc") { - ctx.arc( - Number(raw.x) || 0, - Number(raw.y) || 0, - Number(raw.r ?? raw.radius) || 0, - Number(raw.start ?? 0), - Number(raw.end ?? Math.PI * 2), - !!raw.ccw, - ); - } else if (op === "stroke") { - if (raw.stroke != null) ctx.strokeStyle = String(raw.stroke); - ctx.stroke(); - } else if (op === "fill") { - if (raw.fill != null) ctx.fillStyle = String(raw.fill); - ctx.fill(); - } else if (op === "filltext") { - if (raw.fill != null) ctx.fillStyle = String(raw.fill); - ctx.fillText(String(raw.text ?? ""), Number(raw.x) || 0, Number(raw.y) || 0); - } else if (op === "drawimage" && raw.src) { - const img = new Image(); - img.src = String(raw.src); - // sync only if already loaded; else fire-and-forget draw on load - const draw = () => { - ctx.drawImage( - img, - Number(raw.x) || 0, - Number(raw.y) || 0, - Number(raw.w ?? raw.width ?? img.width) || img.width, - Number(raw.h ?? raw.height ?? img.height) || img.height, - ); - }; - if (img.complete) draw(); - else img.onload = draw; - } - } catch (_) { - /* skip bad cmd */ - } - } -} - -function runAudioEffect(spec) { - const op = String(spec.op || "").toLowerCase(); - const id = String(spec.id || spec.sel || "default"); - try { - if (op === "play") { - // Optional beep via Web Audio (no external file). - if (spec.freq != null || spec.frequency != null || String(spec.src || "") === "beep") { - const AC = window.AudioContext || window.webkitAudioContext; - if (!AC) return; - let ctx = audioHandles.get(`${id}:ctx`); - if (!ctx) { - ctx = new AC(); - audioHandles.set(`${id}:ctx`, ctx); - } - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = String(spec.wave || "sine"); - osc.frequency.value = Number(spec.freq ?? spec.frequency ?? 440); - const vol = spec.volume != null ? Math.min(1, Math.max(0, Number(spec.volume))) : 0.15; - gain.gain.value = vol; - osc.connect(gain); - gain.connect(ctx.destination); - const dur = Number(spec.ms ?? spec.duration ?? 280) / 1000; - osc.start(); - gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + Math.max(0.05, dur)); - osc.stop(ctx.currentTime + Math.max(0.05, dur) + 0.02); - return; - } - let audio = audioHandles.get(id); - if (spec.sel) { - const el = qsOne(String(spec.sel)); - if (el && el.tagName === "AUDIO") audio = el; - } - if (!audio) { - audio = new Audio(spec.src != null ? String(spec.src) : undefined); - audioHandles.set(id, audio); - } else if (spec.src != null) { - audio.src = String(spec.src); - } - if (spec.volume != null) audio.volume = Math.min(1, Math.max(0, Number(spec.volume))); - if (spec.loop != null) audio.loop = !!spec.loop; - const p = audio.play(); - if (p && p.catch) p.catch(() => {}); - return; - } - const audio = spec.sel ? qsOne(String(spec.sel)) : audioHandles.get(id); - if (!audio) return; - if (op === "pause") audio.pause(); - else if (op === "stop") { - audio.pause(); - try { - audio.currentTime = 0; - } catch (_) { - /* ignore */ - } - } - } catch (_) { - /* ignore */ - } -} - -/** - * Run sync DOM patches then schedule async effects. - */ -export function applyEffects(exports, value, { onError } = {}) { - applyDomPatch(value); - if (!value || typeof value !== "object") return Promise.resolve(); - - const tasks = []; - - const fetchSpec = value.fetch; - if (fetchSpec && typeof fetchSpec === "object" && fetchSpec.url && fetchSpec.then) { - tasks.push(runFetchEffect(exports, fetchSpec, onError)); - } - - const fetchAll = value.fetch_all || value.fetchAll; - if (fetchAll && typeof fetchAll === "object" && fetchAll.then) { - tasks.push(runFetchAllEffect(exports, fetchAll, onError)); - } - - const afterSpec = value.after; - if (afterSpec && typeof afterSpec === "object" && afterSpec.then) { - tasks.push(runAfterEffect(exports, afterSpec, onError)); - } - - const intervalSpec = value.interval; - if (intervalSpec && typeof intervalSpec === "object" && intervalSpec.then) { - runIntervalEffect(exports, intervalSpec, onError); - } - - const clearIv = value.clear_interval || value.clearInterval; - if (clearIv && typeof clearIv === "object") { - const id = String(clearIv.id || "default"); - const h = intervalHandles.get(id); - if (h != null) { - clearInterval(h); - intervalHandles.delete(id); - } - } - - const storageSpec = value.storage; - if (storageSpec && typeof storageSpec === "object" && storageSpec.op) { - tasks.push(runStorageEffect(exports, storageSpec, onError)); - } - - const wsSpec = value.ws; - if (wsSpec && typeof wsSpec === "object" && wsSpec.op) { - tasks.push(runWsEffect(exports, wsSpec, onError)); - } - - const readFile = value.read_file || value.readFile; - if (readFile && typeof readFile === "object" && readFile.then) { - tasks.push(runReadFileEffect(exports, readFile, onError)); - } - - const observe = value.observe; - if (observe) { - const specs = Array.isArray(observe) - ? observe - : observe && typeof observe === "object" && observe.then - ? [observe] - : []; - for (const spec of specs) runObserveEffect(exports, spec, onError); - } - - const unobserve = value.unobserve; - if (unobserve) { - const specs = Array.isArray(unobserve) - ? unobserve - : unobserve && typeof unobserve === "object" - ? [unobserve] - : []; - for (const spec of specs) { - const id = String(spec.id || ""); - const h = observeHandles.get(id); - if (h) { - try { - h.disconnect(); - } catch (_) { - /* ignore */ - } - observeHandles.delete(id); - } - } - } - - return Promise.all(tasks); -} - -async function runReadFileEffect(exports, spec, onError) { - const thenFn = spec.then; - const sel = String(spec.sel || ""); - const as = String(spec.as || "text").toLowerCase(); - const input = qsOne(sel); - if (!input || !input.files || !input.files.length) { - const result = call(exports, thenFn, { ok: false, error: "no file", sel }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - return; - } - const file = input.files[Number(spec.index) || 0]; - try { - let body = ""; - let data_url = ""; - if (as === "data_url" || as === "dataurl") { - data_url = await new Promise((resolve, reject) => { - const r = new FileReader(); - r.onload = () => resolve(String(r.result || "")); - r.onerror = () => reject(r.error || new Error("read failed")); - r.readAsDataURL(file); - }); - } else { - body = await file.text(); - } - const result = call(exports, thenFn, { - ok: true, - name: file.name, - size: file.size, - type: file.type || "", - body, - data_url, - as, - }); - if (!result.ok) { - if (onError) onError(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - } catch (e) { - try { - const result = call(exports, thenFn, { ok: false, error: String(e), name: file.name }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - else if (onError) onError(result.error); - } catch (e2) { - if (onError) onError(String(e2)); - } - } -} - -function runObserveEffect(exports, spec, onError) { - const kind = String(spec.kind || spec.type || "intersect").toLowerCase(); - const sel = String(spec.sel || ""); - const thenFn = spec.then; - const id = String(spec.id || `obs${++observeSeq}`); - const el = qsOne(sel); - if (!el || !thenFn) return; - - const prev = observeHandles.get(id); - if (prev) { - try { - prev.disconnect(); - } catch (_) { - /* ignore */ - } - } - - const fire = (payload) => { - try { - const result = call(exports, thenFn, payload); - if (!result.ok) { - if (onError) onError(result.error); - return; - } - applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - }; - - if (kind === "resize" && typeof ResizeObserver !== "undefined") { - const ro = new ResizeObserver((entries) => { - const en = entries[0]; - const cr = en?.contentRect; - fire({ - ok: true, - kind: "resize", - id, - width: cr ? cr.width : 0, - height: cr ? cr.height : 0, - }); - }); - ro.observe(el); - observeHandles.set(id, ro); - return; - } - - if (typeof IntersectionObserver !== "undefined") { - const io = new IntersectionObserver( - (entries) => { - const en = entries[0]; - if (!en) return; - fire({ - ok: true, - kind: "intersect", - id, - intersecting: !!en.isIntersecting, - ratio: en.intersectionRatio, - }); - if (spec.once && en.isIntersecting) { - try { - io.disconnect(); - } catch (_) { - /* ignore */ - } - observeHandles.delete(id); - } - }, - { threshold: spec.threshold != null ? Number(spec.threshold) : 0.1 }, - ); - io.observe(el); - observeHandles.set(id, io); - } -} - -function buildFetchInit(spec) { - const method = (spec.method || "GET").toUpperCase(); - const init = { method }; - if (spec.headers && typeof spec.headers === "object") init.headers = { ...spec.headers }; - if (spec.fields && typeof spec.fields === "object" && typeof FormData !== "undefined") { - const fd = new FormData(); - for (const [k, v] of Object.entries(spec.fields)) fd.append(k, String(v)); - init.body = fd; - } else if (spec.body != null && method !== "GET" && method !== "HEAD") { - init.body = typeof spec.body === "string" ? spec.body : JSON.stringify(spec.body); - } - return init; -} - -async function runFetchEffect(exports, spec, onError) { - const thenFn = spec.then; - try { - const res = await fetch(String(spec.url), buildFetchInit(spec)); - const body = await res.text(); - const result = call(exports, thenFn, { ok: res.ok, status: res.status, body }); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - if (result.stdout) console.log(result.stdout); - } catch (e) { - try { - const result = call(exports, thenFn, { - ok: false, - status: 0, - body: "", - error: String(e), - }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - else if (onError) onError(result.error); - } catch (e2) { - if (onError) onError(String(e2)); - else console.error(e2); - } - } -} - -async function runFetchAllEffect(exports, spec, onError) { - const thenFn = spec.then; - const reqs = Array.isArray(spec.requests) - ? spec.requests - : isPlainObject(spec.requests) - ? Object.keys(spec.requests) - .sort() - .map((k) => spec.requests[k]) - .filter((r) => r && typeof r === "object") - : []; - try { - const results = await Promise.all( - reqs.map(async (r) => { - try { - const res = await fetch(String(r.url), buildFetchInit(r)); - const body = await res.text(); - return { ok: res.ok, status: res.status, body, url: String(r.url) }; - } catch (e) { - return { ok: false, status: 0, body: "", error: String(e), url: String(r.url || "") }; - } - }), - ); - const result = call(exports, thenFn, { ok: true, results }); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - } -} - -function runAfterEffect(exports, spec, onError) { - const ms = Math.max(0, Number(spec.ms) || 0); - const thenFn = spec.then; - return new Promise((resolve) => { - setTimeout(() => { - try { - const result = call(exports, thenFn, { ok: true }); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - resolve(); - return; - } - Promise.resolve(applyEffects(exports, result.value, { onError })).then(resolve); - if (result.stdout) console.log(result.stdout); - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - resolve(); - } - }, ms); - }); -} - -function runIntervalEffect(exports, spec, onError) { - const ms = Math.max(1, Number(spec.ms) || 1000); - const thenFn = spec.then; - const id = String(spec.id || "default"); - if (intervalHandles.has(id)) { - clearInterval(intervalHandles.get(id)); - intervalHandles.delete(id); - } - const handle = setInterval(() => { - try { - const result = call(exports, thenFn, { ok: true, id }); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - return; - } - applyEffects(exports, result.value, { onError }); - if (result.stdout) console.log(result.stdout); - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - } - }, ms); - intervalHandles.set(id, handle); -} - -function storageStore(scope) { - if (scope === "cookie") return null; - if (typeof localStorage === "undefined") return null; - return scope === "session" ? sessionStorage : localStorage; -} - -function cookieGet(key) { - if (typeof document === "undefined") return null; - const prefix = encodeURIComponent(key) + "="; - for (const part of document.cookie.split(";")) { - const s = part.trim(); - if (s.startsWith(prefix)) return decodeURIComponent(s.slice(prefix.length)); - } - return null; -} - -function cookieSet(key, value, days) { - if (typeof document === "undefined") return; - let extra = "; path=/"; - if (days != null && Number(days) > 0) { - const d = new Date(); - d.setTime(d.getTime() + Number(days) * 864e5); - extra += "; expires=" + d.toUTCString(); - } - document.cookie = encodeURIComponent(key) + "=" + encodeURIComponent(value) + extra; -} - -function cookieRemove(key) { - if (typeof document === "undefined") return; - document.cookie = encodeURIComponent(key) + "=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"; -} - -async function runStorageEffect(exports, spec, onError) { - const op = String(spec.op || "").toLowerCase(); - const key = String(spec.key || ""); - const scope = String(spec.scope || "local"); - try { - if (scope === "cookie") { - if (op === "set") { - cookieSet(key, spec.value != null ? String(spec.value) : "", spec.days); - } else if (op === "remove" || op === "delete") { - cookieRemove(key); - } else if (op === "get") { - const value = cookieGet(key); - if (spec.then) { - const result = call(exports, spec.then, { - ok: true, - op, - key, - value: value == null ? "" : value, - found: value != null, - scope, - }); - if (!result.ok) { - if (onError) onError(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - } - return; - } - if (spec.then && op !== "get") { - const result = call(exports, spec.then, { ok: true, op, key, scope }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - } - return; - } - - const store = storageStore(scope); - if (!store) { - if (onError) onError("storage unavailable"); - return; - } - if (op === "set") { - store.setItem(key, spec.value != null ? String(spec.value) : ""); - if (spec.then) { - const result = call(exports, spec.then, { ok: true, op, key, scope }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - } - return; - } - if (op === "remove" || op === "delete") { - store.removeItem(key); - if (spec.then) { - const result = call(exports, spec.then, { ok: true, op, key, scope }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - } - return; - } - if (op === "get") { - const value = store.getItem(key); - if (spec.then) { - const result = call(exports, spec.then, { - ok: true, - op, - key, - value: value == null ? "" : value, - found: value != null, - scope, - }); - if (!result.ok) { - if (onError) onError(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - } - } - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - } -} - -function runWsEffect(exports, spec, onError) { - const op = String(spec.op || "").toLowerCase(); - return new Promise((resolve) => { - try { - if (op === "open") { - if (typeof WebSocket === "undefined") { - if (onError) onError("WebSocket unavailable"); - resolve(); - return; - } - const id = String(spec.id || `ws${++wsSeq}`); - const sock = new WebSocket(String(spec.url)); - wsHandles.set(id, sock); - sock.addEventListener("open", () => { - if (spec.then_open || spec.thenOpen) { - try { - const result = call(exports, spec.then_open || spec.thenOpen, { ok: true, id }); - if (result.ok) applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - } - resolve(); - }); - sock.addEventListener("message", (ev) => { - const thenMsg = spec.then_message || spec.thenMessage; - if (!thenMsg) return; - try { - const result = call(exports, thenMsg, { - ok: true, - id, - data: typeof ev.data === "string" ? ev.data : String(ev.data), - }); - if (result.ok) applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - }); - sock.addEventListener("close", () => { - wsHandles.delete(id); - const thenClose = spec.then_close || spec.thenClose; - if (thenClose) { - try { - const result = call(exports, thenClose, { ok: true, id }); - if (result.ok) applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - } - }); - sock.addEventListener("error", () => { - const thenErr = spec.then_error || spec.thenError; - if (thenErr) { - try { - const result = call(exports, thenErr, { ok: false, id, error: "ws error" }); - if (result.ok) applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - } - }); - return; - } - if (op === "send") { - const id = String(spec.id || [...wsHandles.keys()][0] || ""); - const sock = wsHandles.get(id); - if (sock && sock.readyState === WebSocket.OPEN) { - sock.send(spec.data != null ? String(spec.data) : ""); - } else if (onError) onError(`ws send: no open socket ${id}`); - resolve(); - return; - } - if (op === "close") { - const id = String(spec.id || [...wsHandles.keys()][0] || ""); - const sock = wsHandles.get(id); - if (sock) sock.close(); - wsHandles.delete(id); - resolve(); - return; - } - resolve(); - } catch (e) { - if (onError) onError(String(e)); - resolve(); - } - }); -} - -function bindTarget(sel) { - if (sel === "window" || sel === "@window") return typeof window !== "undefined" ? window : null; - if (sel === "document" || sel === "@document") - return typeof document !== "undefined" ? document : null; - return null; -} - -/** - * Wire events from `# main` return value (list or `{ wire: [...] }`). - */ -export function wireEvents(exports, bootValue, { onError } = {}) { - let rows = []; - if (Array.isArray(bootValue)) rows = bootValue; - else if (bootValue && Array.isArray(bootValue.wire)) rows = bootValue.wire; - - for (const row of rows) { - const sel = row["选择器"] || row.selector || row.sel; - const ev = row["事件"] || row.event || "click"; - const fn = row["调用"] || row.call || row.fn; - const valueFrom = - row["值选择器"] || row.value_from || row.valueFrom || row.from || ""; - const delegate = - row["委托"] || row.delegate || row.delegation || ""; - if (!sel || !fn) continue; - - const special = bindTarget(sel); - const roots = special - ? [special] - : typeof document !== "undefined" - ? [...document.querySelectorAll(sel)] - : []; - - roots.forEach((node) => { - node.addEventListener(ev, (domEv) => { - try { - if (delegate) { - const hit = - typeof domEv.target?.closest === "function" - ? domEv.target.closest(delegate) - : null; - if (!hit || (node.contains && !node.contains(hit))) return; - } - // Drag/drop hosts need preventDefault on dragover/drop; dragstart can set payload. - if ( - ev === "dragover" || - ev === "dragenter" || - ev === "drop" || - ev === "dragstart" - ) { - try { - domEv.preventDefault(); - } catch (_) { - /* ignore */ - } - } - if (ev === "dragstart" && domEv.dataTransfer) { - try { - const payload = - (domEv.target && - typeof domEv.target.getAttribute === "function" && - domEv.target.getAttribute("data-drag")) || - (typeof domEv.target?.textContent === "string" - ? domEv.target.textContent.trim() - : "") || - ""; - if (payload) { - domEv.dataTransfer.setData("text/plain", payload); - domEv.dataTransfer.setData("text", payload); - domEv.dataTransfer.effectAllowed = "copyMove"; - } - } catch (_) { - /* ignore */ - } - } - if ( - ev === "click" && - typeof domEv.target?.closest === "function" && - domEv.target.closest("a[href]") - ) { - try { - domEv.preventDefault(); - } catch (_) { - /* ignore */ - } - } - const args = eventArgsFromDom(domEv, valueFrom); - if (delegate && domEv.target) { - const hit = domEv.target.closest?.(delegate); - if (hit?.getAttribute) { - const did = hit.getAttribute("data-id"); - if (did != null) args.data_id = did; - if (hit.id) args.id = hit.id; - const drag = hit.getAttribute("data-drag"); - if (drag != null) args.drag = drag; - } - } - const result = call(exports, fn, args); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - return; - } - applyEffects(exports, result.value, { onError }); - if (result.stdout) console.log(result.stdout); - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - } - }); - }); - } - return rows.length; -} - -function markReady(opts, message) { - if (opts.ready && typeof document !== "undefined") { - const el = document.querySelector(opts.ready); - if (el) { - el.classList?.remove?.("err"); - el.textContent = message; - } - } - if (opts.enable && typeof document !== "undefined") { - for (const sel of String(opts.enable).split(",")) { - const s = sel.trim(); - if (!s) continue; - document.querySelectorAll(s).forEach((n) => { - n.disabled = false; - n.removeAttribute("disabled"); - }); - } - } -} - -function markError(opts, err) { - const msg = String(err); - if (opts.onError) opts.onError(msg); - if (opts.ready && typeof document !== "undefined") { - const el = document.querySelector(opts.ready); - if (el) { - el.classList?.add?.("err"); - el.textContent = msg; - } - } else { - console.error(msg); - } -} - -function wirePlayground(exports, playgroundSpec, { onError } = {}) { - const parts = String(playgroundSpec) - .split(",") - .map((s) => s.trim()) - .filter(Boolean); - const sourceSel = parts[0] || "#src"; - const runSel = parts[1] || "#run"; - const outSel = parts[2] || "#out"; - const runBtn = document.querySelector(runSel); - const src = document.querySelector(sourceSel); - const out = document.querySelector(outSel); - if (!runBtn || !src) return 0; - runBtn.disabled = false; - runBtn.removeAttribute("disabled"); - runBtn.addEventListener("click", () => { - try { - const result = runSource(exports, src.value || ""); - if (out) { - out.classList?.toggle?.("err", !result.ok); - out.textContent = result.ok - ? (result.stdout || "(empty stdout)") + - (result.value != null && result.value !== "None" - ? `\n[return] ${typeof result.value === "string" ? result.value : JSON.stringify(result.value)}` - : "") - : result.error || "error"; - } - } catch (e) { - if (onError) onError(String(e)); - else if (out) { - out.classList?.add?.("err"); - out.textContent = String(e); - } - } - }); - return 1; -} - -export async function mount(rawOpts = {}) { - const opts = normalizeMountOptions(rawOpts); - const onError = (err) => markError(opts, err); - - let exports; - try { - exports = await loadWasm(opts.wasmUrl); - } catch (e) { - onError(e); - throw e; - } - - const ver = readCString(exports.memory, exports.mq_version()); - - if (opts.playground) { - const n = wirePlayground(exports, opts.playground, { onError }); - markReady(opts, `marqdo-wasm ${ver} · playground ready`); - return { exports, boot: null, wired: n }; - } - - let source = opts.source; - if (!source && opts.sourceUrl) { - const res = await fetch(opts.sourceUrl); - if (!res.ok) { - const err = `failed to load ${opts.sourceUrl} (${res.status})`; - onError(err); - throw new Error(err); - } - source = await res.text(); - } - if (!source) { - const err = "mount: need source, sourceUrl, or playground"; - onError(err); - throw new Error(err); - } - - const result = boot(exports, source); - if (!result.ok) { - onError(result.error || "boot failed"); - throw new Error(result.error || "boot failed"); - } - - if (result.value && !Array.isArray(result.value)) { - await applyEffects(exports, result.value, { onError }); - } - - const n = wireEvents(exports, result.value, { onError }); - const srcLabel = opts.sourceUrl || "(inline)"; - markReady(opts, `marqdo-wasm ${ver} · wired ${n} handler(s)\nsource: ${srcLabel}`); - return { exports, boot: result, wired: n }; -} - -export async function autoMount(doc) { - const configs = collectMountConfigs(doc); - const results = []; - for (const cfg of configs) { - if (cfg.noBoot) continue; - results.push(await mount(cfg)); - } - return results; -} - -const g = typeof globalThis !== "undefined" ? globalThis : undefined; -if (g && g.document) { - const start = () => { - autoMount(g.document).catch((e) => console.error("marqdo autoMount:", e)); - }; - if (g.document.readyState === "loading") { - g.document.addEventListener("DOMContentLoaded", start); - } else { - queueMicrotask(start); - } -} diff --git a/examples/browser-app/static/app.mq.md b/examples/browser-app/static/app.mq.md new file mode 100644 index 0000000..a6c4af8 --- /dev/null +++ b/examples/browser-app/static/app.mq.md @@ -0,0 +1,568 @@ +--- +markup: occlusion +title: Browser effects — native records and explicit completion +description: list CRUD, storage, navigate, interval, fetch_all, ws — GFM + lib/browser +import: + browser: lib/browser.mq.md + table: lib/table.mq.md + text: lib/text.mq.md +--- + +# main + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Initial browser view/state record | + +This entry prepares browser instructions; it does not itself fetch a URL or manipulate a server filesystem. The host page must supply the selectors listed below. List state uses native records with stable ids, keeping duplicate text and literal newlines independent. The wire table maps each UI event to one actual callback, including delegated item buttons, history navigation, timer controls, parallel fetches and a named WebSocket connection. + +Event declarations contain no user values interpolated into code. Input values flow through callback parameters while the server page remains a separate document. + +The returned boot record combines event registration and a storage lookup, without pushing an initial history entry. The browser bridge applies those instructions and dispatches later events into the callbacks. Draft text, tick count, route and socket identifier belong to that browser instance. Storage callbacks complete asynchronously; the initial return is not proof that a saved draft was found. + +We **ticks = 0** as the retained count before the first real timer event. +We **items = [Start native list state](table.empty_list())** and **next_id = 1** for independent record identities. +We **route_path = "/"** as this browser instance’s panel state. +We **ws_id = "echo"** as the one named local connection. + +`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 | | | + +`st` = + +| op | key | then | +|----|-----|------| +| get | mq-draft | on_draft | + +`boot` = + +| wire | storage | +|---|---| +| `wire` | `st` | + +After these steps, return *boot*. + +## add + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | text | "" | Exact draft text supplied by the add control | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Native list refresh, input clear and focus; None for empty text | + +Use `value`="" from the input. Retain each nonempty value exactly as one record, including quotes, angle brackets or a literal newline. A monotonically assigned id separates duplicate titles; deleting one must not erase its siblings. This direct callback updates entry state, then passes those records explicitly to the pure renderer. No business value is interpolated into HTML. + +The input clears and regains focus after a real local addition. An empty string returns None without changing records or consuming an id. This list is session memory; only the separately saved draft uses browser storage. + +1. `value` == "" + Return *None* because there is no new item. +We **id = [Assign an independent stable identity](str(next_id))** and **next_id = next_id + 1**. + +`record` = + +| id | text | +|---|---| +| `id` | `value` | + +We **items = [Retain the actual text record](table.append(list=`items`, item=`record`))** and **view = [Render typed labels and delete controls](_list(records=`items`))** and **clear = [Clear the completed input](browser.set_value(sel="#draft", value=""))** and **focus = [Return to the draft control](browser.focus(sel="#draft"))**. +We **view = [Keep the independent list and value effects](browser.merge(a=`view`, b=`clear`))**. +Return *[Keep focus with the completed list update](browser.merge(a=`view`, b=`focus`))*. + +## on_item + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| data_id | text | "" | Stable id supplied by the delegated delete button | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Remaining native records and removal feedback, or None for an unknown id | + +Use `data_id`="" from button[data-id]. Compare identities rather than text, so duplicate values and values containing newlines stay independent. Preserve remaining order and do nothing for an empty or unknown id. The renderer receives retained records explicitly; it does not infer client state inside a normal helper call. + +A deletion rebuilds the same list through typed controls and reports the removed id as text. It neither modifies a saved draft nor changes timer, transport or route state. Ids are not recycled after deletion, avoiding a stale event selecting a different later item. + +1. `data_id` == "" + Return *None* for an absent selection. +We **remaining = [Start the retained row order](table.empty_list())**. +- [Keep every record except the selected identity](for items as item) + 1. access(`item`, "id") != `data_id` + We **remaining = [Keep this independent record](table.append(list=`remaining`, item=`item`))**. +1. len(`remaining`) == len(`items`) + Return *None* because no selected identity exists. +We **items = remaining** and **view = [Render the actual retained rows](_list(records=`items`))** and **message = "removed " + data_id** and **status = [Describe the observed local removal](browser.set_text(sel="#log", text=`message`))**. +Return *[Keep list and feedback together](browser.merge(a=`view`, b=`status`))*. + +## save_draft + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | text | "" | Exact text selected from the draft input | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Storage write request; completion arrives at on_saved | + +Use `value`="" from the draft control. The storage record names the local key and its completion callback. Return the request immediately; only on_saved can announce a successful write. An intentionally empty draft is valid and differs from an absent key. Storage belongs to this browser origin, while list records stay in session memory. Returning this record does not write server files or grant process access. + +`request` = + +| op | key | value | then | +|---|---|---|---| +| set | mq-draft | `value` | on_saved | + +Return *[Ask the browser to persist the exact draft](browser.storage(spec=`request`))*. + +## load_draft + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Storage read request with an explicit completion callback | + +Request mq-draft from this browser origin. The callback distinguishes a missing key, an empty saved value and a failed read. No input is cleared while the read is pending, and this operation never replaces the native item list. The same read runs at boot, so a reload restores the saved draft without claiming to persist list records. + +`request` = + +| op | key | then | +|---|---|---| +| get | mq-draft | on_draft | + +Return *[Request the stored draft and its actual outcome](browser.storage(spec=`request`))*. + +## on_draft + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| ok | bool | True | Actual storage-read completion | +| value | text | "" | Stored draft text, including an intentionally empty value | +| found | bool | False | Whether the key actually existed | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Restored value and feedback, or actual missing/failure feedback | + +Use `ok`=True, `value`="" and `found`=False from storage. A missing key differs from a stored empty draft, and an unsuccessful read must not be described as absence. Restore the exact value only after a successful read with found=True. This changes the draft input, not the native item list, and never interprets the stored text as code. + +1. not `ok` + Return *[Keep a failed read visible](browser.set_text(sel="#log", text="draft read failed"))*. +1. not `found` + Return *[Keep an absent draft visible](browser.set_text(sel="#log", text="no draft"))*. +We **value_effect = [Restore exact stored draft text](browser.set_value(sel="#draft", value=`value`))** and **status = [Confirm the observed read](browser.set_text(sel="#log", text="draft loaded"))**. +Return *[Keep the actual value and feedback](browser.merge(a=`value_effect`, b=`status`))*. + +## start_tick + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | One named repeating timer instruction | + +Start tick at one-second intervals. The bridge replaces a timer with the same id, so repeated Start clicks do not accumulate independent clocks. Each callback increments the session counter once. This returns an instruction; it is neither a blocking sleep nor proof that one second has passed. Stop cancels future callbacks and preserves the accumulated display. + +Return *[Start or replace the one named timer](browser.interval(ms=1000, then="on_tick", id="tick"))*. + +## stop_tick + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Cancellation of the named timer | + +Cancel tick through its explicit id. Calling Stop before Start is harmless, and stopping does not reset the visible count or alter other timers. A later Start resumes counting from retained state. The browser owns the timer handle; authors do not keep a JavaScript handle or generate a client program to clear it. + +Return *[Cancel future callbacks for this timer](browser.clear_interval(id="tick"))*. + +## on_tick + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| ok | bool | True | Whether this timer callback is valid | +| id | text | "" | Actual named timer id | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Updated count, or None for a failed/unrelated callback | + +Use `ok`=True and `id`="" from the timer. Count only successful events belonging to tick; unrelated callbacks must not change this counter. Retained ticks belongs to the direct browser callback, rather than being supplied by the event. A manual call to this function constructs the same text effect but does not prove that a real timer fired. + +1. not `ok` or `id` != "tick" + Return *None* for an unrelated timer outcome. +We **ticks = ticks + 1** and **label = [Format the actual accumulated count](str(ticks))**. +Return *[Display that observed timer count](browser.set_text(sel="#tick", text=`label`))*. + +## go_home + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Selected panel effects and one actual navigation request | + +Select / from its authored navigation control. This direct callback updates the retained panel state and requests exactly one history entry. The helper receives the path explicitly rather than assuming an ordinary call captures entry bindings. Back/Forward uses on_pop, which renders without navigation. No server request or page HTML is constructed here. + +We **route_path = "/"**. +Return *[Render and request this one deliberate navigation](_view(route=`route_path`, push=True))*. + +## go_about + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Selected panel effects and one actual navigation request | + +Select /about from its authored navigation control. This direct callback updates the retained panel state and requests exactly one history entry. The helper receives the path explicitly rather than assuming an ordinary call captures entry bindings. Back/Forward uses on_pop, which renders without navigation. No server request or page HTML is constructed here. + +We **route_path = "/about"**. +Return *[Render and request this one deliberate navigation](_view(route=`route_path`, push=True))*. + +## go_net + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Selected panel effects and one actual navigation request | + +Select /net from its authored navigation control. This direct callback updates the retained panel state and requests exactly one history entry. The helper receives the path explicitly rather than assuming an ordinary call captures entry bindings. Back/Forward uses on_pop, which renders without navigation. No server request or page HTML is constructed here. + +We **route_path = "/net"**. +Return *[Render and request this one deliberate navigation](_view(route=`route_path`, push=True))*. + +## on_pop + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | "" | Actual browser pathname, including optional query string | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | History-selected panel effects without pushing history again | + +Use `path`="" from the real popstate callback. Keep its normalized panel route in the differently named entry state, avoiding accidental shadowing of a callback parameter. The browser has already selected this history entry, so returning navigate would add an incorrect new entry. Query text does not choose a different panel; only the known pathname is used. + +We **parts = [Separate the pathname from query text](text.str_split(s=`path`, sep="?"))** and **route_path = [Keep the actual panel path](table.first(list=`parts`))**. +Return *[Reflect the actual history position](_view(route=`route_path`))*. + +## show_path + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Current panel visibility and label without history mutation | + +This direct browser callback reads retained route_path and delegates pure rendering with explicit input. It never pushes another history entry, so a repaint cannot trap Back/Forward. Call the navigation callbacks to request a new route. Server routing and page structure remain separate responsibilities; unknown browser paths select the home panel. + +Return *[Refresh the retained panel without navigating](_view(route=`route_path`))*. + +## do_fetch_all + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | The value explicitly returned below; conditional returns follow the selected branch | + +Queue two independent browser fetches and return an immediate loading message together with the request instruction. Results arrive through on_fetch_all; this initial return does not contain either HTTP response. The request table keeps both URLs visible and avoids generating JavaScript to construct the batch. + +The example endpoint is external and may fail or be unavailable. Consumers must inspect the actual callback records rather than count request declarations as successful responses. Browser network policy still applies; no backend file or shell operation is authorized by this instruction. + +`reqs` = + +| @ | url | +|---|-----| +| 1 | "https://httpbin.org/uuid" | +| 2 | "https://httpbin.org/uuid" | + +We **msg = [Describe the pending batch](browser.set_text(sel="#net-out", text="fetch_all…"))** and **requests = [Request both actual HTTP outcomes](browser.fetch_all(requests=`reqs`, then="on_fetch_all"))**. +Return *[Keep pending feedback with its asynchronous requests](browser.merge(a=`msg`, b=`requests`))*. + +## on_fetch_all + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| ok | bool | True | Whether the batch callback itself completed | +| results | any | None | Ordered per-request ok/status/body/error records | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Actual per-request outcomes shown as plain text | + +Use `ok`=True and `results`=None from the bridge. A completed batch can still contain failed HTTP or network operations; the outer callback flag does not make each record successful. Show the real ordered records, including status, body and errors, rather than a fixed completion message. Text output cannot become HTML or a browser command. + +A missing result list stays visibly unavailable. Public endpoints remain demonstration dependencies; local tests supply controlled responses and a failure. This callback does not retry a request or replace its body with a predetermined answer. + +1. not `ok` + Return *[Keep batch failure visible](browser.set_text(sel="#net-out", text="fetch_all failed"))*. +1. `results` == None + Return *[Keep absent results distinct](browser.set_text(sel="#net-out", text="fetch_all returned no results"))*. +We **message = [Retain actual request outcomes](str(results))**. +Return *[Display observed successes and failures literally](browser.set_text(sel="#net-out", text=`message`))*. + +## ws_open + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Named local WebSocket request and lifecycle callbacks | + +Open the site’s /live echo resource under the explicit echo id. A relative URL uses the current origin and its transport security, allowing the example to run without a public echo provider. The server separately binds this native network resource. Returning the record only requests a connection; open, message, error and close callbacks describe actual transport outcomes. Subsequent send and close instructions reuse the same id. + +`request` = + +| op | id | url | then_open | then_message | then_error | then_close | +|---|---|---|---|---|---|---|---| +| open | `ws_id` | "/live" | on_ws_open | on_ws_msg | on_ws_err | on_ws_close | + +Return *[Request the local echo connection](browser.ws(spec=`request`))*. + +## on_ws_open + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| ok | bool | True | Actual connection completion | +| id | text | "" | Connected socket id | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Confirmed connection text, or None for a failed/unrelated callback | + +Use `ok`=True and `id`="" from the real transport. Accept only the named echo socket; a different resource cannot announce this widget ready. This callback confirms the handshake, while sending still requires a separate user action. It neither invents a received message nor marks a requested connection successful before the bridge reports it. + +1. not `ok` or `id` != `ws_id` + Return *None* for an unrelated connection. +Return *[Confirm the observed handshake](browser.set_text(sel="#net-out", text="ws open"))*. + +## on_ws_msg + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| ok | bool | True | Actual message completion | +| data | text | "" | Exact received text | +| id | text | "" | Receiving socket id | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Literal received message, or None for a failed/unrelated callback | + +Use `ok`=True, `data`="" and `id`="" from the echo connection. Preserve the complete received text, including quotes and angle brackets. Display it through set_text so a message is data rather than page markup. Receipt is independent of the send click: the remote resource may respond later or close without replying. + +1. not `ok` or `id` != `ws_id` + Return *None* for an unrelated message. +We **message = "ws ← " + data**. +Return *[Display the actual echo as plain text](browser.set_text(sel="#net-out", text=`message`))*. + +## on_ws_err + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| ok | bool | False | Failure flag supplied by the bridge | +| error | text | "" | Actual transport failure text | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Visible transport failure | + +Use `ok`=False and `error`="" from the transport callback. Keep the actual error text in the output rather than substituting a success message. The callback performs no automatic reconnect and sends no pending message. Reopening is an explicit user operation; failures remain inspectable while the rest of the page can continue operating. + +We **message = "ws error: " + error**. +Return *[Expose the actual connection failure](browser.set_text(sel="#net-out", text=`message`))*. + +## on_ws_close + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| ok | bool | True | Actual close callback flag | +| id | text | "" | Closed socket id | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Observed close text, or None for an unrelated socket | + +Use `ok`=True and `id`="" after the bridge observes closure. The named socket may close because of the user’s request or the server. This is a lifecycle observation and does not itself initiate another close or reopen. Leave list state, draft and timer untouched so transport changes remain independent of local page work. + +1. `id` != `ws_id` + Return *None* for an unrelated socket. +Return *[Report the observed connection closure](browser.set_text(sel="#net-out", text="ws closed"))*. + +## ws_send + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | text | "" | Exact text selected from the message input | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Send request for the existing named socket | + +Use `value`="" as the message payload. Sending preserves literal text and addresses the existing echo socket; it does not create a second hidden connection. Open first and wait for the real connection callback. The request is not an echo result: only on_ws_msg displays a received response, and transport failures remain visible through the bridge. + +`request` = + +| op | id | data | +|---|---|---| +| send | `ws_id` | `value` | + +Return *[Send exact text through the named connection](browser.ws(spec=`request`))*. + +## ws_close + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Close request for the named socket | + +Ask the bridge to close echo, reusing the same identity as open and send. The close callback supplies the observed lifecycle result. Returning this instruction does not delete page records or cancel the independent timer. Closing an absent connection is harmless; opening a later connection remains an explicit user action. + +`request` = + +| op | id | +|---|---| +| close | `ws_id` | + +Return *[Request closure of this connection](browser.ws(spec=`request`))*. + +## copy_log + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Clipboard request and truthful queued feedback | + +Export the retained item texts in their current order, including duplicate values and literal newlines. The native records remain unchanged. This browser capability is a request: policy, user activation or the destination environment may prevent completion. The bridge exposes errors, and the immediate feedback says queued because no completion callback confirms a final clipboard write or saved file. + +We **plain = [Read the current literal list export](_plain(records=`items`))** and **request = [Request clipboard delivery](browser.clipboard(text=`plain`))** and **status = [Describe only the requested operation](browser.set_text(sel="#log", text="clipboard request queued"))**. +Return *[Keep the request and its truthful feedback](browser.merge(a=`request`, b=`status`))*. + +## dl_list + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Download request and truthful queued feedback | + +Export the retained item texts in their current order, including duplicate values and literal newlines. The native records remain unchanged. This browser capability is a request: policy, user activation or the destination environment may prevent completion. The bridge exposes errors, and the immediate feedback says queued because no completion callback confirms a final clipboard write or saved file. + +We **plain = [Read the current literal list export](_plain(records=`items`))** and **request = [Request the plain-text download](browser.download(body=`plain`, filename="items.txt"))** and **status = [Describe only the requested operation](browser.set_text(sel="#log", text="download request queued"))**. +Return *[Keep the request and its truthful feedback](browser.merge(a=`request`, b=`status`))*. + +## _list + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| records | list | required | Native id/text records in visible order | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Structured list effect with literal labels and native delete buttons | + +Use `records` from the direct callback's retained state. Each row contains a span label and button as typed children. The button's data-id carries the independent record identity; visible business text stays in text, never html. The official bridge escapes it and preserves delegation without rebuilding the parent page. + +This helper is pure and receives records explicitly. It does not read hidden entry state, delete anything or assume that a returned effect has already reached the DOM. The existing host list and event wiring own those later steps. + +We **rows = [Start the native visible row records](table.empty_list())**. +- [Describe one label and native delete action](for records as record) + We **id = [Retain the exact row identity](access(record, "id"))** and **value = [Retain literal business text](access(record, "text"))**. + + `label` = + + | tag | text | + |---|---| + | span | `value` | + + `attributes` = + + | type | data-id | + |---|---| + | button | `id` | + + `button` = + + | tag | text | attrs | + |---|---|---| + | button | 删 | `attributes` | + + `children` = + + | node | + |---| + | `label` | + | `button` | + + `row` = + + | tag | children | + |---|---| + | li | `children` | + + We **rows = [Retain this typed row](table.append(list=`rows`, item=`row`))**. +Return *[Update only the existing list](browser.render_list(sel="#items", items=`rows`))*. + + +## _view + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| route | text | required | Selected panel pathname | +| push | bool | False | Explicit navigation callback requests one history entry | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Actual boolean panel visibility, path label and optional deliberate navigation | + +Use `route` and `push`=False. Only /about and /net select secondary panels; other paths render Home. Hidden attributes are actual booleans, while False removes the attribute. The pure helper receives its path explicitly and does not pretend to capture the browser entry state. + +History observations use the default without navigation; authored link callbacks opt in once. Keep all three targets inside a single set_attr record because effect merging is shallow and otherwise one target map could overwrite another. This function performs no fetch, storage write or socket operation. + +We **selected = "/"**. +1. `route` == "/about" or `route` == "/net" + We **selected = route**. +We **home = [Describe Home visibility](table.put(in=None, at="hidden", value=(`selected` != "/")))** and **about = [Describe About visibility](table.put(in=None, at="hidden", value=(`selected` != "/about")))** and **network = [Describe Network visibility](table.put(in=None, at="hidden", value=(`selected` != "/net")))**. + +`targets` = + +| #panel-home | #panel-about | #panel-net | +|---|---|---| +| `home` | `about` | `network` | + +We **visibility = [Keep every panel target together](browser.wrap(key="set_attr", value=`targets`))** and **message = "path: " + selected** and **label = [Display the selected path](browser.set_text(sel="#path", text=`message`))** and **effects = [Keep independent visibility and text effects](browser.merge(a=`visibility`, b=`label`))**. +1. `push` + We **navigation = [Request one intentional history entry](browser.navigate(url=`selected`))** and **effects = [Keep navigation with its actual panel effects](browser.merge(a=`effects`, b=`navigation`))**. +Return *effects* after describing the real selected panel. + + +## _plain + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| records | list | required | Native text records in retained order | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Literal newline-joined values for copy or download | + +Use `records` to retain the original plain-text export purpose without turning the client state into a newline-encoded database. Each item's text remains a single native value; newlines are introduced only in this human-readable export. This pure transformation neither writes the clipboard nor starts a download, and it does not encode HTML. + +We **values = [Select actual text fields in order](table.pluck(list=`records`, key="text"))**. +Return *[Form the intended text export](text.str_join(xs=`values`, sep="\n"))*. + +## on_saved + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| ok | bool | True | Actual storage-write completion | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Feedback for the completed write | + +Use `ok`=True from the storage callback. Confirm saving after the browser reports completion, rather than when the user merely clicks Save. A failed callback remains a failure message. Host storage exceptions also appear through the official bridge error channel; this function cannot turn an unavailable storage service into a successful write. + +1. not `ok` + Return *[Expose the failed write](browser.set_text(sel="#log", text="draft save failed"))*. +Return *[Confirm the completed write](browser.set_text(sel="#log", text="draft saved"))*. diff --git a/examples/browser-app/styles/index.mq.md b/examples/browser-app/styles/index.mq.md new file mode 100644 index 0000000..304ae64 --- /dev/null +++ b/examples/browser-app/styles/index.mq.md @@ -0,0 +1,19 @@ +--- +markup: occlusion +title: Retained browser theme compilation +import: + document: lib/document.mq.md + web: ext/web/web.mq.md + text: lib/text.mq.md +--- + +## css + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Original theme declarations followed by bounded View geometry | + +Call with fs.read and plugin under the site root. The original table retains every declaration from the former host page, including fonts, green palette, panel spacing and feedback surfaces. The geometry table only adapts native View wrappers and long text for a narrow viewport. Compilation returns CSS through the existing native style capability; it neither writes a file nor starts a server. Serve owns the explicit generated output. Review the data leaf when adjusting appearance and verify actual computed styles in the browser. + +We **original = [Read all retained declarations](document.read_table(path="styles/theme.tables.md", title="original"))** and **geometry = [Read explicit native wrapper rules](document.read_table(path="styles/theme.tables.md", title="geometry"))** and **base = [Compile the retained theme](web.make_style(name="original", table=`original`))** and **wrappers = [Compile bounded View adaptation](web.make_style(name="geometry", table=`geometry`))**. +Return *[Keep original cascade before native adaptation](`base` + "\n" + `wrappers`)*. diff --git a/examples/browser-app/styles/theme.tables.md b/examples/browser-app/styles/theme.tables.md new file mode 100644 index 0000000..87eb0ae --- /dev/null +++ b/examples/browser-app/styles/theme.tables.md @@ -0,0 +1,88 @@ +# Browser example theme + +This literal data preserves the original browser-app palette, typefaces, spacing, backgrounds and controls. Region selectors are scoped to the native View frame. Callable compilation is documented in index.mq.md beside this data. + +## original + +Every original declaration appears in its original order. Only selectors gain the known frame address, keeping basic preview defaults from overriding the authored theme. + +| selector | property | value | +|---|---|---| +| ":root" | "--ink" | "#1a1f1c" | +| ":root" | "--paper" | "#e8efe6" | +| ":root" | "--accent" | "#2f6f4e" | +| ":root" | "--muted" | "#5a6b60" | +| "*" | "box-sizing" | "border-box" | +| "body" | "margin" | "0" | +| "body" | "min-height" | "100vh" | +| "body" | "font-family" | "\"IBM Plex Sans\", \"Noto Sans SC\", sans-serif" | +| "body" | "color" | "var(--ink)" | +| "body" | "background" | "linear-gradient(165deg, #f3f7f2, var(--paper))" | +| "body" | "padding" | "2rem clamp(1rem, 4vw, 3rem)" | +| ".mq-document .browser-app h1" | "font-family" | "\"IBM Plex Serif\", \"Noto Serif SC\", serif" | +| ".mq-document .browser-app h1" | "margin" | "0 0 0.35rem" | +| ".mq-document .browser-app .lead" | "color" | "var(--muted)" | +| ".mq-document .browser-app .lead" | "max-width" | "42rem" | +| ".mq-document .browser-app nav a" | "margin-right" | "0.75rem" | +| ".mq-document .browser-app nav a" | "color" | "var(--accent)" | +| ".mq-document .browser-app section" | "margin" | "1.5rem 0" | +| ".mq-document .browser-app section" | "padding" | "1rem 0" | +| ".mq-document .browser-app section" | "border-top" | "1px solid #c5d4c9" | +| ".mq-document .browser-app #path" | "font-family" | "ui-monospace, monospace" | +| ".mq-document .browser-app #path" | "color" | "var(--muted)" | +| ".mq-document .browser-app #items" | "list-style" | "none" | +| ".mq-document .browser-app #items" | "padding" | "0" | +| ".mq-document .browser-app #items" | "margin" | "0.75rem 0" | +| ".mq-document .browser-app #items li" | "display" | "flex" | +| ".mq-document .browser-app #items li" | "align-items" | "center" | +| ".mq-document .browser-app #items li" | "gap" | "0.5rem" | +| ".mq-document .browser-app #items li" | "padding" | "0.4rem 0.6rem" | +| ".mq-document .browser-app #items li" | "margin-bottom" | "0.35rem" | +| ".mq-document .browser-app #items li" | "background" | "rgba(255,255,255,0.65)" | +| ".mq-document .browser-app #items li" | "border" | "1px solid #b7c7bb" | +| ".mq-document .browser-app #items button" | "margin-left" | "auto" | +| ".mq-document .browser-app input[type=\"text\"]" | "padding" | "0.45rem 0.65rem" | +| ".mq-document .browser-app input[type=\"text\"]" | "border" | "1px solid #b7c7bb" | +| ".mq-document .browser-app input[type=\"text\"]" | "width" | "min(16rem, 70%)" | +| ".mq-document .browser-app button" | "padding" | "0.45rem 0.9rem" | +| ".mq-document .browser-app button" | "border" | "0" | +| ".mq-document .browser-app button" | "background" | "var(--accent)" | +| ".mq-document .browser-app button" | "color" | "#f5faf6" | +| ".mq-document .browser-app button" | "font" | "inherit" | +| ".mq-document .browser-app button" | "cursor" | "pointer" | +| ".mq-document .browser-app button" | "margin" | "0.2rem 0.35rem 0.2rem 0" | +| ".mq-document .browser-app button.secondary" | "background" | "#3a4740" | +| ".mq-document .browser-app #tick, #net-out" | "font-variant-numeric" | "tabular-nums" | +| ".mq-document .browser-app #net-out" | "min-height" | "2.5rem" | +| ".mq-document .browser-app #net-out" | "padding" | "0.6rem 0.75rem" | +| ".mq-document .browser-app #net-out" | "background" | "rgba(255,255,255,0.55)" | +| ".mq-document .browser-app #net-out" | "border" | "1px solid #b7c7bb" | +| ".mq-document .browser-app #net-out" | "white-space" | "pre-wrap" | +| ".mq-document .browser-app #net-out" | "word-break" | "break-all" | +| ".mq-document .browser-app pre" | "margin-top" | "1rem" | +| ".mq-document .browser-app pre" | "padding" | "0.85rem 1rem" | +| ".mq-document .browser-app pre" | "background" | "#122018" | +| ".mq-document .browser-app pre" | "color" | "#d7eadc" | +| ".mq-document .browser-app pre" | "font-size" | "0.8rem" | +| ".mq-document .browser-app pre" | "overflow" | "auto" | +| ".mq-document .browser-app pre" | "max-width" | "42rem" | +| ".mq-document .browser-app .err" | "color" | "#ffb4a8" | + +## geometry + +These additions adapt the preview wrappers and keep native controls and literal long text within a narrow viewport. They do not replace the retained palette or typography. + +| selector | property | value | +|---|---|---| +| ".mq-document .mq-view" | "max-width" | "none" | +| ".mq-document .mq-view" | "margin" | "0" | +| ".mq-document .mq-view" | "padding" | "0" | +| ".mq-document .mq-view" | "font-family" | "inherit" | +| ".mq-document .mq-view" | "line-height" | "inherit" | +| ".mq-document .browser-app" | "display" | "block" | +| ".mq-document .browser-app .mq-column" | "display" | "block" | +| ".mq-document .browser-app .mq-row" | "flex-wrap" | "wrap" | +| ".mq-document .browser-app #items span" | "overflow-wrap" | "anywhere" | +| ".mq-document .browser-app button" | "max-width" | "100%" | +| ".mq-document .browser-app pre" | "white-space" | "pre-wrap" | +| ".mq-document .browser-app pre" | "overflow-wrap" | "anywhere" | diff --git a/examples/browser-hello/README.md b/examples/browser-hello/README.md deleted file mode 100644 index e1111cf..0000000 --- a/examples/browser-hello/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# 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)。 diff --git a/examples/browser-hello/counter.mq.md b/examples/browser-hello/counter.mq.md deleted file mode 100644 index c624eb9..0000000 --- a/examples/browser-hello/counter.mq.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -markup: occlusion -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"* diff --git a/examples/browser-hello/fetch.html b/examples/browser-hello/fetch.html deleted file mode 100644 index 8de701e..0000000 --- a/examples/browser-hello/fetch.html +++ /dev/null @@ -1,86 +0,0 @@ - - - - - - Marqdo · fetch / after (C4) - - - -

      Marqdo

      -

      C4/D:返回 fetch / after 效应;bridge 自启(ADR 0003)。业务只在 fetch.mq.md。计数器 · 表单 · 打印

      -
      idle
      - - -
      loading…
      - - - diff --git a/examples/browser-hello/fetch.mq.md b/examples/browser-hello/fetch.mq.md deleted file mode 100644 index dd98c42..0000000 --- a/examples/browser-hello/fetch.mq.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -markup: occlusion -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"* diff --git a/examples/browser-hello/form.html b/examples/browser-hello/form.html deleted file mode 100644 index ffa4d5a..0000000 --- a/examples/browser-hello/form.html +++ /dev/null @@ -1,76 +0,0 @@ - - - - - - Marqdo · 表单 (D3) - - - -

      Marqdo

      -

      D3:input 事件把 value 传入 Marqdo;set_value / set_class / set_attr 回写 DOM。业务只在 form.mq.md。计数器 · 打印

      - - -
      (等待输入)
      -
      loading…
      - - - diff --git a/examples/browser-hello/form.mq.md b/examples/browser-hello/form.mq.md deleted file mode 100644 index 63aa108..0000000 --- a/examples/browser-hello/form.mq.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -markup: occlusion -title: browser form (D3) -description: input wire passes value; effects via lib/browser -import: - browser: lib/browser.mq.md - 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* diff --git a/examples/browser-hello/index.html b/examples/browser-hello/index.html deleted file mode 100644 index f3437dc..0000000 --- a/examples/browser-hello/index.html +++ /dev/null @@ -1,88 +0,0 @@ - - - - - - Marqdo browser hello (WASM C1) - - - -

      Marqdo

      -

      浏览器内 WASM(路线 C/D):源码是 .mq.md,官方 bridge 自启 playground,无作者业务 JS。交互 · fetch · 表单

      - - -
      - -
      -
      loading wasm…
      - - - diff --git a/examples/browser-hello/interact.html b/examples/browser-hello/interact.html deleted file mode 100644 index cf623a1..0000000 --- a/examples/browser-hello/interact.html +++ /dev/null @@ -1,79 +0,0 @@ - - - - - - Marqdo · 交互装配 (C3) - - - -

      Marqdo

      -

      C3/D:GFM 交互表装配事件;官方 mount 自启,业务只在 counter.mq.md。fetch · 表单 · 打印

      -
      0
      - - -
      loading…
      - - - diff --git a/examples/browser-hello/marqdo-bridge.js b/examples/browser-hello/marqdo-bridge.js deleted file mode 100644 index 3a5784a..0000000 --- a/examples/browser-hello/marqdo-bridge.js +++ /dev/null @@ -1,1436 +0,0 @@ -/** - * Canonical Marqdo browser bridge (routes C/D/E). Host glue only — not app logic. - * Authors write .mq.md only; this file may grow host mechanisms freely. - * - * ABI: mq_alloc, mq_dealloc, mq_run, mq_boot, mq_call, mq_version - * Effects: set_text, set_value, set_attr, set_class, toggle_class, set_style, - * focus, blur, scroll_into, set_html, replace_children, render_list, - * navigate, storage, ws, fetch, fetch_all, after, interval, clear_interval - */ - -export function readCString(memory, ptr) { - const bytes = new Uint8Array(memory.buffer); - let end = ptr; - while (bytes[end] !== 0) end += 1; - return new TextDecoder().decode(bytes.subarray(ptr, end)); -} - -function decodePacked(exports, outPtr) { - if (!outPtr) throw new Error("null wasm result pointer"); - const view = new DataView(exports.memory.buffer); - const jsonLen = view.getUint32(outPtr, true); - const jsonBytes = new Uint8Array(exports.memory.buffer, outPtr + 4, jsonLen); - const text = new TextDecoder().decode(jsonBytes); - exports.mq_dealloc(outPtr, 4 + jsonLen); - return JSON.parse(text); -} - -function writeUtf8(exports, text) { - const encoded = new TextEncoder().encode(text); - const ptr = exports.mq_alloc(encoded.length || 1); - if (!ptr) throw new Error("mq_alloc failed"); - new Uint8Array(exports.memory.buffer, ptr, encoded.length).set(encoded); - return { ptr, len: encoded.length }; -} - -export function runSource(exports, source) { - const { ptr, len } = writeUtf8(exports, source); - const outPtr = exports.mq_run(ptr, len); - exports.mq_dealloc(ptr, len || 1); - return decodePacked(exports, outPtr); -} - -export function boot(exports, source) { - const { ptr, len } = writeUtf8(exports, source); - const outPtr = exports.mq_boot(ptr, len); - exports.mq_dealloc(ptr, len || 1); - return decodePacked(exports, outPtr); -} - -export function call(exports, name, argsObj = {}) { - const n = writeUtf8(exports, name); - const a = writeUtf8(exports, JSON.stringify(argsObj ?? {})); - const outPtr = exports.mq_call(n.ptr, n.len, a.ptr, a.len); - exports.mq_dealloc(n.ptr, n.len || 1); - exports.mq_dealloc(a.ptr, a.len || 1); - return decodePacked(exports, outPtr); -} - -export async function loadWasm(url = "./marqdo_wasm.wasm") { - const res = await fetch(url); - if (!res.ok) { - throw new Error( - `failed to fetch ${url} (${res.status}). Build with: marqdo wasm build -o .`, - ); - } - const { instance } = await WebAssembly.instantiateStreaming(res, {}); - return instance.exports; -} - -function isPlainObject(v) { - return v != null && typeof v === "object" && !Array.isArray(v); -} - -function asSelList(v) { - if (v == null) return []; - if (Array.isArray(v)) return v.map(String); - return [String(v)]; -} - -/** Normalize mount options from plain object or DOM dataset. */ -export function normalizeMountOptions(raw = {}) { - const o = raw && typeof raw === "object" ? raw : {}; - const dataset = o.dataset || {}; - const wasmUrl = - o.wasmUrl || o.wasm || dataset.mqWasm || dataset.wasm || "./marqdo_wasm.wasm"; - const sourceUrl = - o.sourceUrl || o.source_url || dataset.mqSourceUrl || dataset.sourceUrl || ""; - let source = o.source != null ? o.source : dataset.mqSource || ""; - if (!source && typeof o.sourceInline === "string") source = o.sourceInline; - const playground = o.playground || dataset.mqPlayground || dataset.playground || ""; - const ready = o.ready || o.readySel || dataset.mqReady || ""; - const enable = o.enable || dataset.mqEnable || ""; - const noBoot = - o.noBoot === true || dataset.mqNoBoot === "1" || dataset.mqNoBoot === "true"; - return { - wasmUrl: String(wasmUrl), - sourceUrl: sourceUrl ? String(sourceUrl) : "", - source: source ? String(source) : "", - playground: playground ? String(playground) : "", - ready: ready ? String(ready) : "", - enable: enable ? String(enable) : "", - noBoot, - onError: typeof o.onError === "function" ? o.onError : null, - }; -} - -export function collectMountConfigs(doc = typeof document !== "undefined" ? document : null) { - if (!doc) return []; - const out = []; - const bootEl = doc.getElementById("marqdo-boot"); - if (bootEl) { - try { - out.push(normalizeMountOptions(JSON.parse(bootEl.textContent || "{}"))); - } catch (e) { - console.error("marqdo-boot JSON:", e); - } - } - const scripts = doc.querySelectorAll( - "script[data-mq-source-url], script[data-mq-source], script[data-mq-playground], script[data-mq-wasm]", - ); - for (const el of scripts) { - if (el.dataset.mqNoBoot === "1" || el.dataset.mqNoBoot === "true") continue; - const hasWork = - el.dataset.mqSourceUrl || el.dataset.mqSource || el.dataset.mqPlayground; - if (!hasWork) continue; - out.push( - normalizeMountOptions({ - dataset: el.dataset, - wasmUrl: el.dataset.mqWasm, - sourceUrl: el.dataset.mqSourceUrl, - source: el.dataset.mqSource, - playground: el.dataset.mqPlayground, - ready: el.dataset.mqReady, - enable: el.dataset.mqEnable, - }), - ); - } - return out; -} - -export function eventArgsFromDom(ev, valueFromSel) { - const t = ev && ev.target; - const args = { event: ev && ev.type ? ev.type : "click" }; - if (t && typeof t === "object") { - if ("value" in t && t.value != null && t.type !== "file") args.value = String(t.value); - if ("checked" in t) args.checked = !!t.checked; - if (t.id) args.id = String(t.id); - if (t.getAttribute) { - const did = t.getAttribute("data-id"); - if (did != null) args.data_id = did; - const drag = t.getAttribute("data-drag"); - if (drag != null) args.drag = drag; - } - if (typeof t.textContent === "string" && !("value" in t)) { - args.text = t.textContent; - } - if (ev.key != null) args.key = String(ev.key); - if (ev.code != null) args.code = String(ev.code); - if (t.files && t.files.length) { - const f = t.files[0]; - args.file_name = f.name; - args.file_size = f.size; - args.file_type = f.type || ""; - args.file_count = t.files.length; - } - } - if (ev && ev.type === "popstate") { - args.url = typeof location !== "undefined" ? location.href : ""; - args.path = typeof location !== "undefined" ? location.pathname + location.search : ""; - args.state = ev.state; - } - if (ev && ev.dataTransfer) { - try { - const txt = ev.dataTransfer.getData("text") || ev.dataTransfer.getData("text/plain"); - if (txt) args.drop_text = txt; - } catch (_) { - /* ignore */ - } - } - if (valueFromSel && typeof document !== "undefined") { - const src = document.querySelector(valueFromSel); - if (src) { - if ("value" in src && src.type !== "file") args.value = String(src.value); - else args.value = src.textContent != null ? String(src.textContent) : ""; - } - } - if (ev && ev.type === "submit" && t) { - const form = typeof t.closest === "function" ? t.closest("form") : t; - if (form && typeof FormData !== "undefined") { - try { - ev.preventDefault(); - } catch (_) { - /* ignore */ - } - const fields = {}; - for (const [k, v] of new FormData(form)) fields[k] = String(v); - args.fields = fields; - } - } - if (ev && (ev.type === "scroll" || ev.type === "resize")) { - try { - const doc = typeof document !== "undefined" ? document.documentElement : null; - const body = typeof document !== "undefined" ? document.body : null; - const scrollTop = (doc && (doc.scrollTop || 0)) || (body && body.scrollTop) || 0; - const height = doc ? (doc.scrollHeight - doc.clientHeight) || 1 : 1; - const ratio = Math.max(0, Math.min(1, scrollTop / height)); - args.scroll_top = scrollTop; - args.scroll_max = height; - args.scroll_ratio = ratio; - } catch (_) { - /* ignore */ - } - } - return args; -} - -function applyStyle(el, styleVal) { - if (typeof styleVal === "string") { - el.setAttribute("style", styleVal); - return; - } - if (isPlainObject(styleVal)) { - for (const [k, v] of Object.entries(styleVal)) { - if (v === null || v === false) el.style.removeProperty(k); - else el.style.setProperty(k.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase()), String(v)); - } - } -} - -export function renderListItems(spec) { - const tag = String(spec.tag || "li"); - const items = Array.isArray(spec.items) ? spec.items : []; - return items - .map((it) => { - if (it == null) return ""; - if (typeof it === "string" || typeof it === "number") { - return `<${tag}>${escapeHtml(String(it))}`; - } - if (!isPlainObject(it)) return ""; - const text = it.text != null ? String(it.text) : it.html != null ? null : ""; - const cls = it.class != null ? ` class="${escapeAttr(String(it.class))}"` : ""; - let attrs = ""; - if (isPlainObject(it.attrs)) { - for (const [k, v] of Object.entries(it.attrs)) { - if (v === null || v === false) continue; - attrs += ` ${escapeAttr(k)}="${escapeAttr(String(v))}"`; - } - } - const inner = it.html != null ? String(it.html) : escapeHtml(text ?? ""); - return `<${tag}${cls}${attrs}>${inner}`; - }) - .join(""); -} - -function escapeHtml(s) { - return s - .replace(/&/g, "&") - .replace(//g, ">") - .replace(/"/g, """); -} - -function escapeAttr(s) { - return escapeHtml(s).replace(/'/g, "'"); -} - -function qsAll(sel) { - if (typeof document === "undefined") return []; - try { - return [...document.querySelectorAll(sel)]; - } catch (_) { - return []; - } -} - -function qsOne(sel) { - const all = qsAll(sel); - return all[0] || null; -} - -/** Sync DOM patches (E1/E2/E3 navigate is sync too). */ -export function applyDomPatch(value) { - if (!value || typeof value !== "object") return; - if (typeof document === "undefined") return; - - const setText = value.set_text || value.setText; - if (isPlainObject(setText)) { - for (const [sel, text] of Object.entries(setText)) { - for (const el of qsAll(sel)) el.textContent = String(text); - } - } - - const setValue = value.set_value || value.setValue; - if (isPlainObject(setValue)) { - for (const [sel, v] of Object.entries(setValue)) { - for (const el of qsAll(sel)) { - if ("value" in el) el.value = String(v); - } - } - } - - const setAttr = value.set_attr || value.setAttr; - if (isPlainObject(setAttr)) { - for (const [sel, attrs] of Object.entries(setAttr)) { - if (!isPlainObject(attrs)) continue; - for (const el of qsAll(sel)) { - for (const [name, raw] of Object.entries(attrs)) { - if (raw === null || raw === false) el.removeAttribute(name); - else el.setAttribute(name, String(raw)); - } - } - } - } - - const setClass = value.set_class || value.setClass; - if (isPlainObject(setClass)) { - for (const [sel, cls] of Object.entries(setClass)) { - for (const el of qsAll(sel)) el.className = String(cls); - } - } - - const addClass = value.add_class || value.addClass; - if (isPlainObject(addClass)) { - for (const [sel, cls] of Object.entries(addClass)) { - const names = String(cls).split(/\s+/).filter(Boolean); - for (const el of qsAll(sel)) for (const c of names) el.classList.add(c); - } - } - - const removeClass = value.remove_class || value.removeClass; - if (isPlainObject(removeClass)) { - for (const [sel, cls] of Object.entries(removeClass)) { - const names = String(cls).split(/\s+/).filter(Boolean); - for (const el of qsAll(sel)) for (const c of names) el.classList.remove(c); - } - } - - const toggleClass = value.toggle_class || value.toggleClass; - if (isPlainObject(toggleClass)) { - for (const [sel, cls] of Object.entries(toggleClass)) { - for (const el of qsAll(sel)) { - if (cls) el.classList.toggle(String(cls)); - } - } - } - - const setStyle = value.set_style || value.setStyle; - if (isPlainObject(setStyle)) { - for (const [sel, st] of Object.entries(setStyle)) { - for (const el of qsAll(sel)) applyStyle(el, st); - } - } - - for (const sel of asSelList(value.focus)) { - const el = qsOne(sel); - if (el && el.focus) el.focus(); - } - for (const sel of asSelList(value.blur)) { - const el = qsOne(sel); - if (el && el.blur) el.blur(); - } - for (const sel of asSelList(value.scroll_into || value.scrollInto)) { - const el = qsOne(sel); - if (el && el.scrollIntoView) el.scrollIntoView({ block: "nearest", behavior: "smooth" }); - } - - const setHtml = value.set_html || value.setHtml; - if (isPlainObject(setHtml)) { - for (const [sel, html] of Object.entries(setHtml)) { - for (const el of qsAll(sel)) el.innerHTML = String(html); - } - } - - const appendHtml = value.append_html || value.appendHtml; - if (isPlainObject(appendHtml)) { - for (const [sel, html] of Object.entries(appendHtml)) { - for (const el of qsAll(sel)) el.insertAdjacentHTML("beforeend", String(html)); - } - } - - const replaceChildren = value.replace_children || value.replaceChildren; - if (isPlainObject(replaceChildren)) { - for (const [sel, html] of Object.entries(replaceChildren)) { - for (const el of qsAll(sel)) el.innerHTML = String(html); - } - } - - const renderList = value.render_list || value.renderList; - if (isPlainObject(renderList)) { - for (const [sel, spec] of Object.entries(renderList)) { - if (!isPlainObject(spec)) continue; - const html = renderListItems(spec); - for (const el of qsAll(sel)) el.innerHTML = html; - } - } - - const removeSel = value.remove || value.remove_nodes || value.removeNodes; - if (removeSel) { - for (const sel of asSelList(removeSel)) { - for (const el of qsAll(sel)) el.remove(); - } - } - - const nav = value.navigate; - if (isPlainObject(nav) && nav.url != null && typeof history !== "undefined") { - const url = String(nav.url); - if (nav.replace) history.replaceState(nav.state ?? null, "", url); - else history.pushState(nav.state ?? null, "", url); - } - - const clip = value.clipboard || value.copy; - if (clip != null && typeof navigator !== "undefined" && navigator.clipboard?.writeText) { - const text = isPlainObject(clip) ? String(clip.text ?? "") : String(clip); - navigator.clipboard.writeText(text).catch(() => {}); - } - - const dl = value.download; - if (isPlainObject(dl) && dl.body != null) { - const mime = String(dl.mime || "text/plain;charset=utf-8"); - const name = String(dl.filename || "download.txt"); - const blob = new Blob([String(dl.body)], { type: mime }); - const url = URL.createObjectURL(blob); - const a = document.createElement("a"); - a.href = url; - a.download = name; - a.click(); - URL.revokeObjectURL(url); - } - - const canvasSpec = value.canvas; - if (isPlainObject(canvasSpec) && canvasSpec.sel) { - runCanvasCommands(canvasSpec); - } - - const audioSpec = value.audio; - if (isPlainObject(audioSpec) && audioSpec.op) { - runAudioEffect(audioSpec); - } -} - -const intervalHandles = new Map(); -const wsHandles = new Map(); -const audioHandles = new Map(); -const observeHandles = new Map(); -let wsSeq = 0; -let observeSeq = 0; - -/** @param {{ sel: string, commands?: object[], clear?: boolean }} spec */ -export function runCanvasCommands(spec) { - if (typeof document === "undefined") return; - const el = qsOne(String(spec.sel)); - if (!el || typeof el.getContext !== "function") return; - const ctx = el.getContext("2d"); - if (!ctx) return; - if (spec.clear) ctx.clearRect(0, 0, el.width || 0, el.height || 0); - const cmds = Array.isArray(spec.commands) - ? spec.commands - : isPlainObject(spec.commands) - ? Object.keys(spec.commands) - .sort() - .map((k) => spec.commands[k]) - : []; - for (const raw of cmds) { - if (!isPlainObject(raw)) continue; - const op = String(raw.op || raw.cmd || "").toLowerCase(); - try { - if (op === "clear" || op === "clearrect") { - ctx.clearRect( - Number(raw.x) || 0, - Number(raw.y) || 0, - Number(raw.w ?? raw.width ?? el.width) || 0, - Number(raw.h ?? raw.height ?? el.height) || 0, - ); - } else if (op === "fillstyle") { - ctx.fillStyle = String(raw.value ?? raw.color ?? "#000"); - } else if (op === "strokestyle") { - ctx.strokeStyle = String(raw.value ?? raw.color ?? "#000"); - } else if (op === "linewidth") { - ctx.lineWidth = Number(raw.value ?? raw.width) || 1; - } else if (op === "font") { - ctx.font = String(raw.value || "16px sans-serif"); - } else if (op === "fillrect") { - if (raw.fill != null) ctx.fillStyle = String(raw.fill); - ctx.fillRect(Number(raw.x) || 0, Number(raw.y) || 0, Number(raw.w ?? raw.width) || 0, Number(raw.h ?? raw.height) || 0); - } else if (op === "strokerect") { - if (raw.stroke != null) ctx.strokeStyle = String(raw.stroke); - ctx.strokeRect(Number(raw.x) || 0, Number(raw.y) || 0, Number(raw.w ?? raw.width) || 0, Number(raw.h ?? raw.height) || 0); - } else if (op === "beginpath") { - ctx.beginPath(); - } else if (op === "closepath") { - ctx.closePath(); - } else if (op === "moveto") { - ctx.moveTo(Number(raw.x) || 0, Number(raw.y) || 0); - } else if (op === "lineto") { - ctx.lineTo(Number(raw.x) || 0, Number(raw.y) || 0); - } else if (op === "arc") { - ctx.arc( - Number(raw.x) || 0, - Number(raw.y) || 0, - Number(raw.r ?? raw.radius) || 0, - Number(raw.start ?? 0), - Number(raw.end ?? Math.PI * 2), - !!raw.ccw, - ); - } else if (op === "stroke") { - if (raw.stroke != null) ctx.strokeStyle = String(raw.stroke); - ctx.stroke(); - } else if (op === "fill") { - if (raw.fill != null) ctx.fillStyle = String(raw.fill); - ctx.fill(); - } else if (op === "filltext") { - if (raw.fill != null) ctx.fillStyle = String(raw.fill); - ctx.fillText(String(raw.text ?? ""), Number(raw.x) || 0, Number(raw.y) || 0); - } else if (op === "drawimage" && raw.src) { - const img = new Image(); - img.src = String(raw.src); - // sync only if already loaded; else fire-and-forget draw on load - const draw = () => { - ctx.drawImage( - img, - Number(raw.x) || 0, - Number(raw.y) || 0, - Number(raw.w ?? raw.width ?? img.width) || img.width, - Number(raw.h ?? raw.height ?? img.height) || img.height, - ); - }; - if (img.complete) draw(); - else img.onload = draw; - } - } catch (_) { - /* skip bad cmd */ - } - } -} - -function runAudioEffect(spec) { - const op = String(spec.op || "").toLowerCase(); - const id = String(spec.id || spec.sel || "default"); - try { - if (op === "play") { - // Optional beep via Web Audio (no external file). - if (spec.freq != null || spec.frequency != null || String(spec.src || "") === "beep") { - const AC = window.AudioContext || window.webkitAudioContext; - if (!AC) return; - let ctx = audioHandles.get(`${id}:ctx`); - if (!ctx) { - ctx = new AC(); - audioHandles.set(`${id}:ctx`, ctx); - } - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = String(spec.wave || "sine"); - osc.frequency.value = Number(spec.freq ?? spec.frequency ?? 440); - const vol = spec.volume != null ? Math.min(1, Math.max(0, Number(spec.volume))) : 0.15; - gain.gain.value = vol; - osc.connect(gain); - gain.connect(ctx.destination); - const dur = Number(spec.ms ?? spec.duration ?? 280) / 1000; - osc.start(); - gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + Math.max(0.05, dur)); - osc.stop(ctx.currentTime + Math.max(0.05, dur) + 0.02); - return; - } - let audio = audioHandles.get(id); - if (spec.sel) { - const el = qsOne(String(spec.sel)); - if (el && el.tagName === "AUDIO") audio = el; - } - if (!audio) { - audio = new Audio(spec.src != null ? String(spec.src) : undefined); - audioHandles.set(id, audio); - } else if (spec.src != null) { - audio.src = String(spec.src); - } - if (spec.volume != null) audio.volume = Math.min(1, Math.max(0, Number(spec.volume))); - if (spec.loop != null) audio.loop = !!spec.loop; - const p = audio.play(); - if (p && p.catch) p.catch(() => {}); - return; - } - const audio = spec.sel ? qsOne(String(spec.sel)) : audioHandles.get(id); - if (!audio) return; - if (op === "pause") audio.pause(); - else if (op === "stop") { - audio.pause(); - try { - audio.currentTime = 0; - } catch (_) { - /* ignore */ - } - } - } catch (_) { - /* ignore */ - } -} - -/** - * Run sync DOM patches then schedule async effects. - */ -export function applyEffects(exports, value, { onError } = {}) { - applyDomPatch(value); - if (!value || typeof value !== "object") return Promise.resolve(); - - const tasks = []; - - const fetchSpec = value.fetch; - if (fetchSpec && typeof fetchSpec === "object" && fetchSpec.url && fetchSpec.then) { - tasks.push(runFetchEffect(exports, fetchSpec, onError)); - } - - const fetchAll = value.fetch_all || value.fetchAll; - if (fetchAll && typeof fetchAll === "object" && fetchAll.then) { - tasks.push(runFetchAllEffect(exports, fetchAll, onError)); - } - - const afterSpec = value.after; - if (afterSpec && typeof afterSpec === "object" && afterSpec.then) { - tasks.push(runAfterEffect(exports, afterSpec, onError)); - } - - const intervalSpec = value.interval; - if (intervalSpec && typeof intervalSpec === "object" && intervalSpec.then) { - runIntervalEffect(exports, intervalSpec, onError); - } - - const clearIv = value.clear_interval || value.clearInterval; - if (clearIv && typeof clearIv === "object") { - const id = String(clearIv.id || "default"); - const h = intervalHandles.get(id); - if (h != null) { - clearInterval(h); - intervalHandles.delete(id); - } - } - - const storageSpec = value.storage; - if (storageSpec && typeof storageSpec === "object" && storageSpec.op) { - tasks.push(runStorageEffect(exports, storageSpec, onError)); - } - - const wsSpec = value.ws; - if (wsSpec && typeof wsSpec === "object" && wsSpec.op) { - tasks.push(runWsEffect(exports, wsSpec, onError)); - } - - const readFile = value.read_file || value.readFile; - if (readFile && typeof readFile === "object" && readFile.then) { - tasks.push(runReadFileEffect(exports, readFile, onError)); - } - - const observe = value.observe; - if (observe) { - const specs = Array.isArray(observe) - ? observe - : observe && typeof observe === "object" && observe.then - ? [observe] - : []; - for (const spec of specs) runObserveEffect(exports, spec, onError); - } - - const unobserve = value.unobserve; - if (unobserve) { - const specs = Array.isArray(unobserve) - ? unobserve - : unobserve && typeof unobserve === "object" - ? [unobserve] - : []; - for (const spec of specs) { - const id = String(spec.id || ""); - const h = observeHandles.get(id); - if (h) { - try { - h.disconnect(); - } catch (_) { - /* ignore */ - } - observeHandles.delete(id); - } - } - } - - return Promise.all(tasks); -} - -async function runReadFileEffect(exports, spec, onError) { - const thenFn = spec.then; - const sel = String(spec.sel || ""); - const as = String(spec.as || "text").toLowerCase(); - const input = qsOne(sel); - if (!input || !input.files || !input.files.length) { - const result = call(exports, thenFn, { ok: false, error: "no file", sel }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - return; - } - const file = input.files[Number(spec.index) || 0]; - try { - let body = ""; - let data_url = ""; - if (as === "data_url" || as === "dataurl") { - data_url = await new Promise((resolve, reject) => { - const r = new FileReader(); - r.onload = () => resolve(String(r.result || "")); - r.onerror = () => reject(r.error || new Error("read failed")); - r.readAsDataURL(file); - }); - } else { - body = await file.text(); - } - const result = call(exports, thenFn, { - ok: true, - name: file.name, - size: file.size, - type: file.type || "", - body, - data_url, - as, - }); - if (!result.ok) { - if (onError) onError(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - } catch (e) { - try { - const result = call(exports, thenFn, { ok: false, error: String(e), name: file.name }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - else if (onError) onError(result.error); - } catch (e2) { - if (onError) onError(String(e2)); - } - } -} - -function runObserveEffect(exports, spec, onError) { - const kind = String(spec.kind || spec.type || "intersect").toLowerCase(); - const sel = String(spec.sel || ""); - const thenFn = spec.then; - const baseId = String(spec.id || `obs${++observeSeq}`); - const nodes = qsAll(sel); - if (!nodes.length || (!thenFn && !spec.add_class)) return; - - nodes.forEach((el, idx) => { - const id = nodes.length === 1 ? baseId : `${baseId}_${idx}`; - const prev = observeHandles.get(id); - if (prev) { - try { - prev.disconnect(); - } catch (_) { - /* ignore */ - } - } - - const fire = (payload) => { - try { - const result = call(exports, thenFn, payload); - if (!result.ok) { - if (onError) onError(result.error); - return; - } - applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - }; - - if (kind === "resize" && typeof ResizeObserver !== "undefined") { - const ro = new ResizeObserver((entries) => { - const en = entries[0]; - const cr = en?.contentRect; - fire({ - ok: true, - kind: "resize", - id, - width: cr ? cr.width : 0, - height: cr ? cr.height : 0, - }); - }); - ro.observe(el); - observeHandles.set(id, ro); - return; - } - - if (typeof IntersectionObserver !== "undefined") { - const opts = { threshold: spec.threshold != null ? Number(spec.threshold) : 0.1 }; - if (spec.rootMargin != null) opts.rootMargin = String(spec.rootMargin); - const io = new IntersectionObserver( - (entries) => { - const en = entries[0]; - if (!en) return; - if (en.isIntersecting && spec.add_class) { - for (const c of String(spec.add_class).split(/\s+/).filter(Boolean)) { - el.classList.add(c); - } - } - if (thenFn) { - fire({ - ok: true, - kind: "intersect", - id, - intersecting: !!en.isIntersecting, - ratio: en.intersectionRatio, - target_id: el.id || "", - }); - } - if (spec.once && en.isIntersecting) { - try { - io.disconnect(); - } catch (_) { - /* ignore */ - } - observeHandles.delete(id); - } - }, - opts, - ); - io.observe(el); - observeHandles.set(id, io); - } - }); -} - -function buildFetchInit(spec) { - const method = (spec.method || "GET").toUpperCase(); - const init = { method }; - if (spec.headers && typeof spec.headers === "object") init.headers = { ...spec.headers }; - if (spec.fields && typeof spec.fields === "object" && typeof FormData !== "undefined") { - const fd = new FormData(); - for (const [k, v] of Object.entries(spec.fields)) fd.append(k, String(v)); - init.body = fd; - } else if (spec.body != null && method !== "GET" && method !== "HEAD") { - init.body = typeof spec.body === "string" ? spec.body : JSON.stringify(spec.body); - } - return init; -} - -async function runFetchEffect(exports, spec, onError) { - const thenFn = spec.then; - try { - const res = await fetch(String(spec.url), buildFetchInit(spec)); - const body = await res.text(); - const result = call(exports, thenFn, { ok: res.ok, status: res.status, body }); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - if (result.stdout) console.log(result.stdout); - } catch (e) { - try { - const result = call(exports, thenFn, { - ok: false, - status: 0, - body: "", - error: String(e), - }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - else if (onError) onError(result.error); - } catch (e2) { - if (onError) onError(String(e2)); - else console.error(e2); - } - } -} - -async function runFetchAllEffect(exports, spec, onError) { - const thenFn = spec.then; - const reqs = Array.isArray(spec.requests) - ? spec.requests - : isPlainObject(spec.requests) - ? Object.keys(spec.requests) - .sort() - .map((k) => spec.requests[k]) - .filter((r) => r && typeof r === "object") - : []; - try { - const results = await Promise.all( - reqs.map(async (r) => { - try { - const res = await fetch(String(r.url), buildFetchInit(r)); - const body = await res.text(); - return { ok: res.ok, status: res.status, body, url: String(r.url) }; - } catch (e) { - return { ok: false, status: 0, body: "", error: String(e), url: String(r.url || "") }; - } - }), - ); - const result = call(exports, thenFn, { ok: true, results }); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - } -} - -function runAfterEffect(exports, spec, onError) { - const ms = Math.max(0, Number(spec.ms) || 0); - const thenFn = spec.then; - return new Promise((resolve) => { - setTimeout(() => { - try { - const result = call(exports, thenFn, { ok: true }); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - resolve(); - return; - } - Promise.resolve(applyEffects(exports, result.value, { onError })).then(resolve); - if (result.stdout) console.log(result.stdout); - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - resolve(); - } - }, ms); - }); -} - -function runIntervalEffect(exports, spec, onError) { - const ms = Math.max(1, Number(spec.ms) || 1000); - const thenFn = spec.then; - const id = String(spec.id || "default"); - if (intervalHandles.has(id)) { - clearInterval(intervalHandles.get(id)); - intervalHandles.delete(id); - } - const handle = setInterval(() => { - try { - const result = call(exports, thenFn, { ok: true, id }); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - return; - } - applyEffects(exports, result.value, { onError }); - if (result.stdout) console.log(result.stdout); - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - } - }, ms); - intervalHandles.set(id, handle); -} - -const memoryKV = new Map(); - -function storageStore(scope) { - if (scope === "cookie") return null; - if (scope === "memory" || scope === "mem" || scope === "内存") { - return { - getItem(key) { - return memoryKV.has(key) ? memoryKV.get(key) : null; - }, - setItem(key, value) { - memoryKV.set(key, String(value)); - }, - removeItem(key) { - memoryKV.delete(key); - }, - }; - } - if (typeof localStorage === "undefined") return null; - return scope === "session" ? sessionStorage : localStorage; -} - -function cookieGet(key) { - if (typeof document === "undefined") return null; - const prefix = encodeURIComponent(key) + "="; - for (const part of document.cookie.split(";")) { - const s = part.trim(); - if (s.startsWith(prefix)) return decodeURIComponent(s.slice(prefix.length)); - } - return null; -} - -function cookieSet(key, value, days) { - if (typeof document === "undefined") return; - let extra = "; path=/"; - if (days != null && Number(days) > 0) { - const d = new Date(); - d.setTime(d.getTime() + Number(days) * 864e5); - extra += "; expires=" + d.toUTCString(); - } - document.cookie = encodeURIComponent(key) + "=" + encodeURIComponent(value) + extra; -} - -function cookieRemove(key) { - if (typeof document === "undefined") return; - document.cookie = encodeURIComponent(key) + "=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"; -} - -async function runStorageEffect(exports, spec, onError) { - const op = String(spec.op || "").toLowerCase(); - const key = String(spec.key || ""); - const scope = String(spec.scope || "local"); - try { - if (scope === "cookie") { - if (op === "set") { - cookieSet(key, spec.value != null ? String(spec.value) : "", spec.days); - } else if (op === "remove" || op === "delete") { - cookieRemove(key); - } else if (op === "get") { - const value = cookieGet(key); - if (spec.then) { - const result = call(exports, spec.then, { - ok: true, - op, - key, - value: value == null ? "" : value, - found: value != null, - scope, - }); - if (!result.ok) { - if (onError) onError(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - } - return; - } - if (spec.then && op !== "get") { - const result = call(exports, spec.then, { ok: true, op, key, scope }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - } - return; - } - - const store = storageStore(scope); - if (!store) { - if (onError) onError("storage unavailable"); - return; - } - if (op === "set") { - store.setItem(key, spec.value != null ? String(spec.value) : ""); - if (spec.then) { - const result = call(exports, spec.then, { ok: true, op, key, scope }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - } - return; - } - if (op === "remove" || op === "delete") { - store.removeItem(key); - if (spec.then) { - const result = call(exports, spec.then, { ok: true, op, key, scope }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - } - return; - } - if (op === "get") { - const value = store.getItem(key); - if (spec.then) { - const result = call(exports, spec.then, { - ok: true, - op, - key, - value: value == null ? "" : value, - found: value != null, - scope, - }); - if (!result.ok) { - if (onError) onError(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - } - } - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - } -} - -function runWsEffect(exports, spec, onError) { - const op = String(spec.op || "").toLowerCase(); - return new Promise((resolve) => { - try { - if (op === "open") { - if (typeof WebSocket === "undefined") { - if (onError) onError("WebSocket unavailable"); - resolve(); - return; - } - const id = String(spec.id || `ws${++wsSeq}`); - const sock = new WebSocket(String(spec.url)); - wsHandles.set(id, sock); - sock.addEventListener("open", () => { - if (spec.then_open || spec.thenOpen) { - try { - const result = call(exports, spec.then_open || spec.thenOpen, { ok: true, id }); - if (result.ok) applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - } - resolve(); - }); - sock.addEventListener("message", (ev) => { - const thenMsg = spec.then_message || spec.thenMessage; - if (!thenMsg) return; - try { - const result = call(exports, thenMsg, { - ok: true, - id, - data: typeof ev.data === "string" ? ev.data : String(ev.data), - }); - if (result.ok) applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - }); - sock.addEventListener("close", () => { - wsHandles.delete(id); - const thenClose = spec.then_close || spec.thenClose; - if (thenClose) { - try { - const result = call(exports, thenClose, { ok: true, id }); - if (result.ok) applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - } - }); - sock.addEventListener("error", () => { - const thenErr = spec.then_error || spec.thenError; - if (thenErr) { - try { - const result = call(exports, thenErr, { ok: false, id, error: "ws error" }); - if (result.ok) applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - } - }); - return; - } - if (op === "send") { - const id = String(spec.id || [...wsHandles.keys()][0] || ""); - const sock = wsHandles.get(id); - if (sock && sock.readyState === WebSocket.OPEN) { - sock.send(spec.data != null ? String(spec.data) : ""); - } else if (onError) onError(`ws send: no open socket ${id}`); - resolve(); - return; - } - if (op === "close") { - const id = String(spec.id || [...wsHandles.keys()][0] || ""); - const sock = wsHandles.get(id); - if (sock) sock.close(); - wsHandles.delete(id); - resolve(); - return; - } - resolve(); - } catch (e) { - if (onError) onError(String(e)); - resolve(); - } - }); -} - -function bindTarget(sel) { - if (sel === "window" || sel === "@window") return typeof window !== "undefined" ? window : null; - if (sel === "document" || sel === "@document") - return typeof document !== "undefined" ? document : null; - return null; -} - -/** - * Wire events from `# main` return value (list or `{ wire: [...] }`). - */ -export function wireEvents(exports, bootValue, { onError } = {}) { - let rows = []; - if (Array.isArray(bootValue)) rows = bootValue; - else if (bootValue && Array.isArray(bootValue.wire)) rows = bootValue.wire; - - for (const row of rows) { - const sel = row["选择器"] || row.selector || row.sel; - const ev = row["事件"] || row.event || "click"; - const fn = row["调用"] || row.call || row.fn; - const valueFrom = - row["值选择器"] || row.value_from || row.valueFrom || row.from || ""; - const delegate = - row["委托"] || row.delegate || row.delegation || ""; - if (!sel || !fn) continue; - - const special = bindTarget(sel); - const roots = special - ? [special] - : typeof document !== "undefined" - ? [...document.querySelectorAll(sel)] - : []; - - roots.forEach((node) => { - node.addEventListener(ev, (domEv) => { - try { - if (delegate) { - const hit = - typeof domEv.target?.closest === "function" - ? domEv.target.closest(delegate) - : null; - if (!hit || (node.contains && !node.contains(hit))) return; - } - // Drag/drop hosts need preventDefault on dragover/drop; dragstart can set payload. - if ( - ev === "dragover" || - ev === "dragenter" || - ev === "drop" || - ev === "dragstart" - ) { - try { - domEv.preventDefault(); - } catch (_) { - /* ignore */ - } - } - if (ev === "dragstart" && domEv.dataTransfer) { - try { - const payload = - (domEv.target && - typeof domEv.target.getAttribute === "function" && - domEv.target.getAttribute("data-drag")) || - (typeof domEv.target?.textContent === "string" - ? domEv.target.textContent.trim() - : "") || - ""; - if (payload) { - domEv.dataTransfer.setData("text/plain", payload); - domEv.dataTransfer.setData("text", payload); - domEv.dataTransfer.effectAllowed = "copyMove"; - } - } catch (_) { - /* ignore */ - } - } - if ( - ev === "click" && - typeof domEv.target?.closest === "function" && - domEv.target.closest("a[href]") - ) { - try { - domEv.preventDefault(); - } catch (_) { - /* ignore */ - } - } - const args = eventArgsFromDom(domEv, valueFrom); - if (delegate && domEv.target) { - const hit = domEv.target.closest?.(delegate); - if (hit?.getAttribute) { - const did = hit.getAttribute("data-id"); - if (did != null) args.data_id = did; - if (hit.id) args.id = hit.id; - const drag = hit.getAttribute("data-drag"); - if (drag != null) args.drag = drag; - } - } - const result = call(exports, fn, args); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - return; - } - applyEffects(exports, result.value, { onError }); - if (result.stdout) console.log(result.stdout); - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - } - }); - }); - } - return rows.length; -} - -function markReady(opts, message) { - if (opts.ready && typeof document !== "undefined") { - const el = document.querySelector(opts.ready); - if (el) { - el.classList?.remove?.("err"); - el.textContent = message; - } - } - if (opts.enable && typeof document !== "undefined") { - for (const sel of String(opts.enable).split(",")) { - const s = sel.trim(); - if (!s) continue; - document.querySelectorAll(s).forEach((n) => { - n.disabled = false; - n.removeAttribute("disabled"); - }); - } - } -} - -function markError(opts, err) { - const msg = String(err); - if (opts.onError) opts.onError(msg); - if (opts.ready && typeof document !== "undefined") { - const el = document.querySelector(opts.ready); - if (el) { - el.classList?.add?.("err"); - el.textContent = msg; - } - } else { - console.error(msg); - } -} - -function wirePlayground(exports, playgroundSpec, { onError } = {}) { - const parts = String(playgroundSpec) - .split(",") - .map((s) => s.trim()) - .filter(Boolean); - const sourceSel = parts[0] || "#src"; - const runSel = parts[1] || "#run"; - const outSel = parts[2] || "#out"; - const runBtn = document.querySelector(runSel); - const src = document.querySelector(sourceSel); - const out = document.querySelector(outSel); - if (!runBtn || !src) return 0; - runBtn.disabled = false; - runBtn.removeAttribute("disabled"); - runBtn.addEventListener("click", () => { - try { - const result = runSource(exports, src.value || ""); - if (out) { - out.classList?.toggle?.("err", !result.ok); - out.textContent = result.ok - ? (result.stdout || "(empty stdout)") + - (result.value != null && result.value !== "None" - ? `\n[return] ${typeof result.value === "string" ? result.value : JSON.stringify(result.value)}` - : "") - : result.error || "error"; - } - } catch (e) { - if (onError) onError(String(e)); - else if (out) { - out.classList?.add?.("err"); - out.textContent = String(e); - } - } - }); - return 1; -} - -export async function mount(rawOpts = {}) { - const opts = normalizeMountOptions(rawOpts); - const onError = (err) => markError(opts, err); - - let exports; - try { - exports = await loadWasm(opts.wasmUrl); - } catch (e) { - onError(e); - throw e; - } - - const ver = readCString(exports.memory, exports.mq_version()); - - if (opts.playground) { - const n = wirePlayground(exports, opts.playground, { onError }); - markReady(opts, `marqdo-wasm ${ver} · playground ready`); - return { exports, boot: null, wired: n }; - } - - let source = opts.source; - if (!source && opts.sourceUrl) { - const res = await fetch(opts.sourceUrl); - if (!res.ok) { - const err = `failed to load ${opts.sourceUrl} (${res.status})`; - onError(err); - throw new Error(err); - } - source = await res.text(); - } - if (!source) { - const err = "mount: need source, sourceUrl, or playground"; - onError(err); - throw new Error(err); - } - - const result = boot(exports, source); - if (!result.ok) { - onError(result.error || "boot failed"); - throw new Error(result.error || "boot failed"); - } - - if (result.value && !Array.isArray(result.value)) { - await applyEffects(exports, result.value, { onError }); - } - - const n = wireEvents(exports, result.value, { onError }); - const srcLabel = opts.sourceUrl || "(inline)"; - markReady(opts, `marqdo-wasm ${ver} · wired ${n} handler(s)\nsource: ${srcLabel}`); - return { exports, boot: result, wired: n }; -} - -export async function autoMount(doc) { - const configs = collectMountConfigs(doc); - const results = []; - for (const cfg of configs) { - if (cfg.noBoot) continue; - results.push(await mount(cfg)); - } - return results; -} - -const g = typeof globalThis !== "undefined" ? globalThis : undefined; -if (g && g.document) { - // Defer WASM boot until after first paint / load so LCP images are not - // contending with a ~1.6MB wasm download on the critical path. - const start = () => { - const run = () => { - autoMount(g.document).catch((e) => console.error("marqdo autoMount:", e)); - }; - const schedule = () => { - if (typeof g.requestIdleCallback === "function") { - g.requestIdleCallback(() => run(), { timeout: 1500 }); - } else { - g.setTimeout(run, 0); - } - }; - if (g.document.readyState === "complete") { - schedule(); - } else { - g.addEventListener("load", schedule, { once: true }); - } - }; - start(); -} diff --git a/examples/browser-media/README.md b/examples/browser-media/README.md deleted file mode 100644 index d707f3b..0000000 --- a/examples/browser-media/README.md +++ /dev/null @@ -1,20 +0,0 @@ -# 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)。 diff --git a/examples/browser-media/index.html b/examples/browser-media/index.html deleted file mode 100644 index f36f9b3..0000000 --- a/examples/browser-media/index.html +++ /dev/null @@ -1,98 +0,0 @@ - - - - - - Marqdo · browser-media (route F) - - - -

      Marqdo browser-media

      -

      路线 F:文件 / Canvas / Audio / Observer / 拖放 — 无作者业务 JS。

      - -
      -

      F1 文件

      - - - -
      -
      - -
      -

      F2 Canvas · F3 Audio

      - - - -
      - -
      -

      F4 Observer

      - - -

      idle

      -

      向下滚动可触发 Intersection;改窗口大小触发 Resize。

      -
      - -
      -

      F5 拖放

      -
      - alpha - beta - gamma -
      -
      拖到这里
      -
      - -
      beacon(滚到可见)
      - -
      loading…
      - - - diff --git a/examples/browser-media/marqdo-bridge.js b/examples/browser-media/marqdo-bridge.js deleted file mode 100644 index 631aa59..0000000 --- a/examples/browser-media/marqdo-bridge.js +++ /dev/null @@ -1,1382 +0,0 @@ -/** - * Canonical Marqdo browser bridge (routes C/D/E). Host glue only — not app logic. - * Authors write .mq.md only; this file may grow host mechanisms freely. - * - * ABI: mq_alloc, mq_dealloc, mq_run, mq_boot, mq_call, mq_version - * Effects: set_text, set_value, set_attr, set_class, toggle_class, set_style, - * focus, blur, scroll_into, set_html, replace_children, render_list, - * navigate, storage, ws, fetch, fetch_all, after, interval, clear_interval - */ - -export function readCString(memory, ptr) { - const bytes = new Uint8Array(memory.buffer); - let end = ptr; - while (bytes[end] !== 0) end += 1; - return new TextDecoder().decode(bytes.subarray(ptr, end)); -} - -function decodePacked(exports, outPtr) { - if (!outPtr) throw new Error("null wasm result pointer"); - const view = new DataView(exports.memory.buffer); - const jsonLen = view.getUint32(outPtr, true); - const jsonBytes = new Uint8Array(exports.memory.buffer, outPtr + 4, jsonLen); - const text = new TextDecoder().decode(jsonBytes); - exports.mq_dealloc(outPtr, 4 + jsonLen); - return JSON.parse(text); -} - -function writeUtf8(exports, text) { - const encoded = new TextEncoder().encode(text); - const ptr = exports.mq_alloc(encoded.length || 1); - if (!ptr) throw new Error("mq_alloc failed"); - new Uint8Array(exports.memory.buffer, ptr, encoded.length).set(encoded); - return { ptr, len: encoded.length }; -} - -export function runSource(exports, source) { - const { ptr, len } = writeUtf8(exports, source); - const outPtr = exports.mq_run(ptr, len); - exports.mq_dealloc(ptr, len || 1); - return decodePacked(exports, outPtr); -} - -export function boot(exports, source) { - const { ptr, len } = writeUtf8(exports, source); - const outPtr = exports.mq_boot(ptr, len); - exports.mq_dealloc(ptr, len || 1); - return decodePacked(exports, outPtr); -} - -export function call(exports, name, argsObj = {}) { - const n = writeUtf8(exports, name); - const a = writeUtf8(exports, JSON.stringify(argsObj ?? {})); - const outPtr = exports.mq_call(n.ptr, n.len, a.ptr, a.len); - exports.mq_dealloc(n.ptr, n.len || 1); - exports.mq_dealloc(a.ptr, a.len || 1); - return decodePacked(exports, outPtr); -} - -export async function loadWasm(url = "./marqdo_wasm.wasm") { - const res = await fetch(url); - if (!res.ok) { - throw new Error( - `failed to fetch ${url} (${res.status}). Build with: marqdo wasm build -o .`, - ); - } - const { instance } = await WebAssembly.instantiateStreaming(res, {}); - return instance.exports; -} - -function isPlainObject(v) { - return v != null && typeof v === "object" && !Array.isArray(v); -} - -function asSelList(v) { - if (v == null) return []; - if (Array.isArray(v)) return v.map(String); - return [String(v)]; -} - -/** Normalize mount options from plain object or DOM dataset. */ -export function normalizeMountOptions(raw = {}) { - const o = raw && typeof raw === "object" ? raw : {}; - const dataset = o.dataset || {}; - const wasmUrl = - o.wasmUrl || o.wasm || dataset.mqWasm || dataset.wasm || "./marqdo_wasm.wasm"; - const sourceUrl = - o.sourceUrl || o.source_url || dataset.mqSourceUrl || dataset.sourceUrl || ""; - let source = o.source != null ? o.source : dataset.mqSource || ""; - if (!source && typeof o.sourceInline === "string") source = o.sourceInline; - const playground = o.playground || dataset.mqPlayground || dataset.playground || ""; - const ready = o.ready || o.readySel || dataset.mqReady || ""; - const enable = o.enable || dataset.mqEnable || ""; - const noBoot = - o.noBoot === true || dataset.mqNoBoot === "1" || dataset.mqNoBoot === "true"; - return { - wasmUrl: String(wasmUrl), - sourceUrl: sourceUrl ? String(sourceUrl) : "", - source: source ? String(source) : "", - playground: playground ? String(playground) : "", - ready: ready ? String(ready) : "", - enable: enable ? String(enable) : "", - noBoot, - onError: typeof o.onError === "function" ? o.onError : null, - }; -} - -export function collectMountConfigs(doc = typeof document !== "undefined" ? document : null) { - if (!doc) return []; - const out = []; - const bootEl = doc.getElementById("marqdo-boot"); - if (bootEl) { - try { - out.push(normalizeMountOptions(JSON.parse(bootEl.textContent || "{}"))); - } catch (e) { - console.error("marqdo-boot JSON:", e); - } - } - const scripts = doc.querySelectorAll( - "script[data-mq-source-url], script[data-mq-source], script[data-mq-playground], script[data-mq-wasm]", - ); - for (const el of scripts) { - if (el.dataset.mqNoBoot === "1" || el.dataset.mqNoBoot === "true") continue; - const hasWork = - el.dataset.mqSourceUrl || el.dataset.mqSource || el.dataset.mqPlayground; - if (!hasWork) continue; - out.push( - normalizeMountOptions({ - dataset: el.dataset, - wasmUrl: el.dataset.mqWasm, - sourceUrl: el.dataset.mqSourceUrl, - source: el.dataset.mqSource, - playground: el.dataset.mqPlayground, - ready: el.dataset.mqReady, - enable: el.dataset.mqEnable, - }), - ); - } - return out; -} - -export function eventArgsFromDom(ev, valueFromSel) { - const t = ev && ev.target; - const args = { event: ev && ev.type ? ev.type : "click" }; - if (t && typeof t === "object") { - if ("value" in t && t.value != null && t.type !== "file") args.value = String(t.value); - if ("checked" in t) args.checked = !!t.checked; - if (t.id) args.id = String(t.id); - if (t.getAttribute) { - const did = t.getAttribute("data-id"); - if (did != null) args.data_id = did; - const drag = t.getAttribute("data-drag"); - if (drag != null) args.drag = drag; - } - if (typeof t.textContent === "string" && !("value" in t)) { - args.text = t.textContent; - } - if (ev.key != null) args.key = String(ev.key); - if (ev.code != null) args.code = String(ev.code); - if (t.files && t.files.length) { - const f = t.files[0]; - args.file_name = f.name; - args.file_size = f.size; - args.file_type = f.type || ""; - args.file_count = t.files.length; - } - } - if (ev && ev.type === "popstate") { - args.url = typeof location !== "undefined" ? location.href : ""; - args.path = typeof location !== "undefined" ? location.pathname + location.search : ""; - args.state = ev.state; - } - if (ev && ev.dataTransfer) { - try { - const txt = ev.dataTransfer.getData("text") || ev.dataTransfer.getData("text/plain"); - if (txt) args.drop_text = txt; - } catch (_) { - /* ignore */ - } - } - if (valueFromSel && typeof document !== "undefined") { - const src = document.querySelector(valueFromSel); - if (src) { - if ("value" in src && src.type !== "file") args.value = String(src.value); - else args.value = src.textContent != null ? String(src.textContent) : ""; - } - } - if (ev && ev.type === "submit" && t) { - const form = typeof t.closest === "function" ? t.closest("form") : t; - if (form && typeof FormData !== "undefined") { - try { - ev.preventDefault(); - } catch (_) { - /* ignore */ - } - const fields = {}; - for (const [k, v] of new FormData(form)) fields[k] = String(v); - args.fields = fields; - } - } - return args; -} - -function applyStyle(el, styleVal) { - if (typeof styleVal === "string") { - el.setAttribute("style", styleVal); - return; - } - if (isPlainObject(styleVal)) { - for (const [k, v] of Object.entries(styleVal)) { - if (v === null || v === false) el.style.removeProperty(k); - else el.style.setProperty(k.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase()), String(v)); - } - } -} - -export function renderListItems(spec) { - const tag = String(spec.tag || "li"); - const items = Array.isArray(spec.items) ? spec.items : []; - return items - .map((it) => { - if (it == null) return ""; - if (typeof it === "string" || typeof it === "number") { - return `<${tag}>${escapeHtml(String(it))}`; - } - if (!isPlainObject(it)) return ""; - const text = it.text != null ? String(it.text) : it.html != null ? null : ""; - const cls = it.class != null ? ` class="${escapeAttr(String(it.class))}"` : ""; - let attrs = ""; - if (isPlainObject(it.attrs)) { - for (const [k, v] of Object.entries(it.attrs)) { - if (v === null || v === false) continue; - attrs += ` ${escapeAttr(k)}="${escapeAttr(String(v))}"`; - } - } - const inner = it.html != null ? String(it.html) : escapeHtml(text ?? ""); - return `<${tag}${cls}${attrs}>${inner}`; - }) - .join(""); -} - -function escapeHtml(s) { - return s - .replace(/&/g, "&") - .replace(//g, ">") - .replace(/"/g, """); -} - -function escapeAttr(s) { - return escapeHtml(s).replace(/'/g, "'"); -} - -function qsAll(sel) { - if (typeof document === "undefined") return []; - try { - return [...document.querySelectorAll(sel)]; - } catch (_) { - return []; - } -} - -function qsOne(sel) { - const all = qsAll(sel); - return all[0] || null; -} - -/** Sync DOM patches (E1/E2/E3 navigate is sync too). */ -export function applyDomPatch(value) { - if (!value || typeof value !== "object") return; - if (typeof document === "undefined") return; - - const setText = value.set_text || value.setText; - if (isPlainObject(setText)) { - for (const [sel, text] of Object.entries(setText)) { - for (const el of qsAll(sel)) el.textContent = String(text); - } - } - - const setValue = value.set_value || value.setValue; - if (isPlainObject(setValue)) { - for (const [sel, v] of Object.entries(setValue)) { - for (const el of qsAll(sel)) { - if ("value" in el) el.value = String(v); - } - } - } - - const setAttr = value.set_attr || value.setAttr; - if (isPlainObject(setAttr)) { - for (const [sel, attrs] of Object.entries(setAttr)) { - if (!isPlainObject(attrs)) continue; - for (const el of qsAll(sel)) { - for (const [name, raw] of Object.entries(attrs)) { - if (raw === null || raw === false) el.removeAttribute(name); - else el.setAttribute(name, String(raw)); - } - } - } - } - - const setClass = value.set_class || value.setClass; - if (isPlainObject(setClass)) { - for (const [sel, cls] of Object.entries(setClass)) { - for (const el of qsAll(sel)) el.className = String(cls); - } - } - - const addClass = value.add_class || value.addClass; - if (isPlainObject(addClass)) { - for (const [sel, cls] of Object.entries(addClass)) { - const names = String(cls).split(/\s+/).filter(Boolean); - for (const el of qsAll(sel)) for (const c of names) el.classList.add(c); - } - } - - const removeClass = value.remove_class || value.removeClass; - if (isPlainObject(removeClass)) { - for (const [sel, cls] of Object.entries(removeClass)) { - const names = String(cls).split(/\s+/).filter(Boolean); - for (const el of qsAll(sel)) for (const c of names) el.classList.remove(c); - } - } - - const toggleClass = value.toggle_class || value.toggleClass; - if (isPlainObject(toggleClass)) { - for (const [sel, cls] of Object.entries(toggleClass)) { - for (const el of qsAll(sel)) { - if (cls) el.classList.toggle(String(cls)); - } - } - } - - const setStyle = value.set_style || value.setStyle; - if (isPlainObject(setStyle)) { - for (const [sel, st] of Object.entries(setStyle)) { - for (const el of qsAll(sel)) applyStyle(el, st); - } - } - - for (const sel of asSelList(value.focus)) { - const el = qsOne(sel); - if (el && el.focus) el.focus(); - } - for (const sel of asSelList(value.blur)) { - const el = qsOne(sel); - if (el && el.blur) el.blur(); - } - for (const sel of asSelList(value.scroll_into || value.scrollInto)) { - const el = qsOne(sel); - if (el && el.scrollIntoView) el.scrollIntoView({ block: "nearest", behavior: "smooth" }); - } - - const setHtml = value.set_html || value.setHtml; - if (isPlainObject(setHtml)) { - for (const [sel, html] of Object.entries(setHtml)) { - for (const el of qsAll(sel)) el.innerHTML = String(html); - } - } - - const appendHtml = value.append_html || value.appendHtml; - if (isPlainObject(appendHtml)) { - for (const [sel, html] of Object.entries(appendHtml)) { - for (const el of qsAll(sel)) el.insertAdjacentHTML("beforeend", String(html)); - } - } - - const replaceChildren = value.replace_children || value.replaceChildren; - if (isPlainObject(replaceChildren)) { - for (const [sel, html] of Object.entries(replaceChildren)) { - for (const el of qsAll(sel)) el.innerHTML = String(html); - } - } - - const renderList = value.render_list || value.renderList; - if (isPlainObject(renderList)) { - for (const [sel, spec] of Object.entries(renderList)) { - if (!isPlainObject(spec)) continue; - const html = renderListItems(spec); - for (const el of qsAll(sel)) el.innerHTML = html; - } - } - - const removeSel = value.remove || value.remove_nodes || value.removeNodes; - if (removeSel) { - for (const sel of asSelList(removeSel)) { - for (const el of qsAll(sel)) el.remove(); - } - } - - const nav = value.navigate; - if (isPlainObject(nav) && nav.url != null && typeof history !== "undefined") { - const url = String(nav.url); - if (nav.replace) history.replaceState(nav.state ?? null, "", url); - else history.pushState(nav.state ?? null, "", url); - } - - const clip = value.clipboard || value.copy; - if (clip != null && typeof navigator !== "undefined" && navigator.clipboard?.writeText) { - const text = isPlainObject(clip) ? String(clip.text ?? "") : String(clip); - navigator.clipboard.writeText(text).catch(() => {}); - } - - const dl = value.download; - if (isPlainObject(dl) && dl.body != null) { - const mime = String(dl.mime || "text/plain;charset=utf-8"); - const name = String(dl.filename || "download.txt"); - const blob = new Blob([String(dl.body)], { type: mime }); - const url = URL.createObjectURL(blob); - const a = document.createElement("a"); - a.href = url; - a.download = name; - a.click(); - URL.revokeObjectURL(url); - } - - const canvasSpec = value.canvas; - if (isPlainObject(canvasSpec) && canvasSpec.sel) { - runCanvasCommands(canvasSpec); - } - - const audioSpec = value.audio; - if (isPlainObject(audioSpec) && audioSpec.op) { - runAudioEffect(audioSpec); - } -} - -const intervalHandles = new Map(); -const wsHandles = new Map(); -const audioHandles = new Map(); -const observeHandles = new Map(); -let wsSeq = 0; -let observeSeq = 0; - -/** @param {{ sel: string, commands?: object[], clear?: boolean }} spec */ -export function runCanvasCommands(spec) { - if (typeof document === "undefined") return; - const el = qsOne(String(spec.sel)); - if (!el || typeof el.getContext !== "function") return; - const ctx = el.getContext("2d"); - if (!ctx) return; - if (spec.clear) ctx.clearRect(0, 0, el.width || 0, el.height || 0); - const cmds = Array.isArray(spec.commands) - ? spec.commands - : isPlainObject(spec.commands) - ? Object.keys(spec.commands) - .sort() - .map((k) => spec.commands[k]) - : []; - for (const raw of cmds) { - if (!isPlainObject(raw)) continue; - const op = String(raw.op || raw.cmd || "").toLowerCase(); - try { - if (op === "clear" || op === "clearrect") { - ctx.clearRect( - Number(raw.x) || 0, - Number(raw.y) || 0, - Number(raw.w ?? raw.width ?? el.width) || 0, - Number(raw.h ?? raw.height ?? el.height) || 0, - ); - } else if (op === "fillstyle") { - ctx.fillStyle = String(raw.value ?? raw.color ?? "#000"); - } else if (op === "strokestyle") { - ctx.strokeStyle = String(raw.value ?? raw.color ?? "#000"); - } else if (op === "linewidth") { - ctx.lineWidth = Number(raw.value ?? raw.width) || 1; - } else if (op === "font") { - ctx.font = String(raw.value || "16px sans-serif"); - } else if (op === "fillrect") { - if (raw.fill != null) ctx.fillStyle = String(raw.fill); - ctx.fillRect(Number(raw.x) || 0, Number(raw.y) || 0, Number(raw.w ?? raw.width) || 0, Number(raw.h ?? raw.height) || 0); - } else if (op === "strokerect") { - if (raw.stroke != null) ctx.strokeStyle = String(raw.stroke); - ctx.strokeRect(Number(raw.x) || 0, Number(raw.y) || 0, Number(raw.w ?? raw.width) || 0, Number(raw.h ?? raw.height) || 0); - } else if (op === "beginpath") { - ctx.beginPath(); - } else if (op === "closepath") { - ctx.closePath(); - } else if (op === "moveto") { - ctx.moveTo(Number(raw.x) || 0, Number(raw.y) || 0); - } else if (op === "lineto") { - ctx.lineTo(Number(raw.x) || 0, Number(raw.y) || 0); - } else if (op === "arc") { - ctx.arc( - Number(raw.x) || 0, - Number(raw.y) || 0, - Number(raw.r ?? raw.radius) || 0, - Number(raw.start ?? 0), - Number(raw.end ?? Math.PI * 2), - !!raw.ccw, - ); - } else if (op === "stroke") { - if (raw.stroke != null) ctx.strokeStyle = String(raw.stroke); - ctx.stroke(); - } else if (op === "fill") { - if (raw.fill != null) ctx.fillStyle = String(raw.fill); - ctx.fill(); - } else if (op === "filltext") { - if (raw.fill != null) ctx.fillStyle = String(raw.fill); - ctx.fillText(String(raw.text ?? ""), Number(raw.x) || 0, Number(raw.y) || 0); - } else if (op === "drawimage" && raw.src) { - const img = new Image(); - img.src = String(raw.src); - // sync only if already loaded; else fire-and-forget draw on load - const draw = () => { - ctx.drawImage( - img, - Number(raw.x) || 0, - Number(raw.y) || 0, - Number(raw.w ?? raw.width ?? img.width) || img.width, - Number(raw.h ?? raw.height ?? img.height) || img.height, - ); - }; - if (img.complete) draw(); - else img.onload = draw; - } - } catch (_) { - /* skip bad cmd */ - } - } -} - -function runAudioEffect(spec) { - const op = String(spec.op || "").toLowerCase(); - const id = String(spec.id || spec.sel || "default"); - try { - if (op === "play") { - // Optional beep via Web Audio (no external file). - if (spec.freq != null || spec.frequency != null || String(spec.src || "") === "beep") { - const AC = window.AudioContext || window.webkitAudioContext; - if (!AC) return; - let ctx = audioHandles.get(`${id}:ctx`); - if (!ctx) { - ctx = new AC(); - audioHandles.set(`${id}:ctx`, ctx); - } - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = String(spec.wave || "sine"); - osc.frequency.value = Number(spec.freq ?? spec.frequency ?? 440); - const vol = spec.volume != null ? Math.min(1, Math.max(0, Number(spec.volume))) : 0.15; - gain.gain.value = vol; - osc.connect(gain); - gain.connect(ctx.destination); - const dur = Number(spec.ms ?? spec.duration ?? 280) / 1000; - osc.start(); - gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + Math.max(0.05, dur)); - osc.stop(ctx.currentTime + Math.max(0.05, dur) + 0.02); - return; - } - let audio = audioHandles.get(id); - if (spec.sel) { - const el = qsOne(String(spec.sel)); - if (el && el.tagName === "AUDIO") audio = el; - } - if (!audio) { - audio = new Audio(spec.src != null ? String(spec.src) : undefined); - audioHandles.set(id, audio); - } else if (spec.src != null) { - audio.src = String(spec.src); - } - if (spec.volume != null) audio.volume = Math.min(1, Math.max(0, Number(spec.volume))); - if (spec.loop != null) audio.loop = !!spec.loop; - const p = audio.play(); - if (p && p.catch) p.catch(() => {}); - return; - } - const audio = spec.sel ? qsOne(String(spec.sel)) : audioHandles.get(id); - if (!audio) return; - if (op === "pause") audio.pause(); - else if (op === "stop") { - audio.pause(); - try { - audio.currentTime = 0; - } catch (_) { - /* ignore */ - } - } - } catch (_) { - /* ignore */ - } -} - -/** - * Run sync DOM patches then schedule async effects. - */ -export function applyEffects(exports, value, { onError } = {}) { - applyDomPatch(value); - if (!value || typeof value !== "object") return Promise.resolve(); - - const tasks = []; - - const fetchSpec = value.fetch; - if (fetchSpec && typeof fetchSpec === "object" && fetchSpec.url && fetchSpec.then) { - tasks.push(runFetchEffect(exports, fetchSpec, onError)); - } - - const fetchAll = value.fetch_all || value.fetchAll; - if (fetchAll && typeof fetchAll === "object" && fetchAll.then) { - tasks.push(runFetchAllEffect(exports, fetchAll, onError)); - } - - const afterSpec = value.after; - if (afterSpec && typeof afterSpec === "object" && afterSpec.then) { - tasks.push(runAfterEffect(exports, afterSpec, onError)); - } - - const intervalSpec = value.interval; - if (intervalSpec && typeof intervalSpec === "object" && intervalSpec.then) { - runIntervalEffect(exports, intervalSpec, onError); - } - - const clearIv = value.clear_interval || value.clearInterval; - if (clearIv && typeof clearIv === "object") { - const id = String(clearIv.id || "default"); - const h = intervalHandles.get(id); - if (h != null) { - clearInterval(h); - intervalHandles.delete(id); - } - } - - const storageSpec = value.storage; - if (storageSpec && typeof storageSpec === "object" && storageSpec.op) { - tasks.push(runStorageEffect(exports, storageSpec, onError)); - } - - const wsSpec = value.ws; - if (wsSpec && typeof wsSpec === "object" && wsSpec.op) { - tasks.push(runWsEffect(exports, wsSpec, onError)); - } - - const readFile = value.read_file || value.readFile; - if (readFile && typeof readFile === "object" && readFile.then) { - tasks.push(runReadFileEffect(exports, readFile, onError)); - } - - const observe = value.observe; - if (observe) { - const specs = Array.isArray(observe) - ? observe - : observe && typeof observe === "object" && observe.then - ? [observe] - : []; - for (const spec of specs) runObserveEffect(exports, spec, onError); - } - - const unobserve = value.unobserve; - if (unobserve) { - const specs = Array.isArray(unobserve) - ? unobserve - : unobserve && typeof unobserve === "object" - ? [unobserve] - : []; - for (const spec of specs) { - const id = String(spec.id || ""); - const h = observeHandles.get(id); - if (h) { - try { - h.disconnect(); - } catch (_) { - /* ignore */ - } - observeHandles.delete(id); - } - } - } - - return Promise.all(tasks); -} - -async function runReadFileEffect(exports, spec, onError) { - const thenFn = spec.then; - const sel = String(spec.sel || ""); - const as = String(spec.as || "text").toLowerCase(); - const input = qsOne(sel); - if (!input || !input.files || !input.files.length) { - const result = call(exports, thenFn, { ok: false, error: "no file", sel }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - return; - } - const file = input.files[Number(spec.index) || 0]; - try { - let body = ""; - let data_url = ""; - if (as === "data_url" || as === "dataurl") { - data_url = await new Promise((resolve, reject) => { - const r = new FileReader(); - r.onload = () => resolve(String(r.result || "")); - r.onerror = () => reject(r.error || new Error("read failed")); - r.readAsDataURL(file); - }); - } else { - body = await file.text(); - } - const result = call(exports, thenFn, { - ok: true, - name: file.name, - size: file.size, - type: file.type || "", - body, - data_url, - as, - }); - if (!result.ok) { - if (onError) onError(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - } catch (e) { - try { - const result = call(exports, thenFn, { ok: false, error: String(e), name: file.name }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - else if (onError) onError(result.error); - } catch (e2) { - if (onError) onError(String(e2)); - } - } -} - -function runObserveEffect(exports, spec, onError) { - const kind = String(spec.kind || spec.type || "intersect").toLowerCase(); - const sel = String(spec.sel || ""); - const thenFn = spec.then; - const id = String(spec.id || `obs${++observeSeq}`); - const el = qsOne(sel); - if (!el || !thenFn) return; - - const prev = observeHandles.get(id); - if (prev) { - try { - prev.disconnect(); - } catch (_) { - /* ignore */ - } - } - - const fire = (payload) => { - try { - const result = call(exports, thenFn, payload); - if (!result.ok) { - if (onError) onError(result.error); - return; - } - applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - }; - - if (kind === "resize" && typeof ResizeObserver !== "undefined") { - const ro = new ResizeObserver((entries) => { - const en = entries[0]; - const cr = en?.contentRect; - fire({ - ok: true, - kind: "resize", - id, - width: cr ? cr.width : 0, - height: cr ? cr.height : 0, - }); - }); - ro.observe(el); - observeHandles.set(id, ro); - return; - } - - if (typeof IntersectionObserver !== "undefined") { - const io = new IntersectionObserver( - (entries) => { - const en = entries[0]; - if (!en) return; - fire({ - ok: true, - kind: "intersect", - id, - intersecting: !!en.isIntersecting, - ratio: en.intersectionRatio, - }); - if (spec.once && en.isIntersecting) { - try { - io.disconnect(); - } catch (_) { - /* ignore */ - } - observeHandles.delete(id); - } - }, - { threshold: spec.threshold != null ? Number(spec.threshold) : 0.1 }, - ); - io.observe(el); - observeHandles.set(id, io); - } -} - -function buildFetchInit(spec) { - const method = (spec.method || "GET").toUpperCase(); - const init = { method }; - if (spec.headers && typeof spec.headers === "object") init.headers = { ...spec.headers }; - if (spec.fields && typeof spec.fields === "object" && typeof FormData !== "undefined") { - const fd = new FormData(); - for (const [k, v] of Object.entries(spec.fields)) fd.append(k, String(v)); - init.body = fd; - } else if (spec.body != null && method !== "GET" && method !== "HEAD") { - init.body = typeof spec.body === "string" ? spec.body : JSON.stringify(spec.body); - } - return init; -} - -async function runFetchEffect(exports, spec, onError) { - const thenFn = spec.then; - try { - const res = await fetch(String(spec.url), buildFetchInit(spec)); - const body = await res.text(); - const result = call(exports, thenFn, { ok: res.ok, status: res.status, body }); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - if (result.stdout) console.log(result.stdout); - } catch (e) { - try { - const result = call(exports, thenFn, { - ok: false, - status: 0, - body: "", - error: String(e), - }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - else if (onError) onError(result.error); - } catch (e2) { - if (onError) onError(String(e2)); - else console.error(e2); - } - } -} - -async function runFetchAllEffect(exports, spec, onError) { - const thenFn = spec.then; - const reqs = Array.isArray(spec.requests) - ? spec.requests - : isPlainObject(spec.requests) - ? Object.keys(spec.requests) - .sort() - .map((k) => spec.requests[k]) - .filter((r) => r && typeof r === "object") - : []; - try { - const results = await Promise.all( - reqs.map(async (r) => { - try { - const res = await fetch(String(r.url), buildFetchInit(r)); - const body = await res.text(); - return { ok: res.ok, status: res.status, body, url: String(r.url) }; - } catch (e) { - return { ok: false, status: 0, body: "", error: String(e), url: String(r.url || "") }; - } - }), - ); - const result = call(exports, thenFn, { ok: true, results }); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - } -} - -function runAfterEffect(exports, spec, onError) { - const ms = Math.max(0, Number(spec.ms) || 0); - const thenFn = spec.then; - return new Promise((resolve) => { - setTimeout(() => { - try { - const result = call(exports, thenFn, { ok: true }); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - resolve(); - return; - } - Promise.resolve(applyEffects(exports, result.value, { onError })).then(resolve); - if (result.stdout) console.log(result.stdout); - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - resolve(); - } - }, ms); - }); -} - -function runIntervalEffect(exports, spec, onError) { - const ms = Math.max(1, Number(spec.ms) || 1000); - const thenFn = spec.then; - const id = String(spec.id || "default"); - if (intervalHandles.has(id)) { - clearInterval(intervalHandles.get(id)); - intervalHandles.delete(id); - } - const handle = setInterval(() => { - try { - const result = call(exports, thenFn, { ok: true, id }); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - return; - } - applyEffects(exports, result.value, { onError }); - if (result.stdout) console.log(result.stdout); - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - } - }, ms); - intervalHandles.set(id, handle); -} - -function storageStore(scope) { - if (scope === "cookie") return null; - if (typeof localStorage === "undefined") return null; - return scope === "session" ? sessionStorage : localStorage; -} - -function cookieGet(key) { - if (typeof document === "undefined") return null; - const prefix = encodeURIComponent(key) + "="; - for (const part of document.cookie.split(";")) { - const s = part.trim(); - if (s.startsWith(prefix)) return decodeURIComponent(s.slice(prefix.length)); - } - return null; -} - -function cookieSet(key, value, days) { - if (typeof document === "undefined") return; - let extra = "; path=/"; - if (days != null && Number(days) > 0) { - const d = new Date(); - d.setTime(d.getTime() + Number(days) * 864e5); - extra += "; expires=" + d.toUTCString(); - } - document.cookie = encodeURIComponent(key) + "=" + encodeURIComponent(value) + extra; -} - -function cookieRemove(key) { - if (typeof document === "undefined") return; - document.cookie = encodeURIComponent(key) + "=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"; -} - -async function runStorageEffect(exports, spec, onError) { - const op = String(spec.op || "").toLowerCase(); - const key = String(spec.key || ""); - const scope = String(spec.scope || "local"); - try { - if (scope === "cookie") { - if (op === "set") { - cookieSet(key, spec.value != null ? String(spec.value) : "", spec.days); - } else if (op === "remove" || op === "delete") { - cookieRemove(key); - } else if (op === "get") { - const value = cookieGet(key); - if (spec.then) { - const result = call(exports, spec.then, { - ok: true, - op, - key, - value: value == null ? "" : value, - found: value != null, - scope, - }); - if (!result.ok) { - if (onError) onError(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - } - return; - } - if (spec.then && op !== "get") { - const result = call(exports, spec.then, { ok: true, op, key, scope }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - } - return; - } - - const store = storageStore(scope); - if (!store) { - if (onError) onError("storage unavailable"); - return; - } - if (op === "set") { - store.setItem(key, spec.value != null ? String(spec.value) : ""); - if (spec.then) { - const result = call(exports, spec.then, { ok: true, op, key, scope }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - } - return; - } - if (op === "remove" || op === "delete") { - store.removeItem(key); - if (spec.then) { - const result = call(exports, spec.then, { ok: true, op, key, scope }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - } - return; - } - if (op === "get") { - const value = store.getItem(key); - if (spec.then) { - const result = call(exports, spec.then, { - ok: true, - op, - key, - value: value == null ? "" : value, - found: value != null, - scope, - }); - if (!result.ok) { - if (onError) onError(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - } - } - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - } -} - -function runWsEffect(exports, spec, onError) { - const op = String(spec.op || "").toLowerCase(); - return new Promise((resolve) => { - try { - if (op === "open") { - if (typeof WebSocket === "undefined") { - if (onError) onError("WebSocket unavailable"); - resolve(); - return; - } - const id = String(spec.id || `ws${++wsSeq}`); - const sock = new WebSocket(String(spec.url)); - wsHandles.set(id, sock); - sock.addEventListener("open", () => { - if (spec.then_open || spec.thenOpen) { - try { - const result = call(exports, spec.then_open || spec.thenOpen, { ok: true, id }); - if (result.ok) applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - } - resolve(); - }); - sock.addEventListener("message", (ev) => { - const thenMsg = spec.then_message || spec.thenMessage; - if (!thenMsg) return; - try { - const result = call(exports, thenMsg, { - ok: true, - id, - data: typeof ev.data === "string" ? ev.data : String(ev.data), - }); - if (result.ok) applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - }); - sock.addEventListener("close", () => { - wsHandles.delete(id); - const thenClose = spec.then_close || spec.thenClose; - if (thenClose) { - try { - const result = call(exports, thenClose, { ok: true, id }); - if (result.ok) applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - } - }); - sock.addEventListener("error", () => { - const thenErr = spec.then_error || spec.thenError; - if (thenErr) { - try { - const result = call(exports, thenErr, { ok: false, id, error: "ws error" }); - if (result.ok) applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - } - }); - return; - } - if (op === "send") { - const id = String(spec.id || [...wsHandles.keys()][0] || ""); - const sock = wsHandles.get(id); - if (sock && sock.readyState === WebSocket.OPEN) { - sock.send(spec.data != null ? String(spec.data) : ""); - } else if (onError) onError(`ws send: no open socket ${id}`); - resolve(); - return; - } - if (op === "close") { - const id = String(spec.id || [...wsHandles.keys()][0] || ""); - const sock = wsHandles.get(id); - if (sock) sock.close(); - wsHandles.delete(id); - resolve(); - return; - } - resolve(); - } catch (e) { - if (onError) onError(String(e)); - resolve(); - } - }); -} - -function bindTarget(sel) { - if (sel === "window" || sel === "@window") return typeof window !== "undefined" ? window : null; - if (sel === "document" || sel === "@document") - return typeof document !== "undefined" ? document : null; - return null; -} - -/** - * Wire events from `# main` return value (list or `{ wire: [...] }`). - */ -export function wireEvents(exports, bootValue, { onError } = {}) { - let rows = []; - if (Array.isArray(bootValue)) rows = bootValue; - else if (bootValue && Array.isArray(bootValue.wire)) rows = bootValue.wire; - - for (const row of rows) { - const sel = row["选择器"] || row.selector || row.sel; - const ev = row["事件"] || row.event || "click"; - const fn = row["调用"] || row.call || row.fn; - const valueFrom = - row["值选择器"] || row.value_from || row.valueFrom || row.from || ""; - const delegate = - row["委托"] || row.delegate || row.delegation || ""; - if (!sel || !fn) continue; - - const special = bindTarget(sel); - const roots = special - ? [special] - : typeof document !== "undefined" - ? [...document.querySelectorAll(sel)] - : []; - - roots.forEach((node) => { - node.addEventListener(ev, (domEv) => { - try { - if (delegate) { - const hit = - typeof domEv.target?.closest === "function" - ? domEv.target.closest(delegate) - : null; - if (!hit || (node.contains && !node.contains(hit))) return; - } - // Drag/drop hosts need preventDefault on dragover/drop; dragstart can set payload. - if ( - ev === "dragover" || - ev === "dragenter" || - ev === "drop" || - ev === "dragstart" - ) { - try { - domEv.preventDefault(); - } catch (_) { - /* ignore */ - } - } - if (ev === "dragstart" && domEv.dataTransfer) { - try { - const payload = - (domEv.target && - typeof domEv.target.getAttribute === "function" && - domEv.target.getAttribute("data-drag")) || - (typeof domEv.target?.textContent === "string" - ? domEv.target.textContent.trim() - : "") || - ""; - if (payload) { - domEv.dataTransfer.setData("text/plain", payload); - domEv.dataTransfer.setData("text", payload); - domEv.dataTransfer.effectAllowed = "copyMove"; - } - } catch (_) { - /* ignore */ - } - } - if ( - ev === "click" && - typeof domEv.target?.closest === "function" && - domEv.target.closest("a[href]") - ) { - try { - domEv.preventDefault(); - } catch (_) { - /* ignore */ - } - } - const args = eventArgsFromDom(domEv, valueFrom); - if (delegate && domEv.target) { - const hit = domEv.target.closest?.(delegate); - if (hit?.getAttribute) { - const did = hit.getAttribute("data-id"); - if (did != null) args.data_id = did; - if (hit.id) args.id = hit.id; - const drag = hit.getAttribute("data-drag"); - if (drag != null) args.drag = drag; - } - } - const result = call(exports, fn, args); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - return; - } - applyEffects(exports, result.value, { onError }); - if (result.stdout) console.log(result.stdout); - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - } - }); - }); - } - return rows.length; -} - -function markReady(opts, message) { - if (opts.ready && typeof document !== "undefined") { - const el = document.querySelector(opts.ready); - if (el) { - el.classList?.remove?.("err"); - el.textContent = message; - } - } - if (opts.enable && typeof document !== "undefined") { - for (const sel of String(opts.enable).split(",")) { - const s = sel.trim(); - if (!s) continue; - document.querySelectorAll(s).forEach((n) => { - n.disabled = false; - n.removeAttribute("disabled"); - }); - } - } -} - -function markError(opts, err) { - const msg = String(err); - if (opts.onError) opts.onError(msg); - if (opts.ready && typeof document !== "undefined") { - const el = document.querySelector(opts.ready); - if (el) { - el.classList?.add?.("err"); - el.textContent = msg; - } - } else { - console.error(msg); - } -} - -function wirePlayground(exports, playgroundSpec, { onError } = {}) { - const parts = String(playgroundSpec) - .split(",") - .map((s) => s.trim()) - .filter(Boolean); - const sourceSel = parts[0] || "#src"; - const runSel = parts[1] || "#run"; - const outSel = parts[2] || "#out"; - const runBtn = document.querySelector(runSel); - const src = document.querySelector(sourceSel); - const out = document.querySelector(outSel); - if (!runBtn || !src) return 0; - runBtn.disabled = false; - runBtn.removeAttribute("disabled"); - runBtn.addEventListener("click", () => { - try { - const result = runSource(exports, src.value || ""); - if (out) { - out.classList?.toggle?.("err", !result.ok); - out.textContent = result.ok - ? (result.stdout || "(empty stdout)") + - (result.value != null && result.value !== "None" - ? `\n[return] ${typeof result.value === "string" ? result.value : JSON.stringify(result.value)}` - : "") - : result.error || "error"; - } - } catch (e) { - if (onError) onError(String(e)); - else if (out) { - out.classList?.add?.("err"); - out.textContent = String(e); - } - } - }); - return 1; -} - -export async function mount(rawOpts = {}) { - const opts = normalizeMountOptions(rawOpts); - const onError = (err) => markError(opts, err); - - let exports; - try { - exports = await loadWasm(opts.wasmUrl); - } catch (e) { - onError(e); - throw e; - } - - const ver = readCString(exports.memory, exports.mq_version()); - - if (opts.playground) { - const n = wirePlayground(exports, opts.playground, { onError }); - markReady(opts, `marqdo-wasm ${ver} · playground ready`); - return { exports, boot: null, wired: n }; - } - - let source = opts.source; - if (!source && opts.sourceUrl) { - const res = await fetch(opts.sourceUrl); - if (!res.ok) { - const err = `failed to load ${opts.sourceUrl} (${res.status})`; - onError(err); - throw new Error(err); - } - source = await res.text(); - } - if (!source) { - const err = "mount: need source, sourceUrl, or playground"; - onError(err); - throw new Error(err); - } - - const result = boot(exports, source); - if (!result.ok) { - onError(result.error || "boot failed"); - throw new Error(result.error || "boot failed"); - } - - if (result.value && !Array.isArray(result.value)) { - await applyEffects(exports, result.value, { onError }); - } - - const n = wireEvents(exports, result.value, { onError }); - const srcLabel = opts.sourceUrl || "(inline)"; - markReady(opts, `marqdo-wasm ${ver} · wired ${n} handler(s)\nsource: ${srcLabel}`); - return { exports, boot: result, wired: n }; -} - -export async function autoMount(doc) { - const configs = collectMountConfigs(doc); - const results = []; - for (const cfg of configs) { - if (cfg.noBoot) continue; - results.push(await mount(cfg)); - } - return results; -} - -const g = typeof globalThis !== "undefined" ? globalThis : undefined; -if (g && g.document) { - const start = () => { - autoMount(g.document).catch((e) => console.error("marqdo autoMount:", e)); - }; - if (g.document.readyState === "loading") { - g.document.addEventListener("DOMContentLoaded", start); - } else { - queueMicrotask(start); - } -} diff --git a/examples/browser-media/media.mq.md b/examples/browser-media/media.mq.md deleted file mode 100644 index 87a3532..0000000 --- a/examples/browser-media/media.mq.md +++ /dev/null @@ -1,164 +0,0 @@ ---- -markup: occlusion -title: browser-media (route F) -description: file / canvas / audio / observers / drag — GFM tables + lib/browser -import: - browser: lib/browser.mq.md - 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` = "\"preview\""** - **`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` = "" + drop_text + ""** -**`t` = > browser.set_text sel="#log" text=msg** -**`box` = > browser.set_html sel="#dropzone" html=h** -*> browser.merge a=t b=box* diff --git a/examples/calculator.mq.md b/examples/calculator.mq.md index bce8da0..6d5c841 100644 --- a/examples/calculator.mq.md +++ b/examples/calculator.mq.md @@ -1,17 +1,39 @@ # 计算器 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 供下述方法复用的对象或类型命名空间;直接调用所需的子函数。 | + 这是一个普通的 Marqdo 文档。 其中包含一些可以复用的数学计算知识。 ## 加法 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | 必填 | Left operand supplied to this calculation | +| b | any | 必填 | Right operand supplied to this calculation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | + 计算两个数字`a`和`b`的和。 -*[计算结果](a + b)* +完成上述步骤后,返回*[计算结果]((`a` + `b`))*。 ## 乘法 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | 必填 | Left operand supplied to this calculation | +| b | any | 必填 | Right operand supplied to this calculation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | + 计算两个数字`a`和`b`的积。 -*[计算结果](a * b)* +完成上述步骤后,返回*[计算结果]((`a` * `b`))*。 diff --git a/examples/code-as-docs/index.mq.md b/examples/code-as-docs/index.mq.md index 816462d..03ccc8a 100644 --- a/examples/code-as-docs/index.mq.md +++ b/examples/code-as-docs/index.mq.md @@ -12,37 +12,84 @@ description: >- ## 单价 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 价 | any | 必填 | 同一币种下单件商品的标价 | +| 杯数 | any | 1 | 参与本次计价的杯数,未提供时使用正文默认值 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 逐行累加得到的订单总额 | + 一杯标价为`价`的饮品,默认`杯数`=1。先把**总额 = 价 * 杯数**算清,再返回*总额*。 ## 会员折 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 原价 | any | 必填 | 应用折扣之前的原始金额 | +| 折扣 | any | 0.85 | 价格乘数;0.85 表示支付原价的百分之八十五 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | + 会员单要原价`原价`;店里默认八五折,记作`折扣`=0.85。 先算**应付 = 原价 * 折扣**,再返回*应付*。 ## 结账摘要 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 品名 | any | 必填 | 收据或摘要中显示的商品名称 | +| 价 | any | 必填 | 同一币种下单件商品的标价 | +| 杯数 | any | 1 | 参与本次计价的杯数,未提供时使用正文默认值 | +| 会员 | any | False | 是否采用本示例的会员折扣分支 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 包含商品、数量和实付金额的显示文案 | + 客人点了`品名`,单价`价`,杯数`杯数`=1;是否`会员`=False。 按杯数问单价:**小计 = 单价 价=`价` 杯数=`杯数`**。 1. `会员` - **实付 = 会员折 原价=`小计`** - **标签 = "会员价"** + 我们先**实付 = [计算并保存 实付](会员折(原价=`小计`))**,供下一步使用。 + 我们先**标签 = "会员价"**,供下一步使用。 2. * - **实付 = 小计** - **标签 = "原价"** + 我们先**实付 = `小计`**,供下一步使用。 + 我们先**标签 = "原价"**,供下一步使用。 对账时拼成一句人话: -**文案 = 品名 + " ×" + 杯数 + " → " + 标签 + " " + 实付** -*文案* +我们先**文案 = ((((((`品名` + " ×") + `杯数`) + " → ") + `标签`) + " ") + `实付`)**,供下一步使用。 +完成上述步骤后,返回*文案*。 ## 印章加一 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 印 | any | 必填 | 积分卡当前已有的印章数量 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | + 积分卡上的`印`,每喝一杯就**印 = 印 + 1**,接着返回*印*。 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + +这份手账把定价规则放在真正的结账函数里,入口只组织今天的几笔订单。菜单横表是品名到单价的记录,外卖行表则是多条带有数量和会员标记的订单;两者的数据形态不同,因此先按名称取价,再逐行传给同一个摘要函数。 + +会员示例与原价对照使用同一套参数和默认值,避免正文与实现各维护一份优惠规则。金额在本例中使用普通运行时数值,会员折扣可能产生小数;这里没有宣称采用专门的货币舍入模型。需要真实计费精度时应另行规定最小单位与舍入步骤,不能把展示摘要的文本当成准确记账凭证。 + +打印的是已经计算出的摘要,后续业务若要复用它应直接传递该值,而不是解析输出文字。最后给积分卡加一只改变演示中的印章值,不写入用户文件,也不代表某个真实账户已经更新。 + 今日黑板价目——表格给人扫一眼,程序当字典用: `菜单` = @@ -55,14 +102,14 @@ description: >- 上午来了位会员,点两杯拿铁。品名写进`名`,价钱从菜单里取: -**名 = "拿铁"** -**价 = [名](access(菜单, `名`))** -**摘要 = [结账摘要] 品名=`名` 价=`价` 杯数=2 会员=True** +我们先**名 = "拿铁"**,供下一步使用。 +我们先**价 = [名](access(`菜单`, `名`))**,供下一步使用。 +我们先**摘要 = [计算并保存 摘要](结账摘要(品名=`名`, 价=`价`, 杯数=2, 会员=True))**,供下一步使用。 **打印 内容=`摘要`** 旁桌只要一杯普通美式,对照一下原价: -**对照 = [结账摘要] 品名="美式" 价=[美式](access(菜单, "美式"))** +我们先**对照 = [计算并保存 对照](结账摘要(品名="美式", 价=[美式](access(`菜单`, "美式"))))**,供下一步使用。 **打印 内容=`对照`** --- @@ -77,11 +124,11 @@ description: >- | 2 | 美式 | 18 | 2 | False | - [行](遍历 今日订单 为 行) - **一行 = 结账摘要 品名=[品名](access(行, "品名")) 价=[单价](access(行, "单价")) 杯数=[杯数](access(行, "杯数")) 会员=[会员](access(行, "会员"))** + 我们先**一行 = [计算并保存 一行](结账摘要(品名=[品名](access(`行`, "品名")), 价=[单价](access(`行`, "单价")), 杯数=[杯数](access(`行`, "杯数")), 会员=[会员](access(`行`, "会员"))))**,供下一步使用。 **打印 内容=`一行`** 打烊前给积分卡盖一个章: -**印 = 41** -**印 = 印章加一 印=`印`** +我们先**印 = 41**,供下一步使用。 +我们先**印 = [计算并保存 印](印章加一(印=`印`))**,供下一步使用。 **打印 内容=`印`** diff --git a/examples/engineering-knowledge/config/resolve.mq.md b/examples/engineering-knowledge/config/resolve.mq.md index 7b24860..b434e95 100644 --- a/examples/engineering-knowledge/config/resolve.mq.md +++ b/examples/engineering-knowledge/config/resolve.mq.md @@ -9,8 +9,22 @@ Use when: final normalized configuration is required. # config +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Object/type namespace for the child functions below; call the intended child directly | + ## resolve_config - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | any | required | Filesystem path under the granted root; this callback's prose identifies URL paths separately | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; this unit completes the operations described below without a data return | +The shared input protocol also accepts `path`. We **[Accept this documented input without changing the result](`path`)**. + +Input `path`, used by the steps below. `defaults` = diff --git a/examples/engineering-knowledge/index.mq.md b/examples/engineering-knowledge/index.mq.md index bf43629..f00f871 100644 --- a/examples/engineering-knowledge/index.mq.md +++ b/examples/engineering-knowledge/index.mq.md @@ -6,6 +6,7 @@ description: Tiny project demonstrating Capability Catalog + reuse + decisions. # Engineering Knowledge demo + This folder is a miniature “large engineering” slice: config resolution already exists. Before generating a new loader, run: @@ -19,4 +20,8 @@ Expected: **REUSE config.resolve**, not a new `load_configuration`. # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + * "see README via catalog/reuse CLI" diff --git a/examples/executable-knowledge/capabilities/order-pricing.mq.md b/examples/executable-knowledge/capabilities/order-pricing.mq.md index 694fb8c..0137b56 100644 --- a/examples/executable-knowledge/capabilities/order-pricing.mq.md +++ b/examples/executable-knowledge/capabilities/order-pricing.mq.md @@ -8,25 +8,45 @@ import: # 订单定价 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 供下述方法复用的对象或类型命名空间;直接调用所需的子函数。 | + 按订单行取未税金额与品类,套用税率后汇总含税总额。 ## 含税价 -`行` +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 行 | any | 必填 | 订单行记录;按相邻数据表提供金额、品类等字段 | -**金额 = [订单行金额](access(行, "金额"))** -**品类 = [订单行品类](access(行, "品类"))** -**税率 = > tax.标准税率.查询 品类=`品类`** -**结果 = [本行含税价](金额 * (1 + 税率))** -*结果* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 本次计算得到的结果 | + +输入`行`,按下方步骤使用这个值。 + +我们先**金额 = [订单行金额](access(`行`, "金额"))**,供下一步使用。 +我们先**品类 = [订单行品类](access(`行`, "品类"))**,供下一步使用。 +我们先**税率 = [计算并保存 税率](tax.标准税率.查询(品类=`品类`))**,供下一步使用。 +我们先**结果 = [本行含税价]((`金额` * (1 + `税率`)))**,供下一步使用。 +完成上述步骤后,返回*结果*。 ## 含税总额 -`订单` +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 订单 | any | 必填 | 包含行记录集合的订单数据;税率与金额字段由本示例约定 | -**行列表 = [订单行列表](access(订单, "行"))** -`总额` = 0 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 逐行累加得到的订单总额 | + +输入`订单`,按下方步骤使用这个值。 + +我们先**行列表 = [订单行列表](access(`订单`, "行"))**,供下一步使用。 +我们先**总额 = 0**,供下一步使用。 - [逐个订单行](遍历 行列表 为 行) - **行含税价 = > 订单定价.含税价 行=`行`** - **总额 = [累加](总额 + 行含税价)** -*总额* + 我们先**行含税价 = [计算并保存 行含税价](订单定价.含税价(行=`行`))**,供下一步使用。 + 我们先**总额 = [累加]((`总额` + `行含税价`))**,供下一步使用。 +完成上述步骤后,返回*总额*。 diff --git a/examples/executable-knowledge/docs/invoice-answer.mq.md b/examples/executable-knowledge/docs/invoice-answer.mq.md index c6726e8..b78965d 100644 --- a/examples/executable-knowledge/docs/invoice-answer.mq.md +++ b/examples/executable-knowledge/docs/invoice-answer.mq.md @@ -9,11 +9,15 @@ import: # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + 发票回答:演示订单一行图书,未税金额 100。 -`订单` = > json.parse text={"行":[{"金额":100,"品类":"书"}]} -**总额 = > pricing.订单定价.含税总额 订单=`订单`** +We first **订单 = [Compute 订单](json.parse(text="{\"行\":[{\"金额\":100,\"品类\":\"书\"}]}"))** for the next step. +We first **总额 = [Compute 总额](pricing.订单定价.含税总额(订单=`订单`))** for the next step. 这张订单的含税总额是[含税总价](总额)。 -> print text=`总额` +We now **[Display this step's result](> print text=`总额`)**. diff --git a/examples/executable-knowledge/knowledge/negative-refund.mq.md b/examples/executable-knowledge/knowledge/negative-refund.mq.md index 9341bc3..529b024 100644 --- a/examples/executable-knowledge/knowledge/negative-refund.mq.md +++ b/examples/executable-knowledge/knowledge/negative-refund.mq.md @@ -7,8 +7,16 @@ title: 折扣不适用于退款 # 折扣不适用于退款 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Object/type namespace for the child functions below; call the intended child directly | + 负知识:退款结算不得套用会员折扣。Agent 复用折扣能力时应拒绝该适用面。 ## 说明 -*[不适用](false)* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | The value explicitly returned below; conditional returns follow the selected branch | + +After these steps, return *[不适用](`false`)*. diff --git a/examples/executable-knowledge/knowledge/tax-2026.mq.md b/examples/executable-knowledge/knowledge/tax-2026.mq.md index 4ca4351..8bafa8d 100644 --- a/examples/executable-knowledge/knowledge/tax-2026.mq.md +++ b/examples/executable-knowledge/knowledge/tax-2026.mq.md @@ -11,10 +11,18 @@ applicability: # 标准税率 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Object/type namespace for the child functions below; call the intended child directly | + 当前政策下的标准增值税率。`品类` 预留给差异化税率;本演示固定返回标准税率。 ## 查询 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | The value explicitly returned below; conditional returns follow the selected branch | + `品类` -*[标准税率](0.13)* +After these steps, return *[标准税率](0.13)*. diff --git a/examples/executable-knowledge/schema/order.mq.md b/examples/executable-knowledge/schema/order.mq.md index 61a98ed..5c1b97f 100644 --- a/examples/executable-knowledge/schema/order.mq.md +++ b/examples/executable-knowledge/schema/order.mq.md @@ -8,11 +8,20 @@ type: Schema | 字段 | 类型 | 说明 | |---|---|---| -| 行 | list<订单行> | 待计价的订单行 | +| 行 | list | 待计价的订单行;每一项遵守下方独立对象的字段契约 | -## 订单行 +订单只收拢本次计算需要的行记录,不替调用方补缺失金额或品类。 +每一行使用同一金额单位,税率知识由能力模块选择;此处只描述数据形态。 + +# 订单行 | 字段 | 类型 | 说明 | |---|---|---| | 金额 | number | 未税金额 | | 品类 | text | 用于选择税率 | + +订单行是独立的顶层对象类型,因此订单中的列表元素可以引用它。 +字段表紧接对象标题,避免将类型声明误写成具有参数和返回值的普通函数。 + +行字段的运行时契约约束列表本身;元素形态按订单行的字段说明提供, +不把尚未支持的泛型类型拼写当成已经执行的逐元素校验。 diff --git a/examples/foreign-native-report/index.mq.md b/examples/foreign-native-report/index.mq.md new file mode 100644 index 0000000..1a5fbdb --- /dev/null +++ b/examples/foreign-native-report/index.mq.md @@ -0,0 +1,151 @@ +--- +markup: occlusion +title: Native report tools and a persistent Intl formatter +import: + foreign: lib/foreign.mq.md + table: lib/table.mq.md + stats: lib/stats.mq.md + math: lib/math.mq.md + result: lib/result.mq.md +--- + +This module keeps order analysis in native Marqdo and uses Node Intl only for +locale-aware currency formatting. Import it from a report page or call its +two public functions separately. There is no executable main in this module; +the English and Chinese public feature pages compose the full callable view. + +From the repository root, call analyze_orders with an orders row list and +--effects none. It returns ordinary report data. Pass that report to +format_summary with --effects process.exec for the bounded persistent formatter. +A missing Node executable is an explicit failed Result; native analysis remains +available without it. No Python interpreter is required. + +## analyze_orders + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| orders | list | required | Order rows with a region and numeric amount; no file or network IO | +| region_key | text | "region" | Field whose value identifies a group | +| amount_key | text | "amount" | Numeric amount field in every row | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Native report with regions, total, count and average | + +Use `orders`, `region_key`="region" and `amount_key`="amount" for the +whole analysis. Grouping, ordering, arithmetic, means and population deviation +all use Marqdo and its standard libraries. Each region retains orders, total, +mean and z_span, so moving the boundary does not remove the analysis. The data +is a row list, not a JSON program or an opaque host dataframe. + +The report has one row per region in sorted key order. Population variance is +the mean squared deviation; a singleton or equal-valued group has zero spread, +for which the normalization denominator is one and z_span is zero. The maximum +normalized deviation is the same statistic the previous kernel example displayed. +Values are ordinary runtime numbers, not a financial decimal model; the formatter +later chooses presentation precision without changing this report. + +Empty input returns no regions and zero totals/average. Missing fields and invalid +amounts preserve native diagnostics; do not replace them with invented zeroes. +The function is pure and needs no interpreter, plugin, process, file or network +grant. Its actual return can be checked with marqdo call before preparing a view. +The native report is also the only analysis value copied into external kernels: +there is no second implementation of grouping or statistics in another language. + +We **groups = [Group native rows and order their original keys](table.sort_by(list=table.group_by(list=`orders`, key=`region_key`), key="key"))** and **regions = [Start native summary rows](table.empty_list())**. +- [Summarize each region through native values](for groups as group) + We **rows = [Read this group's original rows](access(group, "rows"))** and **region = [Retain its region key](access(group, "key"))** and **values = [Read numeric amounts](table.pluck(list=`rows`, key=`amount_key`))**. + We **mean = [Compute the native arithmetic mean](stats.mean(list=`values`))** and **squared = 0.0**. + - [Accumulate population squared deviation](for values as value) + We **squared = squared + (value - mean) * (value - mean)**. + We **sigma = [Compute population spread](math.sqrt(value=`squared` / len(values)))**. + 1. `sigma` <= 0 + We **sigma = 1** so equal-valued groups keep a zero normalized span. + We **count = [Count this region's values](len(values))** and **total = [Sum the region in Marqdo](table.aggregate(list=`values`))** and **maximum = [Read its largest amount](table.aggregate(list=`values`, op="max"))** and **z_span = (maximum - mean) / sigma**. + + `row` = + + | region | orders | total | mean | z_span | + |---|---|---|---|---| + | `region` | `count` | `total` | `mean` | `z_span` | + + We **regions = [Retain this native summary row](table.append(list=`regions`, item=`row`))**. +We **count = [Count all input orders](len(orders))** and **total = [Sum all native amounts](table.aggregate(list=`orders`, key=`amount_key`))** and **average = 0**. +1. `count` > 0 + We **average = [Use the native mean without integer division](stats.mean(list=table.pluck(list=`orders`, key=`amount_key`)))** for a nonempty report. + +`report` = + +| regions | total | count | average | +|---|---|---|---| +| `regions` | `total` | `count` | `average` | + +After the native analysis we return *report*. + +## format_summary + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| report | map | required | Native analyze_orders result with total and average | +| locale | text | "en-US" | Locale understood by Node Intl; currency is CNY | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result containing localized total and average strings | + +Use `report` and `locale`="en-US" only for the presentation gap: +locale-aware currency formatting is provided here by Node's built-in Intl. +The source makes that external boundary explicit. It does not read or write files, +recalculate the native report, import a package or use Python. Node must already +be installed; probe it before creating a kernel and return a real failure if +it is unavailable. + +One persistent kernel receives JSON copies of the report and locale. The first +evaluation creates a formatter and formats the total; the second reuses that +same formatter for the already-computed native average. A fresh process without +its previous state could not run the second expression successfully. The helper +checks each evaluation's ok field and closes a live kernel before returning, +including handled evaluation errors. A dead kernel has already been retired and +must not be closed a second time. + +This function needs process.exec. Native policy or serialization diagnostics +remain diagnostics, not synthetic currency strings. Kernel values cannot become +guessed handles, and an opaque handle never crosses a CLI JSON boundary. Only +the two actual formatted strings leave this task in its successful Result. + +We **probe = [Check the explicit external interpreter](foreign.probe(lang="node"))**. +1. not access(`probe`, "ok") + Return *[Keep the missing interpreter visible](result.error(code="example.node", message=str(`probe`), operation="format_summary"))*. +We **kernel = [Open one persistent formatter kernel](foreign.session_open(lang="node"))** and **copied = [Copy the native report as ordinary data](foreign.session_set(id=`kernel`, name="report", value=`report`))** and **selected = [Copy the requested display locale](foreign.session_set(id=`kernel`, name="locale", value=`locale`))**. + +`formatter_code` = +```node +var money = new Intl.NumberFormat(locale, {style: "currency", currency: "CNY"}); +money.format(report.total) +``` + +We **first = [Create the formatter and format the native total](foreign.session_eval(id=`kernel`, code=`formatter_code`))**. +1. not access(`first`, "ok") + 1. access(`first`, "alive") + We **closed = [Close a still-live failed formatter](foreign.session_close(id=`kernel`))**. + Return *[Keep the actual formatter failure](result.error(code="example.format", message=str(`first`), operation="format_summary"))*. + +`average_code` = +```node +money.format(report.average) +``` + +We **second = [Reuse the formatter's persistent state](foreign.session_eval(id=`kernel`, code=`average_code`))**. +1. not access(`second`, "ok") + 1. access(`second`, "alive") + We **closed = [Close a live kernel after the second failure](foreign.session_close(id=`kernel`))**. + Return *[Keep the actual reuse failure](result.error(code="example.format", message=str(`second`), operation="format_summary"))*. +We **total = [Read the actual formatted total](access(first, "result"))** and **average = [Read the actual formatted average](access(second, "result"))** and **closed = [Close the consumed formatter kernel](foreign.session_close(id=`kernel`))**. + +`formatted` = + +| total | average | +|---|---| +| `total` | `average` | + +Return *[The real locale-aware strings](result.ok(value=`formatted`))*. diff --git a/examples/knowledge-layers/libai.mq.md b/examples/knowledge-layers/libai.mq.md index 982ae9e..5654ec4 100644 --- a/examples/knowledge-layers/libai.mq.md +++ b/examples/knowledge-layers/libai.mq.md @@ -9,9 +9,17 @@ import: # 李白 = > 诗人 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 供下述方法复用的对象或类型命名空间;直接调用所需的子函数。 | + ## 姓名 -*"李白"* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | + +完成上述步骤后,返回*"李白"*。 ## 出生年份 @@ -19,4 +27,4 @@ import: |------|------|------| | 701 | number | 公元 701 年;来源:corpus/libai.md#出生年份 | -*701* +完成上述步骤后,返回*701*。 diff --git a/examples/knowledge-layers/main.mq.md b/examples/knowledge-layers/main.mq.md index c3cc8ae..8f22ec6 100644 --- a/examples/knowledge-layers/main.mq.md +++ b/examples/knowledge-layers/main.mq.md @@ -4,4 +4,8 @@ markup: occlusion # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + 诗人李白的出生年份是[出生年份](李白.出生年份)。 diff --git a/examples/knowledge-layers/poet.mq.md b/examples/knowledge-layers/poet.mq.md index 3eead98..42e6aaa 100644 --- a/examples/knowledge-layers/poet.mq.md +++ b/examples/knowledge-layers/poet.mq.md @@ -4,6 +4,10 @@ markup: occlusion # 诗人 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;本段完成下述操作,不额外返回业务数据。 | + | 字段 | 类型 | 说明 | |------|------|------| | 姓名 | text | 诗人姓名 | diff --git a/examples/linalg-least-squares/index.mq.md b/examples/linalg-least-squares/index.mq.md index eb32adb..a98697f 100644 --- a/examples/linalg-least-squares/index.mq.md +++ b/examples/linalg-least-squares/index.mq.md @@ -9,10 +9,15 @@ import: # Least squares from a runnable document + Fit a line through three points with an overdetermined `A x ≈ b` using `lstsq` (QR path). A heatmap makes the design matrix visible in `view`. # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + `A` = $$ \begin{bmatrix}1&0\\1&1\\1&2\end{bmatrix} @@ -23,15 +28,15 @@ $$ \begin{pmatrix}1\\2\\2\end{pmatrix} $$ -**`A` = > la.from_formula formula=`A`** -**`b` = > la.from_formula formula=`b`** +We first **A = [Compute A](la.from_formula(formula=`A`))** for the next step. +We first **b = [Compute b](la.from_formula(formula=`b`))** for the next step. -**`_` = > la.draw factor=`A` kind="heatmap" theme="light" path="ls-heatmap.svg"** +We first **_ = [Compute _](la.draw(factor=`A`, kind="heatmap", theme="light", path="ls-heatmap.svg"))** for the next step. -**`ls` = > la.lstsq a=`A` b=`b`** -**`x` = [x](access(ls, "x"))** -**`resid` = [residual_fro](access(ls, "residual_fro"))** +We first **ls = [Compute ls](la.lstsq(a=`A`, b=`b`))** for the next step. +We first **x = [x](access(`ls`, "x"))** for the next step. +We first **resid = [residual_fro](access(`ls`, "residual_fro"))** for the next step. -> print text=`x` -> print text=`resid` -> print text=ls-ok +We now **[Display this step's result](> print text=`x`)**. +We now **[Display this step's result](> print text=`resid`)**. +We now **[Display this step's result](> print text="ls-ok")**. diff --git a/examples/linalg-svd/index.mq.md b/examples/linalg-svd/index.mq.md index 42a36e5..ee62db6 100644 --- a/examples/linalg-svd/index.mq.md +++ b/examples/linalg-svd/index.mq.md @@ -8,20 +8,25 @@ import: # SVD from a runnable document + A diagonal matrix has singular values on the diagonal. Prefer matrix values and methods; `factorize` / `draw` stay explicit for teaching SVGs. # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + `M` = $$ \begin{bmatrix}4&0\\0&2\end{bmatrix} $$ -**`M` = > la.from_formula formula=`M`** -**`f` = > la.factorize matrix=`M` kind="svd"** -**`S` = [S](access(f, "S"))** -**`_` = > la.draw factor=`f` kind="svd" theme="light" path="svd-structure.svg"** -**`hm` = > la.draw factor=`M` kind="hinton" path="svd-hinton.svg"** +We first **M = [Compute M](la.from_formula(formula=`M`))** for the next step. +We first **f = [Compute f](la.factorize(matrix=`M`, kind="svd"))** for the next step. +We first **S = [S](access(`f`, "S"))** for the next step. +We first **_ = [Compute _](la.draw(factor=`f`, kind="svd", theme="light", path="svd-structure.svg"))** for the next step. +We first **hm = [Compute hm](la.draw(factor=`M`, kind="hinton", path="svd-hinton.svg"))** for the next step. -> print text=`S` -> print text=svd-ok +We now **[Display this step's result](> print text=`S`)**. +We now **[Display this step's result](> print text="svd-ok")**. diff --git a/examples/linalg-transpose/index.mq.md b/examples/linalg-transpose/index.mq.md index b598eab..0e7c73c 100644 --- a/examples/linalg-transpose/index.mq.md +++ b/examples/linalg-transpose/index.mq.md @@ -8,10 +8,15 @@ import: # Transpose reverses products + Declare shapes in a table, form \(P = AB\), then check \((AB)^\top = B^\top A^\top\) by running the document. # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + `shapes` = | @ | name | rows | cols | @@ -19,13 +24,13 @@ Declare shapes in a table, form \(P = AB\), then check \((AB)^\top = B^\top A^\t | 1 | A | 2 | 3 | | 2 | B | 3 | 2 | -**`env` = > la.declare table=`shapes`** -**`A` = [A](access(env, "A"))** -**`B` = [B](access(env, "B"))** -**`P` = `A` * `B`** -**`t` = > `P`.T_ascii** -> print text=`t` +We first **env = [Compute env](la.declare(table=`shapes`))** for the next step. +We first **A = [A](access(`env`, "A"))** for the next step. +We first **B = [B](access(`env`, "B"))** for the next step. +We first **P = (`A` * `B`)** for the next step. +We first **t = [Compute t](> `P`.T_ascii)** for the next step. +We now **[Display this step's result](> print text=`t`)**. 1. `t` == "B^T*A^T" - > print text=identity-ok + We now **[Display this step's result](> print text="identity-ok")**. 2. * - > print text=identity-fail + We now **[Display this step's result](> print text="identity-fail")**. diff --git a/examples/link-syntax/libai.mq.md b/examples/link-syntax/libai.mq.md index d647918..5106a0c 100644 --- a/examples/link-syntax/libai.mq.md +++ b/examples/link-syntax/libai.mq.md @@ -9,6 +9,10 @@ status: stable # 李白 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 供下述方法复用的对象或类型命名空间;直接调用所需的子函数。 | + 这个文档存储了李白的信息。 ## 李白的出生年份 @@ -19,4 +23,4 @@ status: stable |------|------|------| | 701 | number | 公元 701 年 | -*701* +完成上述步骤后,返回*701*。 diff --git a/examples/link-syntax/main.mq.md b/examples/link-syntax/main.mq.md index 0ff2200..c02f938 100644 --- a/examples/link-syntax/main.mq.md +++ b/examples/link-syntax/main.mq.md @@ -3,4 +3,8 @@ markup: occlusion --- # main + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | 用户想要知道李白的出生年份,我们要告诉用户[李白的出生年份](李白.李白的出生年份) diff --git a/examples/marqdo-blog/README.md b/examples/marqdo-blog/README.md index aa6b1b4..64d1c19 100644 --- a/examples/marqdo-blog/README.md +++ b/examples/marqdo-blog/README.md @@ -18,15 +18,16 @@ smoke.sh # curl checks against a running serve ## Run -```bash -bash scripts/build-web-plugin.sh -export MARQDO_EXT=$PWD/ext # if ~/.marqdo/ext is stale -export MARQDO_WEB_PLUGIN=$PWD/plugins/web/build/libweb.so -cd examples/marqdo-blog && marqdo run serve.mq.md -# other terminal: -bash examples/marqdo-blog/smoke.sh +从仓库根使用当前 CLI 和开发手册准备原生插件,再调用启动函数: + +```sh +target/debug/marqdo call skills/marqdo-dev/index.mq.md prepare_web --effects plugin --fs-root . --require-ok --json +target/debug/marqdo call examples/marqdo-blog/serve.mq.md main --effects plugin,fs.write,network.write --fs-root examples/marqdo-blog --require-ok --json ``` +默认数据库按授权站点根解析到 data/blog.db,重启保留已有文章。准备工程插件见开发入口的 prepare_engineering;验收使用独占副本,不删除现有数据库。 + + | Path | Artifact | |------|----------| | `/` | Document home + post cards | diff --git a/examples/marqdo-blog/api/echo.mq.md b/examples/marqdo-blog/api/echo.mq.md index 1b75fa3..0293fa2 100644 --- a/examples/marqdo-blog/api/echo.mq.md +++ b/examples/marqdo-blog/api/echo.mq.md @@ -10,11 +10,15 @@ auth: none # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Result or browser effect record assembled below | + Echo request fields bound via Artifact Metadata (`arg` overlays). -**msg = message** +We first **msg = `message`** for the next step. 1. not `msg` - **msg = ""** + We first **msg = ""** for the next step. 2. * `out` = @@ -23,4 +27,4 @@ Echo request fields bound via Artifact Metadata (`arg` overlays). |----|---------| | True | `msg` | -*out* +After these steps, return *out*. diff --git a/examples/marqdo-blog/api/ping.mq.md b/examples/marqdo-blog/api/ping.mq.md index 42dfff1..5b3e1bd 100644 --- a/examples/marqdo-blog/api/ping.mq.md +++ b/examples/marqdo-blog/api/ping.mq.md @@ -11,10 +11,14 @@ description: Health ping — documentation is the API (ADR 0007). # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Result or browser effect record assembled below | + `out` = | ok | service | |----|---------| | True | marqdo-blog | -*out* +After these steps, return *out*. diff --git a/examples/marqdo-blog/components/foot.mq.md b/examples/marqdo-blog/components/foot.mq.md index 3ecf33a..811dae5 100644 --- a/examples/marqdo-blog/components/foot.mq.md +++ b/examples/marqdo-blog/components/foot.mq.md @@ -4,6 +4,10 @@ markup: occlusion ## 页脚 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | The value explicitly returned below; conditional returns follow the selected branch | + 站点页脚。放版权与概览链接。 `页脚` = @@ -14,4 +18,4 @@ markup: occlusion | 关于 | /about | | | 后台 | /admin | | -*`页脚`* \ No newline at end of file +After these steps, return *页脚*. \ No newline at end of file diff --git a/examples/marqdo-blog/components/nav.mq.md b/examples/marqdo-blog/components/nav.mq.md index c67b75f..1bf4b42 100644 --- a/examples/marqdo-blog/components/nav.mq.md +++ b/examples/marqdo-blog/components/nav.mq.md @@ -4,6 +4,10 @@ markup: occlusion ## 导航 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | The value explicitly returned below; conditional returns follow the selected branch | + 站点顶部导航。首项是站点名(渐变 Logo 由主题 CSS 处理),`后台` 指向需要登录的 `/admin`。 `导航` = @@ -16,4 +20,4 @@ markup: occlusion | 关于 | /about | | | 后台 | /admin | | -*`导航`* \ No newline at end of file +After these steps, return *导航*. \ No newline at end of file diff --git a/examples/marqdo-blog/components/side.mq.md b/examples/marqdo-blog/components/side.mq.md index 07cf43c..cebf8cb 100644 --- a/examples/marqdo-blog/components/side.mq.md +++ b/examples/marqdo-blog/components/side.mq.md @@ -4,6 +4,10 @@ markup: occlusion ## 侧栏 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | The value explicitly returned below; conditional returns follow the selected branch | + 右侧归档面板:文章入口、标签、实时小部件。 `侧栏` = @@ -16,4 +20,4 @@ markup: occlusion | 发布文章 | /admin/new | | | 实时终端 | /#live | | -*`侧栏`* \ No newline at end of file +After these steps, return *侧栏*. \ No newline at end of file diff --git a/examples/marqdo-blog/db/posts.mq.md b/examples/marqdo-blog/db/posts.mq.md index 2c6e1ed..22459b2 100644 --- a/examples/marqdo-blog/db/posts.mq.md +++ b/examples/marqdo-blog/db/posts.mq.md @@ -1,46 +1,61 @@ --- markup: occlusion -title: blog posts schema +title: 当前 Artifact 博客数据调用手册 import: + document: lib/document.mq.md data: ext/data/db.mq.md + fs: lib/fs.mq.md + text: lib/text.mq.md --- +本文件负责可调用的说明与编排,[posts.tables.md](posts.tables.md)负责可独立阅读的 Markdown 常量。调用时把 --fs-root 指向 examples/marqdo-blog,读取需要 fs.read;连接数据库或编译样式时还需要 plugin。 + ## schema -`fields` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 与原字面表一致的数据类型和记录/列式形态 | -| 字段 | 类型 | 可空 | -|------|------|------| -| title | text | False | -| slug | text | False | -| summary | text | True | -| content | text | True | -| tag | text | True | -| created_at | text | True | +当前站点的文章字段包括标题、slug、摘要、正文、标签和创建日期。原生数据库初始化器负责 id;本结构保留当前自动列表与详情页所需字段。 -*fields* +从站点根目录授予 fs.read 后调用。实际常量位于 [posts.tables.md](posts.tables.md#schema);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 + +完成后返回*[读取schema的实际 Markdown 常量](document.read_table(path="db/posts.tables.md", title="schema"))*. ## seed -`rows` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 与原字面表一致的数据类型和记录/列式形态 | -| title | slug | summary | content | tag | created_at | -|-------|------|---------|---------|-----|------------| -| Hello Marqdo | hello | Welcome | Hello — executable documents. | intro | 2026-09-01 | -| Artifact Web | artifact-web | Document first | Pages are mq.md files. | design | 2026-09-28 | +两篇当前站点的起始文章保留稳定 slug、内容与日期。只有调用 open 且文章表为空时才插入;读取种子本身不会改变现有文章。 -*rows* +从站点根目录授予 fs.read 后调用。实际常量位于 [posts.tables.md](posts.tables.md#seed);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 + +完成后返回*[读取seed的实际 Markdown 常量](document.read_table(path="db/posts.tables.md", title="seed"))*. ## open - + `url`="sqlite:data/blog.db" -**store = > data.db url=`url`** -**fields = > schema** -> `store`.init name=posts fields=`fields` -**existing = > `store`.select table="posts" limit=1** -1. `existing` - *store* -2. * - **seed = > seed** - > `store`.insert table=posts rows=`seed` - *store* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | any | None | None 使用授权站点根内 data/blog.db;验收可传独占绝对 URI | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 已初始化且保留原有文章的实际数据库资源 | + +使用`url`=None,以 examples/marqdo-blog 为 --fs-root 授予 fs.write 与 plugin。默认路径先通过固有能力创建 data 目录,再解析真实绝对文件地址,避免被插件模块位置或终端工作目录影响。显式 SQLite 路径同样经过根目录和符号链接检查;其他受支持后端按其连接契约执行,文件授权不限制外部数据库服务。 + +字段与种子由原生 Markdown 读取器保留字面类型。初始化只确保文章表存在,再查一行判断是否已有业务数据;只为空表插入原来的两条记录。已有或部分填充的表都原样保留,这不是列迁移器,也不会删除或重排用户文章。连接、结构或插入失败应停止启动,不能继续监听并声称数据库已经准备好。 + +隔离验收使用调用者拥有的临时站点副本,保留同一资源继续查询与写入。进程退出、连接关闭后再清理该目录,不对示例的现有 data 目录执行重置。读取结构或种子本身不写库,写入只发生在这份明确初始化流程里。 + +1. `url` == None + 我们 **[创建本站默认数据目录](fs.make_dirs(path="data"))**、**file = [按原生授权根解析数据库文件](fs.resolve(path="data/blog.db"))** 和 **url = "sqlite:" + file**。 +1. [明确选择 SQLite 后端](text.starts_with(text=`url`, prefix="sqlite:")) + 我们 **file = [取出实际 SQLite 地址](text.replace(text=`url`, old="sqlite:", new="", count=1))**、**file = [检查根目录和符号链接边界](fs.resolve(path=`file`))** 和 **url = "sqlite:" + file**。 +我们 **store = [连接实际选择的数据库](data.db(url=`url`))** 和 **fields = [读取当前文章结构](schema())**。 +接着 **[确保文章结构但不清空数据](> `store`.init name="posts" fields=`fields`)** 和 **existing = [检查是否已有业务文章](> `store`.select table="posts" limit=1)**。 +1. not `existing` + 我们 **rows = [读取空表使用的原始记录](seed())** 和 **[只初始化空表](> `store`.insert table="posts" rows=`rows`)**。 +准备完成后返回 *store*,供当前服务流程继续使用。 diff --git a/examples/marqdo-blog/db/posts.tables.md b/examples/marqdo-blog/db/posts.tables.md new file mode 100644 index 0000000..669e7a7 --- /dev/null +++ b/examples/marqdo-blog/db/posts.tables.md @@ -0,0 +1,25 @@ +# 当前 Artifact 博客数据 + +这里保存原生字面 GFM 数据。调用函数通过 document.read_table 读取所选章节;不会执行本文件中的说明或示例。 + +## schema + +当前站点的文章字段包括标题、slug、摘要、正文、标签和创建日期。原生数据库初始化器负责 id;本结构保留当前自动列表与详情页所需字段。 + +| 字段 | 类型 | 可空 | +|------|------|------| +| title | text | False | +| slug | text | False | +| summary | text | True | +| content | text | True | +| tag | text | True | +| created_at | text | True | + +## seed + +两篇当前站点的起始文章保留稳定 slug、内容与日期。只有调用 open 且文章表为空时才插入;读取种子本身不会改变现有文章。 + +| title | slug | summary | content | tag | created_at | +|-------|------|---------|---------|-----|------------| +| Hello Marqdo | hello | Welcome | Hello — executable documents. | intro | 2026-09-01 | +| Artifact Web | artifact-web | Document first | Pages are mq.md files. | design | 2026-09-28 | diff --git a/examples/marqdo-blog/db/schema.mq.md b/examples/marqdo-blog/db/schema.mq.md index 5c3899c..e2315f0 100644 --- a/examples/marqdo-blog/db/schema.mq.md +++ b/examples/marqdo-blog/db/schema.mq.md @@ -1,50 +1,44 @@ --- markup: occlusion +title: 博客表结构调用手册 +import: + document: lib/document.mq.md --- +本文件负责可调用的说明与编排,[schema.tables.md](schema.tables.md)负责可独立阅读的 Markdown 常量。调用时把 --fs-root 指向 examples/marqdo-blog,读取需要 fs.read;连接数据库或编译样式时还需要 plugin。 + ## posts -文章主表结构。`slug` 用于详情页 `/post/{slug}` 的动态路由;`content` 存 Markdown 正文;`tag` 是主标签(tags 表 slug)。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 与原字面表一致的数据类型和记录/列式形态 | -`schema` = +文章结构保留 id、标题、slug、摘要、Markdown 正文、主标签和时间字段。slug 对应文章详情路由;可空声明控制存储约束,路由授权仍由端点或门禁负责。 -| 字段 | 类型 | 可空 | -|------|------|------| -| id | integer | false | -| title | text | false | -| slug | text | false | -| summary | text | true | -| content | text | true | -| tag | text | true | -| created_at | text | true | -| updated_at | text | true | +从站点根目录授予 fs.read 后调用。实际常量位于 [schema.tables.md](schema.tables.md#posts);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 -*`schema`* +完成后返回*[读取posts的实际 Markdown 常量](document.read_table(path="db/schema.tables.md", title="posts"))*. ## tags -标签表结构。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 与原字面表一致的数据类型和记录/列式形态 | -`tags` = +标签结构保留显示名称与稳定 slug。显示文字可以改动,路由和文章主标签应继续引用稳定标识;唯一索引需要在正式迁移中明确声明。 -| 字段 | 类型 | 可空 | -|------|------|------| -| id | integer | false | -| name | text | false | -| slug | text | false | +从站点根目录授予 fs.read 后调用。实际常量位于 [schema.tables.md](schema.tables.md#tags);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 -*`tags`* +完成后返回*[读取tags的实际 Markdown 常量](document.read_table(path="db/schema.tables.md", title="tags"))*. ## post_tags -文章-标签关联表结构。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 与原字面表一致的数据类型和记录/列式形态 | -`post_tags` = +关联结构保留文章与标签标识。种子关系依赖空数据库中预期的插入顺序;向已有用户库导入时应先映射真实 id,不能直接复用演示序号。 -| 字段 | 类型 | 可空 | -|------|------|------| -| id | integer | false | -| post_id | integer | false | -| tag_id | integer | false | +从站点根目录授予 fs.read 后调用。实际常量位于 [schema.tables.md](schema.tables.md#post_tags);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 -*`post_tags`* \ No newline at end of file +完成后返回*[读取post_tags的实际 Markdown 常量](document.read_table(path="db/schema.tables.md", title="post_tags"))*. diff --git a/examples/marqdo-blog/db/schema.tables.md b/examples/marqdo-blog/db/schema.tables.md new file mode 100644 index 0000000..c050211 --- /dev/null +++ b/examples/marqdo-blog/db/schema.tables.md @@ -0,0 +1,38 @@ +# 博客表结构 + +这里保存原生字面 GFM 数据。调用函数通过 document.read_table 读取所选章节;不会执行本文件中的说明或示例。 + +## posts + +文章结构保留 id、标题、slug、摘要、Markdown 正文、主标签和时间字段。slug 对应文章详情路由;可空声明控制存储约束,路由授权仍由端点或门禁负责。 + +| 字段 | 类型 | 可空 | +|------|------|------| +| id | integer | false | +| title | text | false | +| slug | text | false | +| summary | text | true | +| content | text | true | +| tag | text | true | +| created_at | text | true | +| updated_at | text | true | + +## tags + +标签结构保留显示名称与稳定 slug。显示文字可以改动,路由和文章主标签应继续引用稳定标识;唯一索引需要在正式迁移中明确声明。 + +| 字段 | 类型 | 可空 | +|------|------|------| +| id | integer | false | +| name | text | false | +| slug | text | false | + +## post_tags + +关联结构保留文章与标签标识。种子关系依赖空数据库中预期的插入顺序;向已有用户库导入时应先映射真实 id,不能直接复用演示序号。 + +| 字段 | 类型 | 可空 | +|------|------|------| +| id | integer | false | +| post_id | integer | false | +| tag_id | integer | false | diff --git a/examples/marqdo-blog/db/seed.mq.md b/examples/marqdo-blog/db/seed.mq.md index 225f95f..e793a32 100644 --- a/examples/marqdo-blog/db/seed.mq.md +++ b/examples/marqdo-blog/db/seed.mq.md @@ -1,57 +1,44 @@ --- markup: occlusion +title: 博客演示种子调用手册 +import: + document: lib/document.mq.md --- +本文件负责可调用的说明与编排,[seed.tables.md](seed.tables.md)负责可独立阅读的 Markdown 常量。调用时把 --fs-root 指向 examples/marqdo-blog,读取需要 fs.read;连接数据库或编译样式时还需要 plugin。 + ## posts -种子文章。首页与详情页的初始数据。created_at 用于按时间倒序展示;tag 是主标签 slug。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 与原字面表一致的数据类型和记录/列式形态 | -`posts` = +六篇演示文章覆盖文档、路由、原生集合、实时通信、会话和数据库。日期用于稳定排序,正文保持 Markdown 数据;这些常量不会自行写入数据库。 -| 行 | title | slug | summary | content | tag | created_at | updated_at | -|----|-------|------|---------|---------|-----|------------|------------| -| 1 | 你好,Marqdo 博客 | hello-marqdo | 用 Marqdo 的 web 扩展库搭建的第一个博客。表格即组件、文档即代码。 | 这是一篇介绍博客系统的文章。它由 Marqdo 脚本在启动时写入 SQLite,通过 ext/web 的组件装配渲染成页面。 | marqdo | 2026-08-01 | 2026-08-02 | -| 2 | 动态路由与文章详情 | dynamic-routing | 如何用 /post/{slug} 动态路由渲染单篇文章。 | 本文说明动态路由机制:作者面注册带 {slug} 占位符的路由,请求时把路径参数注入页面查询条件。 | web | 2026-08-05 | 2026-08-05 | -| 3 | 用 GFM 表格表达数据 | gfm-tables | Marqdo 的字典操作不依赖 json 库,GFM 表格即可完成。 | 表格即数据、表格即组件。这篇文章展示如何在 .mq.md 里用横向表写种子数据,用脚注索引读取字段。 | tutorial | 2026-08-10 | 2026-08-11 | -| 4 | WebSocket 实时小部件 | websocket-live | 给博客加一个实时回显的 WebSocket 端点。 | 通过 app.路由实时 注册 /live 端点,配合 public/live.js 在首页显示实时连接状态。 | realtime | 2026-08-15 | 2026-08-15 | -| 5 | 会话与登录鉴权 | session-auth | 后台用 session 门禁保护,只有登录用户能发布文章。 | 用 app.鉴权 配置管理员用户表,/admin 下的 CRUD 页面都需要有效会话。 | web | 2026-08-18 | 2026-08-20 | -| 6 | 数据库与 CRUD | database-crud | 博客的文章、标签、关联全部由 SQLite 支撑。 | db.初始化 建表、db.插入 写种子、后台表单增删改。文章与标签通过 post_tags 关联。 | database | 2026-08-20 | 2026-08-21 | +从站点根目录授予 fs.read 后调用。实际常量位于 [seed.tables.md](seed.tables.md#posts);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 -*`posts`* +完成后返回*[读取posts的实际 Markdown 常量](document.read_table(path="db/seed.tables.md", title="posts"))*. ## tags -种子标签。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 与原字面表一致的数据类型和记录/列式形态 | -`tags` = +演示标签保留原始顺序与 slug,便于在独立空库中验证文章关联。读取这些行没有插入或删除效果;现有用户标签应由显式迁移管理。 -| 行 | name | slug | -|----|------|------| -| 1 | Marqdo | marqdo | -| 2 | Web | web | -| 3 | 教程 | tutorial | -| 4 | 数据库 | database | -| 5 | 实时 | realtime | +从站点根目录授予 fs.read 后调用。实际常量位于 [seed.tables.md](seed.tables.md#tags);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 -*`tags`* +完成后返回*[读取tags的实际 Markdown 常量](document.read_table(path="db/seed.tables.md", title="tags"))*. ## post_tags -种子文章-标签关联。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 与原字面表一致的数据类型和记录/列式形态 | -`post_tags` = +关联行保持文章与标签的演示对应关系。它们适用于按同一顺序初始化的空库;已有数据需要重新映射 id,读取函数不会清空或重建任何表。 -| 行 | post_id | tag_id | -|----|---------|--------| -| 1 | 1 | 1 | -| 2 | 1 | 2 | -| 3 | 2 | 2 | -| 4 | 3 | 1 | -| 5 | 3 | 3 | -| 6 | 4 | 5 | -| 7 | 4 | 2 | -| 8 | 5 | 2 | -| 9 | 6 | 4 | -| 10 | 6 | 1 | +从站点根目录授予 fs.read 后调用。实际常量位于 [seed.tables.md](seed.tables.md#post_tags);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 -*`post_tags`* \ No newline at end of file +完成后返回*[读取post_tags的实际 Markdown 常量](document.read_table(path="db/seed.tables.md", title="post_tags"))*. diff --git a/examples/marqdo-blog/db/seed.tables.md b/examples/marqdo-blog/db/seed.tables.md new file mode 100644 index 0000000..7acb234 --- /dev/null +++ b/examples/marqdo-blog/db/seed.tables.md @@ -0,0 +1,45 @@ +# 博客演示种子 + +这里保存原生字面 GFM 数据。调用函数通过 document.read_table 读取所选章节;不会执行本文件中的说明或示例。 + +## posts + +六篇演示文章覆盖文档、路由、原生集合、实时通信、会话和数据库。日期用于稳定排序,正文保持 Markdown 数据;这些常量不会自行写入数据库。 + +| 行 | title | slug | summary | content | tag | created_at | updated_at | +|----|-------|------|---------|---------|-----|------------|------------| +| 1 | 你好,Marqdo 博客 | hello-marqdo | 用 Marqdo 的 web 扩展库搭建的第一个博客。表格即组件、文档即代码。 | 这是一篇介绍博客系统的文章。它由 Marqdo 脚本在启动时写入 SQLite,通过 ext/web 的组件装配渲染成页面。 | marqdo | 2026-08-01 | 2026-08-02 | +| 2 | 动态路由与文章详情 | dynamic-routing | 如何用 /post/{slug} 动态路由渲染单篇文章。 | 本文说明动态路由机制:作者面注册带 {slug} 占位符的路由,请求时把路径参数注入页面查询条件。 | web | 2026-08-05 | 2026-08-05 | +| 3 | 用 GFM 表格表达数据 | gfm-tables | Marqdo 的字典操作不依赖 json 库,GFM 表格即可完成。 | 表格即数据、表格即组件。这篇文章展示如何在 .mq.md 里用横向表写种子数据,用脚注索引读取字段。 | tutorial | 2026-08-10 | 2026-08-11 | +| 4 | WebSocket 实时小部件 | websocket-live | 给博客加一个实时回显的 WebSocket 端点。 | 通过 app.路由实时 注册 /live 端点,配合 public/live.js 在首页显示实时连接状态。 | realtime | 2026-08-15 | 2026-08-15 | +| 5 | 会话与登录鉴权 | session-auth | 后台用 session 门禁保护,只有登录用户能发布文章。 | 用 app.鉴权 配置管理员用户表,/admin 下的 CRUD 页面都需要有效会话。 | web | 2026-08-18 | 2026-08-20 | +| 6 | 数据库与 CRUD | database-crud | 博客的文章、标签、关联全部由 SQLite 支撑。 | db.初始化 建表、db.插入 写种子、后台表单增删改。文章与标签通过 post_tags 关联。 | database | 2026-08-20 | 2026-08-21 | + +## tags + +演示标签保留原始顺序与 slug,便于在独立空库中验证文章关联。读取这些行没有插入或删除效果;现有用户标签应由显式迁移管理。 + +| 行 | name | slug | +|----|------|------| +| 1 | Marqdo | marqdo | +| 2 | Web | web | +| 3 | 教程 | tutorial | +| 4 | 数据库 | database | +| 5 | 实时 | realtime | + +## post_tags + +关联行保持文章与标签的演示对应关系。它们适用于按同一顺序初始化的空库;已有数据需要重新映射 id,读取函数不会清空或重建任何表。 + +| 行 | post_id | tag_id | +|----|---------|--------| +| 1 | 1 | 1 | +| 2 | 1 | 2 | +| 3 | 2 | 2 | +| 4 | 3 | 1 | +| 5 | 3 | 3 | +| 6 | 4 | 5 | +| 7 | 4 | 2 | +| 8 | 5 | 2 | +| 9 | 6 | 4 | +| 10 | 6 | 1 | diff --git a/examples/marqdo-blog/pages/about.mq.md b/examples/marqdo-blog/pages/about.mq.md index 848830a..e992925 100644 --- a/examples/marqdo-blog/pages/about.mq.md +++ b/examples/marqdo-blog/pages/about.mq.md @@ -8,4 +8,5 @@ markup: occlusion # 关于 Marqdo + Marqdo 是可执行文档语言:文档即程序,程序即知识。 diff --git a/examples/marqdo-blog/serve.mq.md b/examples/marqdo-blog/serve.mq.md index cbfed36..36341ac 100644 --- a/examples/marqdo-blog/serve.mq.md +++ b/examples/marqdo-blog/serve.mq.md @@ -1,13 +1,28 @@ --- markup: occlusion -title: marqdo-blog serve -description: Scan Artifact documents/endpoints and listen (ADR 0007). +title: Callable Artifact blog launcher import: web: ext/web/web.mq.md posts: db/posts.mq.md --- -# main +This launcher starts the ordinary Markdown/data-source Documents and declared JSON Endpoints. It owns data preparation and listener lifetime; the index remains readable page content. From the checkout use marqdo call examples/marqdo-blog/serve.mq.md main with --effects plugin,fs.write,network.write and --fs-root examples/marqdo-blog. -**store = > posts.open url="sqlite:data/blog.db"** -> web.serve root="." host="127.0.0.1" port=18081 db=`store` static_dir="public" +## main + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| root | text | "examples/marqdo-blog" | Explicit discovery root relative to the checkout | +| port | number | 18081 | Local loopback listen port | +| url | any | None | None uses the retained site-root database; tests supply an owned URI | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Blocking listener after database preparation and declared-route discovery | + +Use `root`="examples/marqdo-blog", `port`=18081 and `url`=None from the checkout. The ordinary callable heading makes this workflow available through call, while Document bodies remain Markdown. Native filesystem resolution keeps SQLite under the actual granted site root, independently of the terminal working directory. Existing articles are retained and only an empty table receives demonstration rows. + +Discovery follows the actual route metadata for Home, About, slug detail, Ping and Echo. Ordinary Documents keep their existing request-time data-source behavior. Starting this workflow is an explicit local network action, not a side effect of reading a library. The listener blocks until the supervising caller stops the process; no detached daemon or database reset is implied. + +We **store = [Prepare the retained current blog data](posts.open(url=`url`))**. +Return *[Discover and listen with the actual site context](web.serve(root=`root`, host="127.0.0.1", port=`port`, db=`store`, static_dir="public"))*. diff --git a/examples/marqdo-blog/styles/theme.mq.md b/examples/marqdo-blog/styles/theme.mq.md index 4d8f5f6..aeee470 100644 --- a/examples/marqdo-blog/styles/theme.mq.md +++ b/examples/marqdo-blog/styles/theme.mq.md @@ -1,407 +1,149 @@ --- markup: occlusion -title: styles/theme -description: 博客主题:样式即数据表格,装配即函数。 +title: 博客主题字面样式调用手册 import: - 网页: ext/web/网页.mq.md + document: lib/document.mq.md + web: ext/web/web.mq.md text: lib/text.mq.md + table: lib/table.mq.md --- -博客主题的样式即数据表格:每个 `## 段` 导出一张 GFM 样式表(`|选择器|属性|值|`, -或用 `|媒体|选择器|属性|值|` 表达响应式),`## 全局` 用 `样式装配` 函数把它们 -装配成一份完整 CSS。这符合 文档即代码 —— 样式是可读的表格,装配是显式调用。 +本文件负责可调用的说明与编排,[theme.tables.md](theme.tables.md)负责可独立阅读的 Markdown 常量。调用时把 --fs-root 指向 examples/marqdo-blog,读取需要 fs.read;连接数据库或编译样式时还需要 plugin。 ## 基础 -配色与字体变量、页面骨架。衬线标题 + 无衬线正文,暖白纸感背景。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 与原字面表一致的数据类型和记录/列式形态 | -`基础` = +基础段声明纸张、文字和强调色变量,以及字体与页面骨架。返回值仍是原生样式表数据,编译与浏览器加载由各自的明确步骤完成。 -| 选择器 | 属性 | 值 | -|--------|------|-----| -| :root | --ink | #1c1917 | -| :root | --ink-soft | #44403c | -| :root | --muted | #78716c | -| :root | --faint | #a8a29e | -| :root | --paper | #f7f5f2 | -| :root | --card | #ffffff | -| :root | --line | #e7e5e4 | -| :root | --accent | #4f46e5 | -| :root | --accent-2 | #7c3aed | -| :root | --accent-ink | #ffffff | -| :root | --radius | 16px | -| :root | --shadow | 0 1px 2px rgba(28,25,23,.05), 0 8px 24px rgba(28,25,23,.06) | -| :root | --shadow-lg | 0 4px 12px rgba(28,25,23,.08), 0 20px 48px rgba(28,25,23,.12) | -| :root | --serif | "Noto Serif SC", Georgia, "Songti SC", serif | -| :root | --sans | "Noto Sans SC", "IBM Plex Sans", system-ui, -apple-system, sans-serif | -| html | scroll-behavior | smooth | -| * | box-sizing | border-box | -| ::selection | background | rgba(79,70,229,.18) | -| body | margin | 0 | -| body | font-family | var(--sans) | -| body | background | var(--paper) | -| body | color | var(--ink) | -| body | display | grid | -| body | min-height | 100vh | -| body | line-height | 1.7 | -| body | grid-template-rows | auto 1fr auto | -| body.has-sidebar | grid-template-columns | 15rem 1fr | -| body.has-sidebar | grid-template-areas | "top top" "side main" "foot foot" | -| body.no-sidebar | grid-template-areas | "top" "main" "foot" | +从站点根目录授予 fs.read 后调用。实际常量位于 [theme.tables.md](theme.tables.md#基础);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 -*`基础`* +完成后返回*[读取基础的实际 Markdown 常量](document.read_table(path="styles/theme.tables.md", title="基础"))*. ## 顶栏 -吸顶导航:磨砂玻璃 + 细分隔线,Logo 处用渐变强调。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 与原字面表一致的数据类型和记录/列式形态 | -`顶栏` = +顶栏段保留吸顶导航、磨砂背景、品牌渐变与链接状态。选择器与值都位于数据叶子,调用函数说明用途,避免把整套声明堆进执行流程。 -| 选择器 | 属性 | 值 | -|--------|------|-----| -| header.topnav | grid-area | top | -| header.topnav | position | sticky | -| header.topnav | top | 0 | -| header.topnav | z-index | 20 | -| header.topnav | background | rgba(255,255,255,.82) | -| header.topnav | backdrop-filter | blur(10px) | -| header.topnav | -webkit-backdrop-filter | blur(10px) | -| header.topnav | border-bottom | 1px solid var(--line) | -| header.topnav | padding | .9rem 2rem | -| header.topnav | display | flex | -| header.topnav | align-items | center | -| header.topnav | justify-content | space-between | -| ul.nav | list-style | none | -| ul.nav | margin | 0 | -| ul.nav | padding | 0 | -| ul.nav | display | flex | -| ul.nav | align-items | center | -| ul.nav | gap | .35rem | -| ul.nav li | margin | 0 | -| ul.nav a | display | inline-block | -| ul.nav a | padding | .45rem .9rem | -| ul.nav a | border-radius | 999px | -| ul.nav a | color | var(--ink-soft) | -| ul.nav a | font-weight | 500 | -| ul.nav a | text-decoration | none | -| ul.nav a | transition | background .18s ease, color .18s ease | -| ul.nav a:hover | background | rgba(79,70,229,.1) | -| ul.nav a:hover | color | var(--accent) | -| ul.nav li:first-child a | font-family | var(--serif) | -| ul.nav li:first-child a | font-size | 1.25rem | -| ul.nav li:first-child a | font-weight | 700 | -| ul.nav li:first-child a | background | linear-gradient(120deg, var(--accent), var(--accent-2)) | -| ul.nav li:first-child a | -webkit-background-clip | text | -| ul.nav li:first-child a | background-clip | text | -| ul.nav li:first-child a | -webkit-text-fill-color | transparent | -| ul.nav li:first-child a | color | transparent | -| ul.nav li:first-child a | padding-left | .2rem | -| ul.nav li:first-child a | padding-right | .2rem | +从站点根目录授予 fs.read 后调用。实际常量位于 [theme.tables.md](theme.tables.md#顶栏);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 -*`顶栏`* +完成后返回*[读取顶栏的实际 Markdown 常量](document.read_table(path="styles/theme.tables.md", title="顶栏"))*. ## 侧栏 -归档面板:浅底圆角卡片,链接胶囊化。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 与原字面表一致的数据类型和记录/列式形态 | -`侧栏` = +侧栏段保留归档面板的布局、链接间距和悬停反馈。它只提供样式数据,具体侧栏内容仍由独立组件或 Document 负责。 -| 选择器 | 属性 | 值 | -|--------|------|-----| -| aside.side | grid-area | side | -| aside.side | padding | 2rem 1.25rem | -| aside.side | border-right | 1px solid var(--line) | -| aside.side | background | linear-gradient(180deg, #fbfaf8, #f3f1ec) | -| ul.side-nav | list-style | none | -| ul.side-nav | margin | 0 | -| ul.side-nav | padding | 0 | -| ul.side-nav | display | flex | -| ul.side-nav | flex-direction | column | -| ul.side-nav | gap | .25rem | -| ul.side-nav li | margin | 0 | -| ul.side-nav a | display | block | -| ul.side-nav a | padding | .55rem .85rem | -| ul.side-nav a | border-radius | 10px | -| ul.side-nav a | color | var(--ink-soft) | -| ul.side-nav a | text-decoration | none | -| ul.side-nav a | font-weight | 500 | -| ul.side-nav a | transition | background .15s ease, transform .15s ease, color .15s ease | -| ul.side-nav a:hover | background | #fff | -| ul.side-nav a:hover | color | var(--accent) | -| ul.side-nav a:hover | transform | translateX(4px) | -| ul.side-nav a:hover | box-shadow | 0 1px 3px rgba(28,25,23,.08) | +从站点根目录授予 fs.read 后调用。实际常量位于 [theme.tables.md](theme.tables.md#侧栏);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 -*`侧栏`* +完成后返回*[读取侧栏的实际 Markdown 常量](document.read_table(path="styles/theme.tables.md", title="侧栏"))*. ## 主体 -内容区留白与节奏。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 与原字面表一致的数据类型和记录/列式形态 | -`主体` = +主体段定义内容区留白、标题和导语的排版节奏。数据读取保持原有字段和值;主题编译不会替页面构造布局节点。 -| 选择器 | 属性 | 值 | -|--------|------|-----| -| main.main | grid-area | main | -| main.main | padding | 2.5rem 2.5rem 3.5rem | -| main.main | max-width | 76rem | -| main.main | width | 100% | -| .main-intro | margin-bottom | .5rem | -| .main-intro h1 | font-family | var(--serif) | -| .main-intro h1 | margin | 0 0 .5rem | -| .main-intro h1 | font-size | clamp(2rem, 5vw, 2.9rem) | -| .main-intro h1 | line-height | 1.2 | -| .main-intro h1 | font-weight | 700 | -| .main-intro h1 | letter-spacing | -.01em | -| .main-intro p | color | var(--muted) | -| .main-intro p | margin | 0 | -| .main-intro p | font-size | 1.05rem | +从站点根目录授予 fs.read 后调用。实际常量位于 [theme.tables.md](theme.tables.md#主体);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 -*`主体`* +完成后返回*[读取主体的实际 Markdown 常量](document.read_table(path="styles/theme.tables.md", title="主体"))*. ## 卡片 -文章卡片:白底大圆角、柔和阴影、hover 抬升,整卡可点。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 与原字面表一致的数据类型和记录/列式形态 | -`卡片` = +卡片段保留文章列表的网格、阴影、封面和悬停状态。样式类名应与页面输出保持一致;此函数只读取声明,不查询文章数据。 -| 选择器 | 属性 | 值 | -|--------|------|-----| -| .content.cards | display | grid | -| .content.cards | gap | 1.5rem | -| .content.cards | margin-top | 2rem | -| .content.cards | grid-template-columns | repeat(auto-fill, minmax(17rem, 1fr)) | -| .content.cards article.card | background | var(--card) | -| .content.cards article.card | border | 1px solid var(--line) | -| .content.cards article.card | border-radius | var(--radius) | -| .content.cards article.card | padding | 1.6rem 1.7rem | -| .content.cards article.card | box-shadow | var(--shadow) | -| .content.cards article.card | transition | transform .22s ease, box-shadow .22s ease, border-color .22s ease | -| .content.cards article.card | display | flex | -| .content.cards article.card | flex-direction | column | -| .content.cards article.card | gap | .55rem | -| .content.cards article.card:hover | transform | translateY(-6px) | -| .content.cards article.card:hover | box-shadow | var(--shadow-lg) | -| .content.cards article.card:hover | border-color | rgba(79,70,229,.35) | -| .content.cards a.card-link | text-decoration | none | -| .content.cards a.card-link | color | inherit | -| .content.cards a.card-link | display | flex | -| .content.cards a.card-link | flex-direction | column | -| .content.cards a.card-link | gap | .55rem | -| .content.cards a.card-link | height | 100% | -| .content.cards a.card-link:hover | color | inherit | -| .content.cards h2 | font-family | var(--serif) | -| .content.cards h2 | margin | 0 | -| .content.cards h2 | font-size | 1.35rem | -| .content.cards h2 | line-height | 1.35 | -| .content.cards h2 | font-weight | 700 | -| .content.cards h2 | transition | color .18s ease | -| .content.cards a.card-link:hover h2 | color | var(--accent) | -| .card-meta | font-size | .82rem | -| .card-meta | color | var(--faint) | -| .card-meta | letter-spacing | .04em | -| .card-meta | text-transform | uppercase | -| .card-tag | align-self | flex-start | -| .card-tag | font-size | .78rem | -| .card-tag | color | var(--accent) | -| .card-tag | background | rgba(79,70,229,.08) | -| .card-tag | padding | .15rem .65rem | -| .card-tag | border-radius | 999px | -| .card-tag | font-weight | 600 | -| .content.cards p | color | var(--muted) | -| .content.cards p | margin | 0 | -| .content.cards p | font-size | .95rem | -| .content.cards p | flex | 1 | +从站点根目录授予 fs.read 后调用。实际常量位于 [theme.tables.md](theme.tables.md#卡片);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 -*`卡片`* +完成后返回*[读取卡片的实际 Markdown 常量](document.read_table(path="styles/theme.tables.md", title="卡片"))*. ## 页脚 -`页脚` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 与原字面表一致的数据类型和记录/列式形态 | -| 选择器 | 属性 | 值 | -|--------|------|-----| -| footer.foot | grid-area | foot | -| footer.foot | padding | 1.4rem 2rem | -| footer.foot | border-top | 1px solid var(--line) | -| footer.foot | color | var(--muted) | -| footer.foot | background | #fff | -| footer.foot | font-size | .9rem | -| footer.foot | display | flex | -| footer.foot | justify-content | space-between | -| footer.foot | align-items | center | -| footer.foot | flex-wrap | wrap | -| footer.foot | gap | .5rem | -| ul.foot-nav | list-style | none | -| ul.foot-nav | margin | 0 | -| ul.foot-nav | padding | 0 | -| ul.foot-nav | display | flex | -| ul.foot-nav | gap | 1rem | -| ul.foot-nav | flex-wrap | wrap | -| ul.foot-nav li | margin | 0 | -| ul.foot-nav a | color | var(--muted) | -| ul.foot-nav a | text-decoration | none | -| ul.foot-nav a:hover | color | var(--accent) | +页脚段保留页面末尾的留白、分隔线和链接外观。页脚若分为多个布局区域,仍应沿组件目录拆分,样式声明不会代替工程结构。 -*`页脚`* +从站点根目录授予 fs.read 后调用。实际常量位于 [theme.tables.md](theme.tables.md#页脚);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 + +完成后返回*[读取页脚的实际 Markdown 常量](document.read_table(path="styles/theme.tables.md", title="页脚"))*. ## 表单 -后台表单统一风格。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 与原字面表一致的数据类型和记录/列式形态 | -`表单` = +表单段保留输入控件、按钮和管理操作的状态样式。字段校验、保存和鉴权属于数据与安全资源;样式只改变已存在控件的外观。 -| 选择器 | 属性 | 值 | -|--------|------|-----| -| .site-form | margin-top | 1.75rem | -| .site-form | max-width | 34rem | -| .site-form | background | var(--card) | -| .site-form | border | 1px solid var(--line) | -| .site-form | border-radius | var(--radius) | -| .site-form | padding | 1.8rem | -| .site-form | box-shadow | var(--shadow) | -| .site-form form | display | grid | -| .site-form form | gap | 1rem | -| .site-form label | display | grid | -| .site-form label | gap | .35rem | -| .site-form label | font-size | .92rem | -| .site-form label | font-weight | 600 | -| .site-form label | color | var(--ink-soft) | -| .site-form input | padding | .65rem .8rem | -| .site-form input | border | 1px solid var(--line) | -| .site-form input | border-radius | 10px | -| .site-form input | font | inherit | -| .site-form input | background | #fdfcfb | -| .site-form input | transition | border-color .15s ease, box-shadow .15s ease | -| .site-form textarea | padding | .65rem .8rem | -| .site-form textarea | border | 1px solid var(--line) | -| .site-form textarea | border-radius | 10px | -| .site-form textarea | font | inherit | -| .site-form textarea | background | #fdfcfb | -| .site-form textarea | transition | border-color .15s ease, box-shadow .15s ease | -| .site-form select | padding | .65rem .8rem | -| .site-form select | border | 1px solid var(--line) | -| .site-form select | border-radius | 10px | -| .site-form select | font | inherit | -| .site-form select | background | #fdfcfb | -| .site-form select | transition | border-color .15s ease, box-shadow .15s ease | -| .site-form input:focus | outline | none | -| .site-form input:focus | border-color | var(--accent) | -| .site-form input:focus | box-shadow | 0 0 0 3px rgba(79,70,229,.12) | -| .site-form textarea:focus | outline | none | -| .site-form textarea:focus | border-color | var(--accent) | -| .site-form textarea:focus | box-shadow | 0 0 0 3px rgba(79,70,229,.12) | -| .site-form select:focus | outline | none | -| .site-form select:focus | border-color | var(--accent) | -| .site-form select:focus | box-shadow | 0 0 0 3px rgba(79,70,229,.12) | -| .site-form input[readonly] | background | #f5f5f4 | -| .site-form input[readonly] | color | var(--muted) | -| .site-form textarea | min-height | 10rem | -| .site-form textarea | resize | vertical | -| .site-form .err | color | #b91c1c | -| .site-form .err | font-size | .85rem | -| .site-form .actions | display | flex | -| .site-form .actions | gap | .75rem | -| .site-form .actions | align-items | center | -| .site-form .actions | flex-wrap | wrap | -| .site-form .actions | padding-top | .25rem | -| .site-form button | background | linear-gradient(120deg, var(--accent), var(--accent-2)) | -| .site-form button | color | var(--accent-ink) | -| .site-form button | border | 0 | -| .site-form button | padding | .6rem 1.3rem | -| .site-form button | border-radius | 999px | -| .site-form button | cursor | pointer | -| .site-form button | font-weight | 600 | -| .site-form button | font-size | .95rem | -| .site-form button | transition | opacity .15s ease, transform .15s ease, box-shadow .15s ease | -| .site-form button:hover | opacity | .92 | -| .site-form button:hover | transform | translateY(-1px) | -| .site-form button:hover | box-shadow | 0 6px 18px rgba(79,70,229,.3) | -| .site-form a.btn | display | inline-block | -| .site-form a.btn | padding | .6rem 1.3rem | -| .site-form a.btn | border-radius | 999px | -| .site-form a.btn | border | 1px solid var(--line) | -| .site-form a.btn | color | var(--ink-soft) | -| .site-form a.btn | text-decoration | none | -| .site-form a.btn | font-weight | 500 | -| .site-form a.btn | font-size | .95rem | -| .site-form .meta | color | var(--muted) | -| .site-form .meta | font-size | .9rem | -| .site-form .admin-list | margin | 0 | -| .site-form .admin-list | padding | 0 | -| .site-form .admin-list | list-style | none | -| .site-form .admin-list | display | grid | -| .site-form .admin-list | gap | .5rem | -| .site-form .admin-list li | background | #fdfcfb | -| .site-form .admin-list li | border | 1px solid var(--line) | -| .site-form .admin-list li | border-radius | 10px | -| .site-form .admin-list li | padding | .6rem .9rem | -| .site-form .admin-list li | display | flex | -| .site-form .admin-list li | justify-content | space-between | -| .site-form .admin-list li | align-items | center | -| .site-form .admin-list li | gap | 1rem | -| .site-form .admin-list a | color | var(--accent) | -| .site-form .admin-list a | text-decoration | none | -| .site-form .admin-list a | font-size | .9rem | +从站点根目录授予 fs.read 后调用。实际常量位于 [theme.tables.md](theme.tables.md#表单);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 -*`表单`* +完成后返回*[读取表单的实际 Markdown 常量](document.read_table(path="styles/theme.tables.md", title="表单"))*. ## 响应式 -窄屏收为单栏,导航换行。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 与原字面表一致的数据类型和记录/列式形态 | -`响应式` = +响应式段保留窄屏断点、侧栏流向、内容间距和列表列数。媒体条件仍由原生样式编译器读取,浏览器结果需要实际窄屏验证。 -| 媒体 | 选择器 | 属性 | 值 | -|------|--------|------|-----| -| (max-width: 860px) | body.has-sidebar | grid-template-columns | 1fr | -| (max-width: 860px) | body.has-sidebar | grid-template-areas | "top" "main" "side" "foot" | -| (max-width: 860px) | aside.side | border-right | 0 | -| (max-width: 860px) | aside.side | border-bottom | 1px solid var(--line) | -| (max-width: 860px) | aside.side | padding | 1rem 2rem | -| (max-width: 860px) | ul.side-nav | flex-direction | row | -| (max-width: 860px) | ul.side-nav | flex-wrap | wrap | -| (max-width: 860px) | main.main | padding | 1.75rem 1.25rem 2.5rem | -| (max-width: 860px) | header.topnav | padding | .75rem 1.25rem | -| (max-width: 860px) | footer.foot | padding | 1.2rem 1.25rem | -| (max-width: 860px) | .content.cards | grid-template-columns | 1fr | -| (max-width: 520px) | ul.nav | flex-wrap | wrap | +从站点根目录授予 fs.read 后调用。实际常量位于 [theme.tables.md](theme.tables.md#响应式);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 + +完成后返回*[读取响应式的实际 Markdown 常量](document.read_table(path="styles/theme.tables.md", title="响应式"))*. + +## _编译段 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 名称 | text | 必填 | theme.tables.md 中精确且唯一的样式章节名 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 由所选样式声明编译的 CSS | + +使用`名称`选择一个具有独立职责的声明段,授权 fs.read 和 plugin。字面表读取保留原始选择器、属性和值,原生样式编译器负责媒体条件及 CSS 单元格处理。标题错误会保留文档诊断;此步骤不写文件,也不会把样式附加到浏览器。 + +我们 **数据 = [读取这一段的实际样式常量](document.read_table(path="styles/theme.tables.md", title=`名称`))**。 +完成后返回*[编译所选声明段](web.make_style(name=`名称`, table=`数据`))*. -*`响应式`* ## 全局 -用 样式装配 函数逐个把段落表装配成 CSS,再拼接成完整样式表。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 全部声明段按稳定顺序编译的 CSS 文本 | -**基础表 = > 基础** -**顶栏表 = > 顶栏** -**侧栏表 = > 侧栏** -**主体表 = > 主体** -**卡片表 = > 卡片** -**页脚表 = > 页脚** -**表单表 = > 表单** -**响应式表 = > 响应式** +从站点根授权 fs.read 与 plugin 后调用。名称表保留基础、导航、侧栏、主体、卡片、页脚、表单和断点的原有顺序;每段通过同一编译步骤读取自己的 Markdown 常量。变量声明因此先于使用它们的组件规则,响应式覆盖放在最后。返回值仍是 CSS 文本,保存与资源引用由明确的后续步骤完成。各命名数据函数也继续保留,方便独立检查某个区域。 -**css基础 = > 网页.样式装配 名="基础" 表=`基础表`** -**css顶栏 = > 网页.样式装配 名="顶栏" 表=`顶栏表`** -**css侧栏 = > 网页.样式装配 名="侧栏" 表=`侧栏表`** -**css主体 = > 网页.样式装配 名="主体" 表=`主体表`** -**css卡片 = > 网页.样式装配 名="卡片" 表=`卡片表`** -**css页脚 = > 网页.样式装配 名="页脚" 表=`页脚表`** -**css表单 = > 网页.样式装配 名="表单" 表=`表单表`** -**css响应式 = > 网页.样式装配 名="响应式" 表=`响应式表`** +`names` = -`css段` = +| 名称 | +|---| +| 基础 | +| 顶栏 | +| 侧栏 | +| 主体 | +| 卡片 | +| 页脚 | +| 表单 | +| 响应式 | -| css | -|-----| -| `css基础` | -| `css顶栏` | -| `css侧栏` | -| `css主体` | -| `css卡片` | -| `css页脚` | -| `css表单` | -| `css响应式` | - -**css = > text.str_join xs=`css段` sep=""** -*css* +我们 **parts = [开始有序的 CSS 段列表](table.empty_list())**。 +- [依次编译每个独立声明段](for names as name) + 我们 **css = [编译当前区域](_编译段(名称=`name`))**,并 **parts = [保留覆盖顺序](table.append(list=`parts`, item=`css`))**。 +完成后返回*[按区域顺序连接 CSS](text.str_join(xs=`parts`, sep="\n"))*. diff --git a/examples/marqdo-blog/styles/theme.tables.md b/examples/marqdo-blog/styles/theme.tables.md new file mode 100644 index 0000000..5e19ba9 --- /dev/null +++ b/examples/marqdo-blog/styles/theme.tables.md @@ -0,0 +1,330 @@ +# 博客主题字面样式 + +这里保存原生字面 GFM 数据。调用函数通过 document.read_table 读取所选章节;不会执行本文件中的说明或示例。 + +## 基础 + +基础段声明纸张、文字和强调色变量,以及字体与页面骨架。返回值仍是原生样式表数据,编译与浏览器加载由各自的明确步骤完成。 + +| 选择器 | 属性 | 值 | +|--------|------|-----| +| :root | --ink | #1c1917 | +| :root | --ink-soft | #44403c | +| :root | --muted | #78716c | +| :root | --faint | #a8a29e | +| :root | --paper | #f7f5f2 | +| :root | --card | #ffffff | +| :root | --line | #e7e5e4 | +| :root | --accent | #4f46e5 | +| :root | --accent-2 | #7c3aed | +| :root | --accent-ink | #ffffff | +| :root | --radius | 16px | +| :root | --shadow | 0 1px 2px rgba(28,25,23,.05), 0 8px 24px rgba(28,25,23,.06) | +| :root | --shadow-lg | 0 4px 12px rgba(28,25,23,.08), 0 20px 48px rgba(28,25,23,.12) | +| :root | --serif | "Noto Serif SC", Georgia, "Songti SC", serif | +| :root | --sans | "Noto Sans SC", "IBM Plex Sans", system-ui, -apple-system, sans-serif | +| html | scroll-behavior | smooth | +| * | box-sizing | border-box | +| ::selection | background | rgba(79,70,229,.18) | +| body | margin | 0 | +| body | font-family | var(--sans) | +| body | background | var(--paper) | +| body | color | var(--ink) | +| body | display | grid | +| body | min-height | 100vh | +| body | line-height | 1.7 | +| body | grid-template-rows | auto 1fr auto | +| body.has-sidebar | grid-template-columns | 15rem 1fr | +| body.has-sidebar | grid-template-areas | "top top" "side main" "foot foot" | +| body.no-sidebar | grid-template-areas | "top" "main" "foot" | + +## 顶栏 + +顶栏段保留吸顶导航、磨砂背景、品牌渐变与链接状态。选择器与值都位于数据叶子,调用函数说明用途,避免把整套声明堆进执行流程。 + +| 选择器 | 属性 | 值 | +|--------|------|-----| +| header.topnav | grid-area | top | +| header.topnav | position | sticky | +| header.topnav | top | 0 | +| header.topnav | z-index | 20 | +| header.topnav | background | rgba(255,255,255,.82) | +| header.topnav | backdrop-filter | blur(10px) | +| header.topnav | -webkit-backdrop-filter | blur(10px) | +| header.topnav | border-bottom | 1px solid var(--line) | +| header.topnav | padding | .9rem 2rem | +| header.topnav | display | flex | +| header.topnav | align-items | center | +| header.topnav | justify-content | space-between | +| ul.nav | list-style | none | +| ul.nav | margin | 0 | +| ul.nav | padding | 0 | +| ul.nav | display | flex | +| ul.nav | align-items | center | +| ul.nav | gap | .35rem | +| ul.nav li | margin | 0 | +| ul.nav a | display | inline-block | +| ul.nav a | padding | .45rem .9rem | +| ul.nav a | border-radius | 999px | +| ul.nav a | color | var(--ink-soft) | +| ul.nav a | font-weight | 500 | +| ul.nav a | text-decoration | none | +| ul.nav a | transition | background .18s ease, color .18s ease | +| ul.nav a:hover | background | rgba(79,70,229,.1) | +| ul.nav a:hover | color | var(--accent) | +| ul.nav li:first-child a | font-family | var(--serif) | +| ul.nav li:first-child a | font-size | 1.25rem | +| ul.nav li:first-child a | font-weight | 700 | +| ul.nav li:first-child a | background | linear-gradient(120deg, var(--accent), var(--accent-2)) | +| ul.nav li:first-child a | -webkit-background-clip | text | +| ul.nav li:first-child a | background-clip | text | +| ul.nav li:first-child a | -webkit-text-fill-color | transparent | +| ul.nav li:first-child a | color | transparent | +| ul.nav li:first-child a | padding-left | .2rem | +| ul.nav li:first-child a | padding-right | .2rem | + +## 侧栏 + +侧栏段保留归档面板的布局、链接间距和悬停反馈。它只提供样式数据,具体侧栏内容仍由独立组件或 Document 负责。 + +| 选择器 | 属性 | 值 | +|--------|------|-----| +| aside.side | grid-area | side | +| aside.side | padding | 2rem 1.25rem | +| aside.side | border-right | 1px solid var(--line) | +| aside.side | background | linear-gradient(180deg, #fbfaf8, #f3f1ec) | +| ul.side-nav | list-style | none | +| ul.side-nav | margin | 0 | +| ul.side-nav | padding | 0 | +| ul.side-nav | display | flex | +| ul.side-nav | flex-direction | column | +| ul.side-nav | gap | .25rem | +| ul.side-nav li | margin | 0 | +| ul.side-nav a | display | block | +| ul.side-nav a | padding | .55rem .85rem | +| ul.side-nav a | border-radius | 10px | +| ul.side-nav a | color | var(--ink-soft) | +| ul.side-nav a | text-decoration | none | +| ul.side-nav a | font-weight | 500 | +| ul.side-nav a | transition | background .15s ease, transform .15s ease, color .15s ease | +| ul.side-nav a:hover | background | #fff | +| ul.side-nav a:hover | color | var(--accent) | +| ul.side-nav a:hover | transform | translateX(4px) | +| ul.side-nav a:hover | box-shadow | 0 1px 3px rgba(28,25,23,.08) | + +## 主体 + +主体段定义内容区留白、标题和导语的排版节奏。数据读取保持原有字段和值;主题编译不会替页面构造布局节点。 + +| 选择器 | 属性 | 值 | +|--------|------|-----| +| main.main | grid-area | main | +| main.main | padding | 2.5rem 2.5rem 3.5rem | +| main.main | max-width | 76rem | +| main.main | width | 100% | +| .main-intro | margin-bottom | .5rem | +| .main-intro h1 | font-family | var(--serif) | +| .main-intro h1 | margin | 0 0 .5rem | +| .main-intro h1 | font-size | clamp(2rem, 5vw, 2.9rem) | +| .main-intro h1 | line-height | 1.2 | +| .main-intro h1 | font-weight | 700 | +| .main-intro h1 | letter-spacing | -.01em | +| .main-intro p | color | var(--muted) | +| .main-intro p | margin | 0 | +| .main-intro p | font-size | 1.05rem | + +## 卡片 + +卡片段保留文章列表的网格、阴影、封面和悬停状态。样式类名应与页面输出保持一致;此函数只读取声明,不查询文章数据。 + +| 选择器 | 属性 | 值 | +|--------|------|-----| +| .content.cards | display | grid | +| .content.cards | gap | 1.5rem | +| .content.cards | margin-top | 2rem | +| .content.cards | grid-template-columns | repeat(auto-fill, minmax(17rem, 1fr)) | +| .content.cards article.card | background | var(--card) | +| .content.cards article.card | border | 1px solid var(--line) | +| .content.cards article.card | border-radius | var(--radius) | +| .content.cards article.card | padding | 1.6rem 1.7rem | +| .content.cards article.card | box-shadow | var(--shadow) | +| .content.cards article.card | transition | transform .22s ease, box-shadow .22s ease, border-color .22s ease | +| .content.cards article.card | display | flex | +| .content.cards article.card | flex-direction | column | +| .content.cards article.card | gap | .55rem | +| .content.cards article.card:hover | transform | translateY(-6px) | +| .content.cards article.card:hover | box-shadow | var(--shadow-lg) | +| .content.cards article.card:hover | border-color | rgba(79,70,229,.35) | +| .content.cards a.card-link | text-decoration | none | +| .content.cards a.card-link | color | inherit | +| .content.cards a.card-link | display | flex | +| .content.cards a.card-link | flex-direction | column | +| .content.cards a.card-link | gap | .55rem | +| .content.cards a.card-link | height | 100% | +| .content.cards a.card-link:hover | color | inherit | +| .content.cards h2 | font-family | var(--serif) | +| .content.cards h2 | margin | 0 | +| .content.cards h2 | font-size | 1.35rem | +| .content.cards h2 | line-height | 1.35 | +| .content.cards h2 | font-weight | 700 | +| .content.cards h2 | transition | color .18s ease | +| .content.cards a.card-link:hover h2 | color | var(--accent) | +| .card-meta | font-size | .82rem | +| .card-meta | color | var(--faint) | +| .card-meta | letter-spacing | .04em | +| .card-meta | text-transform | uppercase | +| .card-tag | align-self | flex-start | +| .card-tag | font-size | .78rem | +| .card-tag | color | var(--accent) | +| .card-tag | background | rgba(79,70,229,.08) | +| .card-tag | padding | .15rem .65rem | +| .card-tag | border-radius | 999px | +| .card-tag | font-weight | 600 | +| .content.cards p | color | var(--muted) | +| .content.cards p | margin | 0 | +| .content.cards p | font-size | .95rem | +| .content.cards p | flex | 1 | + +## 页脚 + +页脚段保留页面末尾的留白、分隔线和链接外观。页脚若分为多个布局区域,仍应沿组件目录拆分,样式声明不会代替工程结构。 + +| 选择器 | 属性 | 值 | +|--------|------|-----| +| footer.foot | grid-area | foot | +| footer.foot | padding | 1.4rem 2rem | +| footer.foot | border-top | 1px solid var(--line) | +| footer.foot | color | var(--muted) | +| footer.foot | background | #fff | +| footer.foot | font-size | .9rem | +| footer.foot | display | flex | +| footer.foot | justify-content | space-between | +| footer.foot | align-items | center | +| footer.foot | flex-wrap | wrap | +| footer.foot | gap | .5rem | +| ul.foot-nav | list-style | none | +| ul.foot-nav | margin | 0 | +| ul.foot-nav | padding | 0 | +| ul.foot-nav | display | flex | +| ul.foot-nav | gap | 1rem | +| ul.foot-nav | flex-wrap | wrap | +| ul.foot-nav li | margin | 0 | +| ul.foot-nav a | color | var(--muted) | +| ul.foot-nav a | text-decoration | none | +| ul.foot-nav a:hover | color | var(--accent) | + +## 表单 + +表单段保留输入控件、按钮和管理操作的状态样式。字段校验、保存和鉴权属于数据与安全资源;样式只改变已存在控件的外观。 + +| 选择器 | 属性 | 值 | +|--------|------|-----| +| .site-form | margin-top | 1.75rem | +| .site-form | max-width | 34rem | +| .site-form | background | var(--card) | +| .site-form | border | 1px solid var(--line) | +| .site-form | border-radius | var(--radius) | +| .site-form | padding | 1.8rem | +| .site-form | box-shadow | var(--shadow) | +| .site-form form | display | grid | +| .site-form form | gap | 1rem | +| .site-form label | display | grid | +| .site-form label | gap | .35rem | +| .site-form label | font-size | .92rem | +| .site-form label | font-weight | 600 | +| .site-form label | color | var(--ink-soft) | +| .site-form input | padding | .65rem .8rem | +| .site-form input | border | 1px solid var(--line) | +| .site-form input | border-radius | 10px | +| .site-form input | font | inherit | +| .site-form input | background | #fdfcfb | +| .site-form input | transition | border-color .15s ease, box-shadow .15s ease | +| .site-form textarea | padding | .65rem .8rem | +| .site-form textarea | border | 1px solid var(--line) | +| .site-form textarea | border-radius | 10px | +| .site-form textarea | font | inherit | +| .site-form textarea | background | #fdfcfb | +| .site-form textarea | transition | border-color .15s ease, box-shadow .15s ease | +| .site-form select | padding | .65rem .8rem | +| .site-form select | border | 1px solid var(--line) | +| .site-form select | border-radius | 10px | +| .site-form select | font | inherit | +| .site-form select | background | #fdfcfb | +| .site-form select | transition | border-color .15s ease, box-shadow .15s ease | +| .site-form input:focus | outline | none | +| .site-form input:focus | border-color | var(--accent) | +| .site-form input:focus | box-shadow | 0 0 0 3px rgba(79,70,229,.12) | +| .site-form textarea:focus | outline | none | +| .site-form textarea:focus | border-color | var(--accent) | +| .site-form textarea:focus | box-shadow | 0 0 0 3px rgba(79,70,229,.12) | +| .site-form select:focus | outline | none | +| .site-form select:focus | border-color | var(--accent) | +| .site-form select:focus | box-shadow | 0 0 0 3px rgba(79,70,229,.12) | +| .site-form input[readonly] | background | #f5f5f4 | +| .site-form input[readonly] | color | var(--muted) | +| .site-form textarea | min-height | 10rem | +| .site-form textarea | resize | vertical | +| .site-form .err | color | #b91c1c | +| .site-form .err | font-size | .85rem | +| .site-form .actions | display | flex | +| .site-form .actions | gap | .75rem | +| .site-form .actions | align-items | center | +| .site-form .actions | flex-wrap | wrap | +| .site-form .actions | padding-top | .25rem | +| .site-form button | background | linear-gradient(120deg, var(--accent), var(--accent-2)) | +| .site-form button | color | var(--accent-ink) | +| .site-form button | border | 0 | +| .site-form button | padding | .6rem 1.3rem | +| .site-form button | border-radius | 999px | +| .site-form button | cursor | pointer | +| .site-form button | font-weight | 600 | +| .site-form button | font-size | .95rem | +| .site-form button | transition | opacity .15s ease, transform .15s ease, box-shadow .15s ease | +| .site-form button:hover | opacity | .92 | +| .site-form button:hover | transform | translateY(-1px) | +| .site-form button:hover | box-shadow | 0 6px 18px rgba(79,70,229,.3) | +| .site-form a.btn | display | inline-block | +| .site-form a.btn | padding | .6rem 1.3rem | +| .site-form a.btn | border-radius | 999px | +| .site-form a.btn | border | 1px solid var(--line) | +| .site-form a.btn | color | var(--ink-soft) | +| .site-form a.btn | text-decoration | none | +| .site-form a.btn | font-weight | 500 | +| .site-form a.btn | font-size | .95rem | +| .site-form .meta | color | var(--muted) | +| .site-form .meta | font-size | .9rem | +| .site-form .admin-list | margin | 0 | +| .site-form .admin-list | padding | 0 | +| .site-form .admin-list | list-style | none | +| .site-form .admin-list | display | grid | +| .site-form .admin-list | gap | .5rem | +| .site-form .admin-list li | background | #fdfcfb | +| .site-form .admin-list li | border | 1px solid var(--line) | +| .site-form .admin-list li | border-radius | 10px | +| .site-form .admin-list li | padding | .6rem .9rem | +| .site-form .admin-list li | display | flex | +| .site-form .admin-list li | justify-content | space-between | +| .site-form .admin-list li | align-items | center | +| .site-form .admin-list li | gap | 1rem | +| .site-form .admin-list a | color | var(--accent) | +| .site-form .admin-list a | text-decoration | none | +| .site-form .admin-list a | font-size | .9rem | + +## 响应式 + +响应式段保留窄屏断点、侧栏流向、内容间距和列表列数。媒体条件仍由原生样式编译器读取,浏览器结果需要实际窄屏验证。 + +| 媒体 | 选择器 | 属性 | 值 | +|------|--------|------|-----| +| (max-width: 860px) | body.has-sidebar | grid-template-columns | 1fr | +| (max-width: 860px) | body.has-sidebar | grid-template-areas | "top" "main" "side" "foot" | +| (max-width: 860px) | aside.side | border-right | 0 | +| (max-width: 860px) | aside.side | border-bottom | 1px solid var(--line) | +| (max-width: 860px) | aside.side | padding | 1rem 2rem | +| (max-width: 860px) | ul.side-nav | flex-direction | row | +| (max-width: 860px) | ul.side-nav | flex-wrap | wrap | +| (max-width: 860px) | main.main | padding | 1.75rem 1.25rem 2.5rem | +| (max-width: 860px) | header.topnav | padding | .75rem 1.25rem | +| (max-width: 860px) | footer.foot | padding | 1.2rem 1.25rem | +| (max-width: 860px) | .content.cards | grid-template-columns | 1fr | +| (max-width: 520px) | ul.nav | flex-wrap | wrap | diff --git a/examples/oa2026-showcase/add.mq.md b/examples/oa2026-showcase/add.mq.md index a5d4b7b..5cd757d 100644 --- a/examples/oa2026-showcase/add.mq.md +++ b/examples/oa2026-showcase/add.mq.md @@ -4,11 +4,23 @@ markup: occlusion ## 加一 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| n | any | 必填 | Numeric input advanced or calculated by this example | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | + 对于输入变量`n`,我们执行 **`n` = `n` + 1**,然后把更新后的值作为结果返回 *`n`*。 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 从 41 出发调用「加一」,把结果存进`r`并打印。 -**`r` = > 加一 n=41** -> print text=`r` +我们先**r = [计算并保存 r](加一(n=41))**,供下一步使用。 +随后我们**[显示当前步骤的结果](> print text=`r`)**。 diff --git a/examples/oa2026-showcase/bell.mq.md b/examples/oa2026-showcase/bell.mq.md index dc34002..925bf24 100644 --- a/examples/oa2026-showcase/bell.mq.md +++ b/examples/oa2026-showcase/bell.mq.md @@ -8,6 +8,10 @@ import: # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + 贝尔态:一次可读的量子实验。 我们先做一个假设:如果对第一个量子比特施加 Hadamard 门,再用它控制第二个量子比特翻转, @@ -22,39 +26,39 @@ import: | 1 | H | 0 | | 2 | CX | 0,1 | -**`电路` = > quantum.circuit qubits=2 steps=`步骤`** -**`概率` = > `电路`.probabilities** +We first **电路 = [Compute 电路](quantum.circuit(qubits=2, steps=`步骤`))** for the next step. +We first **概率 = [Compute 概率](> `电路`.probabilities)** for the next step. -> print text=`概率` +We now **[Display this step's result](> print text=`概率`)**. --- 我们期待什么?如果假设成立,`概率`应该只在「00」与「11」上有值,而且各占一半。 先把两个关键概率取出来,读者不必在长映射里找: -**`p00` = [00](access(概率, "00"))** -**`p11` = [11](access(概率, "11"))** +We first **p00 = [00](access(`概率`, "00"))** for the next step. +We first **p11 = [11](access(`概率`, "11"))** for the next step. -> print text=`p00` -> print text=`p11` +We now **[Display this step's result](> print text=`p00`)**. +We now **[Display this step's result](> print text=`p11`)**. 下面的断言不是装饰:如果电路写错,或者门接错,运行会直接失败。 1. `p00` > 0.49 - > print text=bell-00-ok + We now **[Display this step's result](> print text="bell-00-ok")**. 2. * - > print text=bell-00-fail + We now **[Display this step's result](> print text="bell-00-fail")**. 1. `p11` > 0.49 - > print text=bell-11-ok + We now **[Display this step's result](> print text="bell-11-ok")**. 2. * - > print text=bell-11-fail + We now **[Display this step's result](> print text="bell-11-fail")**. --- 图不是截图,而是这份文档运行后生成的派生物。电路图和概率图都来自同一个`电路`。 -**`_` = > `电路`.draw path="bell-circuit.svg" theme="light"** -**`_` = > `电路`.draw kind="probs" path="bell-probs.svg" theme="light"** +We first **_ = [Compute _](> `电路`.draw path="bell-circuit.svg" theme="light")** for the next step. +We first **_ = [Compute _](> `电路`.draw kind="probs" path="bell-probs.svg" theme="light")** for the next step. -> print text=bell-draw-ok +We now **[Display this step's result](> print text="bell-draw-ok")**. diff --git a/examples/oa2026-showcase/calculus.mq.md b/examples/oa2026-showcase/calculus.mq.md index 6f09933..27616a7 100644 --- a/examples/oa2026-showcase/calculus.mq.md +++ b/examples/oa2026-showcase/calculus.mq.md @@ -8,6 +8,10 @@ import: # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + 我们从一条曲线开始。下面这个公式既是排版出来的数学对象, 也是运行时可以直接求导、求根与绘图的`f`。 @@ -18,17 +22,17 @@ $$ 对它求导,得到`df`;再让`df`在 x = 2 处取值,得到切线斜率。 -**`df` = [math.diff] formula=`f` var="x"** -**`slope` = [math.eval] formula=`df` var="x" value=2** -> print text=`df` -> print text=`slope` +We first **df = [Compute df](math.diff(formula=`f`, var="x"))** for the next step. +We first **slope = [Compute slope](math.eval(formula=`df`, var="x", value=2))** for the next step. +We now **[Display this step's result](> print text=`df`)**. +We now **[Display this step's result](> print text=`slope`)**. 曲线与 x 轴的交点同样可以被机器找出来。这里不需要另写一段脚本。 -**`roots` = [math.solve] formula=`f` var="x" min=-3 max=3** -> print text=`roots` +We first **roots = [Compute roots](math.solve(formula=`f`, var="x", min=-3, max=3))** for the next step. +We now **[Display this step's result](> print text=`roots`)**. 最后把公式画成图。图不是截图,而是本文档运行产生的派生物。 -**`_svg` = [math.plot] formula=`f` var="x" min=-3 max=3 path="calculus-plot.svg"** -> print text=plot-ok +We first **_svg = [Compute _svg](math.plot(formula=`f`, var="x", min=-3, max=3, path="calculus-plot.svg"))** for the next step. +We now **[Display this step's result](> print text="plot-ok")**. diff --git a/examples/oa2026-showcase/foreign-node.mq.md b/examples/oa2026-showcase/foreign-node.mq.md index 1b27458..31753d9 100644 --- a/examples/oa2026-showcase/foreign-node.mq.md +++ b/examples/oa2026-showcase/foreign-node.mq.md @@ -1,86 +1,116 @@ --- markup: occlusion -title: 外联:把 Node 当作文档里的计算车间 -description: 一次性执行、持久会话、显式传值,以及可读的结果。 +title: 原生订单分析与 Node Intl 展示边界 import: + native: ../foreign-native-report/index.mq.md foreign: lib/foreign.mq.md + table: lib/table.mq.md + result: lib/result.mq.md --- -# main +订单分析应先使用已经具备的原生能力。只有本地化货币展示交给 Node Intl;一次性执行和持久会话都是明确的外联边界,文件操作与通用数据处理不需要 Python 或外部读取器。 -这份文档要回答一个很具体的问题:同一批订单,按区域汇总之后,总金额分别是多少? -数据已经写在文档里,计算交给 Node,结果回到文档里继续被阅读与断言。 +从仓库根目录调用:`marqdo call examples/oa2026-showcase/foreign-node.mq.md main --require-ok --effects process.exec --fs-root . --json`。只需原生分析时,可直接 call 共享模块的 analyze_orders,不需要任何进程授权。 + +## main + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result:前后两份原生分析、实际排序结果与一次性/持久格式化结果 | + +成功时 value 的字段如下。先检查最外层 ok,再按字段读取;这里列出的数据都是本轮实际计算或执行得到的值。 + +| value 中的字段 | 值的形态 | 直接含义 | +|---|---|---| +| before | 原生分析记录 | 五笔订单的总额 870、数量 5、平均值 174 与按区域保留的统计行 | +| after | 原生分析记录 | 追加八十元订单后,总额 950、数量 6、平均值约 158.3333;不做展示舍入 | +| initial_ranking | 原生行记录列表 | 首轮按区域总额降序排列;每行保留区域、数量、总额、均值与标准化跨度 | +| updated_ranking | 原生行记录列表 | 更新后的区域总额依次为 420、300、230;排序返回新列表 | +| one_shot | 两个展示文本字段 | 一次性进程返回的 total 与 average,只表示首轮报告的本地化展示 | +| persistent_initial | 两个展示文本字段 | 持久格式器对同一首轮报告得到的 total 与 average,可与一次性结果核对 | +| persistent_updated | 两个展示文本字段 | 持久格式器展示更新后的报告;950.00 与 158.33 是展示文本,不覆盖原生数值 | + + +本例先处理五笔订单:总额为八百七十,随后追加一笔华北的八十元订单,总额变为九百五十。分组、计数、平均值、追加和按区域总额排序全部使用 Marqdo 固有能力;不再在 Node 中维护另一份订单分析程序。共享模块中的 analyze_orders 是唯一的分析实现,其参数与字段表可以直接阅读和调用。 + +外联只承担确实缺失的本地化展示。第一次通过本文件的 format_once 演示标准输入上的 JSON 往返;两次共享 format_summary 分别展示原生修改前后的结果。每次共享调用都在同一内核内建立格式器、复用它格式化平均值并关闭资源,实际生命周期写在对应函数中,而不是把一个句柄藏进跨命令的 JSON 字符串。 + +总额排序也保留在原生流程中:先按 total 升序,再反转得到降序记录。排序不会改变原始订单或报告,每个返回行仍包含区域、订单数和总额。追加发生在 Marqdo 集合中,随后将重新计算出的值拷贝给展示边界,避免外部内核与原生数据各保留一份会悄悄分叉的业务状态。 + +调用需要 process.exec 和 Node,不读写用户文件,也不安装包。先检查共享格式化任务的 ok,再使用 value;一次性 JSON 协议失败则保留原生诊断。成功结果携带真正的原生数据和展示字符串,既能继续被其他函数使用,也能核对展示没有替代数值计算。查看返回结果比只读一条“完成”打印更能证明这一轮执行发生了什么。 `订单` = | @ | 区域 | 金额 | -|---|------|------| +|---|---|---| | 1 | 华东 | 120 | | 2 | 华东 | 300 | | 3 | 华南 | 90 | | 4 | 华南 | 140 | | 5 | 华北 | 220 | -先做一次性执行。`foreign.call` 把`订单`编码成 JSON 放到 stdin, -Node 读完、汇总、打印 JSON;外联再把 stdout 解析成 Marqdo 的值。 -没有 shell,也没有隐式的 stdin 约定——传什么、读什么,都写在代码里。 +We **before = [在原生标准库中完成首轮订单分析](native.analyze_orders(orders=`订单`, region_key="区域", amount_key="金额"))** and +**initial_ranking = [保留首轮按区域总额降序的原生行记录](table.reverse(list=table.sort_by(list=access(before, "regions"), key="total")))** and +**one_shot = [只把首轮报告的展示交给一次性进程](format_once(report=`before`))** and +**initial = [用共享持久内核流程展示同一份原生结果](native.format_summary(report=`before`, locale="zh-CN"))**。 +1. not access(`initial`, "ok") + 返回*initial*,保留真实运行失败。 -`汇总代码` = -```javascript -const incoming = JSON.parse(require('fs').readFileSync(0, 'utf8')); +`追加` = -const byRegion = {}; -for (const row of incoming) { - byRegion[row["区域"]] = (byRegion[row["区域"]] || 0) + Number(row["金额"]); -} +| 区域 | 金额 | +|---|---| +| 华北 | 80 | -console.log(JSON.stringify(byRegion)); +We **orders = [在原生集合中追加新订单](table.append(list=`订单`, item=`追加`))** and +**after = [用同一份原生实现重新计算完整报告](native.analyze_orders(orders=`orders`, region_key="区域", amount_key="金额"))** and +**updated_ranking = [在原生集合中保留更新后的降序记录](table.reverse(list=table.sort_by(list=access(after, "regions"), key="total")))** and +**updated = [把更新后的原生结果交给展示边界](native.format_summary(report=`after`, locale="zh-CN"))**。 +1. not access(`updated`, "ok") + 返回*updated*,保留持久内核的失败出口。 +We **persistent_initial = [保留首轮实际格式化文本](access(initial, "value"))** and **persistent_updated = [保留更新后的实际展示文本](access(updated, "value"))**。 + +`观察` = + +| before | after | initial_ranking | updated_ranking | one_shot | persistent_initial | persistent_updated | +|---|---|---|---|---|---|---| +| `before` | `after` | `initial_ranking` | `updated_ranking` | `one_shot` | `persistent_initial` | `persistent_updated` | + +完成原生分析与明确的展示外联后,我们返回*[本次实际观察到的数据与结果](result.ok(value=`观察`))*。 + +## format_once + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| report | map | required | 原生分析结果,包含 total 与 average 数值 | +| locale | text | "zh-CN" | Node Intl 使用的展示语言区域 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 直接返回 total/average 本地化文本;子进程或 JSON 失败保留原生诊断 | + +使用 `report` 和 `locale`="zh-CN" 补足本地化货币展示。一次性外联只接收已经计算好的总额与平均值,不分组、不排序、不修改订单。传入数据由 Marqdo 的 input 通道编码为 JSON;Node 从标准输入流接收它,不读取任何路径,也不额外生成文件。 + +代码围栏明确写出进程如何消费输入、建立 Intl 格式器以及输出唯一的 JSON 记录。标准输出只承载这个协议值,诊断保留在错误通道;混入其他打印会导致 JSON 解析失败,而不是被当作部分成功。这里选择人民币展示,不声称进行汇率换算或货币精度计算。 + +调用需要 process.exec 与已安装的 Node,超时为五秒。foreign.call 在进程失败或输出不是合法 JSON 时给出原生诊断,因此本函数的成功值就是格式化记录,不再套一个假造的通过标记。这个一次性子进程结束后没有可复用状态;持久会话的创建、两次求值和关闭由共享原生报表手册中的 format_summary 展示。 + +`输入` = + +| report | locale | +|---|---| +| `report` | `locale` | + +`格式化代码` = +```node +let raw = ""; +process.stdin.setEncoding("utf8"); +process.stdin.on("data", chunk => { raw += chunk; }); +process.stdin.on("end", () => { + const input = JSON.parse(raw); + const money = new Intl.NumberFormat(input.locale, {style: "currency", currency: "CNY"}); + console.log(JSON.stringify({total: money.format(input.report.total), average: money.format(input.report.average)})); +}); ``` -**`汇总` = > foreign.call code=`汇总代码` input=`订单`** -> print text=`汇总` - ---- - -一次性执行适合「算完就走」。如果想让同一个 Node 内核保留变量, -就显式开启会话、显式设值、显式求值、显式关闭——状态不会藏在某个看不见的 cell 里。 - -**`会话` = > foreign.session_open lang="node"** -**> foreign.session_set id=`会话` name="orders" value=`订单`** - -`排序代码` = -```javascript -const ranked = Object.entries( - orders.reduce((acc, row) => { - acc[row["区域"]] = (acc[row["区域"]] || 0) + Number(row["金额"]); - return acc; - }, {}) -).sort((a, b) => b[1] - a[1]); - -console.log(ranked.map(([region, total]) => `${region}: ${total}`).join("\n")); -``` - -**`第一次` = > foreign.session_eval id=`会话` code=`排序代码`** -> print text=[stdout](access(`第一次`, "stdout")) - -内核状态是持续的。下面这段代码在同一个`orders`上追加一条华北订单, -再重新排序;不需要重新传一遍整张表。 - -`追加代码` = -```javascript -orders.push({ 区域: "华北", 金额: 80 }); - -const rankedAgain = Object.entries( - orders.reduce((acc, row) => { - acc[row["区域"]] = (acc[row["区域"]] || 0) + Number(row["金额"]); - return acc; - }, {}) -).sort((a, b) => b[1] - a[1]); - -console.log(rankedAgain.map(([region, total]) => `${region}: ${total}`).join("\n")); -``` - -**`第二次` = > foreign.session_eval id=`会话` code=`追加代码`** -> print text=[stdout](access(`第二次`, "stdout")) - -**> foreign.session_close id=`会话`** +接收完整输入后,我们返回*[执行有界的一次性展示边界并解析真实 JSON 返回](foreign.call(code=`格式化代码`, input=`输入`, timeout=5))*。 diff --git a/examples/oa2026-showcase/invoice.mq.md b/examples/oa2026-showcase/invoice.mq.md index 541d582..741bfc1 100644 --- a/examples/oa2026-showcase/invoice.mq.md +++ b/examples/oa2026-showcase/invoice.mq.md @@ -6,6 +6,10 @@ description: 叙述、数据、计算与断言共享同一个 .mq.md 源文件 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + 这份文档不是代码旁边的说明,也不是说明里贴的代码。下表既是给人读的订单, 也是运行时直接使用的记录集合;下面的句子既解释业务规则,也参与计算。 @@ -19,27 +23,27 @@ description: 叙述、数据、计算与断言共享同一个 .mq.md 源文件 逐行把「单价 × 数量」累加进`小计`。读者看到的是清单,机器执行的是同一张表。 -**`小计` = 0** +We first **小计 = 0** for the next step. - [行](遍历 订单 为 行) - **`小计` = `小计` + [单价](access(行, "单价")) * [数量](access(行, "数量"))** + We first **小计 = (`小计` + ([单价](access(`行`, "单价")) * [数量](access(`行`, "数量"))))** for the next step. 业务约定写在叙述里:提前不少于七天,整单按九五折;否则原价。 本单最早提前 14 天。 -**`最早提前` = 14** +We first **最早提前 = 14** for the next step. 1. `最早提前` >= 7 - **`折后` = `小计` * 95 / 100** + We first **折后 = ((`小计` * 95) / 100)** for the next step. 2. * - **`折后` = `小计`** + We first **折后 = `小计`** for the next step. 把结果、依据和判断一起写进文档。下面的断言如果跑不通,文档本身就是错的。 -**`含税` = `折后` * 106 / 100** -> print text=`小计` -> print text=`折后` -> print text=`含税` +We first **含税 = ((`折后` * 106) / 100)** for the next step. +We now **[Display this step's result](> print text=`小计`)**. +We now **[Display this step's result](> print text=`折后`)**. +We now **[Display this step's result](> print text=`含税`)**. 1. `含税` < 10000 - > print text=within-cap + We now **[Display this step's result](> print text="within-cap")**. 2. * - > print text=over-cap + We now **[Display this step's result](> print text="over-cap")**. diff --git a/examples/quantum-bell/index.mq.md b/examples/quantum-bell/index.mq.md index 5e145c2..c9e07a0 100644 --- a/examples/quantum-bell/index.mq.md +++ b/examples/quantum-bell/index.mq.md @@ -10,10 +10,15 @@ import: # Bell |Φ+⟩ + H on qubit 0, then CNOT(0→1). Ideal measurement: |00⟩ and |11⟩ each with probability 1/2. # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + `steps` = | step | gate | qubits | @@ -21,9 +26,9 @@ H on qubit 0, then CNOT(0→1). Ideal measurement: |00⟩ and |11⟩ each with p | 1 | H | 0 | | 2 | CX | 0,1 | -**qc = > quantum.circuit qubits=2 steps=`steps`** -**p = > qc.probabilities** -**_ = > qc.draw path="bell.svg"** -**_ = > qc.draw kind="probs" path="bell-probs.svg"** +We first **qc = [Compute qc](quantum.circuit(qubits=2, steps=`steps`))** for the next step. +We first **p = [Compute p](qc.probabilities())** for the next step. +We first **_ = [Compute _](qc.draw(path="bell.svg"))** for the next step. +We first **_ = [Compute _](qc.draw(kind="probs", path="bell-probs.svg"))** for the next step. -> print text=`p` +We now **[Display this step's result](> print text=`p`)**. diff --git a/examples/quantum-entanglement/index.mq.md b/examples/quantum-entanglement/index.mq.md index 4112217..6788179 100644 --- a/examples/quantum-entanglement/index.mq.md +++ b/examples/quantum-entanglement/index.mq.md @@ -9,10 +9,19 @@ import: # Entanglement from a runnable document + Build |Φ⁺⟩ with H then CX. Full-state purity stays 1; tracing out one qubit yields a mixed state (purity 1/2). Schmidt coefficients and entropy quantify the bipartition. SVG plots (hinton / qsphere / multibloch) make the same facts visible. # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + +Prepare a two-qubit Bell state by applying H and then controlled-X. The full density matrix is pure, while tracing out one qubit leaves a mixed reduced state; these are different questions about the same state. The ZZ expectation and Schmidt entropy give complementary checks, not additional measurements of an evolving physical device. + +The five SVG outputs are real artifacts written through the quantum drawing API, so run in a disposable filesystem root with its required plugin and write effects. Their different views share the calculated state. Keep both numeric observations and generated paths when verifying the example; a successful file write alone does not establish the entanglement values. + `steps` = | step | gate | qubits | @@ -20,28 +29,28 @@ Build |Φ⁺⟩ with H then CX. Full-state purity stays 1; tracing out one qubit | 1 | H | 0 | | 2 | CX | 0,1 | -**qc = > quantum.circuit qubits=2 steps=`steps`** -**p = > `qc`.probabilities** +We first **qc = [Compute qc](quantum.circuit(qubits=2, steps=`steps`))** for the next step. +We first **p = [Compute p](> `qc`.probabilities)** for the next step. -**rho = > `qc`.density** -**pur = > `rho`.purity** -**red = > `rho`.partial_trace keep=0** -**rpur = > `red`.purity** +We first **rho = [Compute rho](> `qc`.density)** for the next step. +We first **pur = [Compute pur](> `rho`.purity)** for the next step. +We first **red = [Compute red](> `rho`.partial_trace keep=0)** for the next step. +We first **rpur = [Compute rpur](> `red`.purity)** for the next step. -**zz = "ZZ"** -**ezz = > `qc`.expect obs=`zz`** +We first **zz = "ZZ"** for the next step. +We first **ezz = [Compute ezz](> `qc`.expect obs=`zz`)** for the next step. -**sch = > `qc`.schmidt cut=1** -**ent = [entropy](access(sch, "entropy"))** +We first **sch = [Compute sch](> `qc`.schmidt cut=1)** for the next step. +We first **ent = [entropy](access(`sch`, "entropy"))** for the next step. -**_ = > `qc`.draw path="entangle-circuit.svg" theme="dark"** -**_ = > `qc`.draw kind="hinton" path="entangle-hinton.svg"** -**_ = > `qc`.draw kind="qsphere" path="entangle-qsphere.svg"** -**_ = > `qc`.draw kind="multibloch" path="entangle-multibloch.svg"** -**_ = > `rho`.draw kind="city" path="entangle-city.svg"** +We first **_ = [Compute _](> `qc`.draw path="entangle-circuit.svg" theme="dark")** for the next step. +We first **_ = [Compute _](> `qc`.draw kind="hinton" path="entangle-hinton.svg")** for the next step. +We first **_ = [Compute _](> `qc`.draw kind="qsphere" path="entangle-qsphere.svg")** for the next step. +We first **_ = [Compute _](> `qc`.draw kind="multibloch" path="entangle-multibloch.svg")** for the next step. +We first **_ = [Compute _](> `rho`.draw kind="city" path="entangle-city.svg")** for the next step. -> print text=`p` -> print text=`pur` -> print text=`rpur` -> print text=`ezz` -> print text=`ent` +We now **[Display this step's result](> print text=`p`)**. +We now **[Display this step's result](> print text=`pur`)**. +We now **[Display this step's result](> print text=`rpur`)**. +We now **[Display this step's result](> print text=`ezz`)**. +We now **[Display this step's result](> print text=`ent`)**. diff --git a/examples/quantum-ghz/index.mq.md b/examples/quantum-ghz/index.mq.md index 121ac54..d9e38ef 100644 --- a/examples/quantum-ghz/index.mq.md +++ b/examples/quantum-ghz/index.mq.md @@ -9,10 +9,15 @@ import: # GHZ + H on qubit 0, CX(0→1), CX(0→2). Ideal: |000⟩ and |111⟩ each with probability 1/2. # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + `steps` = | step | gate | qubits | @@ -21,11 +26,11 @@ H on qubit 0, CX(0→1), CX(0→2). Ideal: |000⟩ and |111⟩ each with probabi | 2 | CX | 0,1 | | 3 | CX | 0,2 | -**qc = > quantum.circuit qubits=3 steps=`steps`** -**p = > qc.probabilities** -**_ = > qc.draw path="ghz.svg"** -**_ = > qc.draw kind="probs" path="ghz-probs.svg"** -**H = > gate.gate name="H"** -**_ = > H.draw kind="matrix" path="ghz-h-matrix.svg"** +We first **qc = [Compute qc](quantum.circuit(qubits=3, steps=`steps`))** for the next step. +We first **p = [Compute p](qc.probabilities())** for the next step. +We first **_ = [Compute _](qc.draw(path="ghz.svg"))** for the next step. +We first **_ = [Compute _](qc.draw(kind="probs", path="ghz-probs.svg"))** for the next step. +We first **H = [Compute H](gate.gate(name="H"))** for the next step. +We first **_ = [Compute _](H.draw(kind="matrix", path="ghz-h-matrix.svg"))** for the next step. -> print text=`p` +We now **[Display this step's result](> print text=`p`)**. diff --git a/examples/quantum-skill-call/index.mq.md b/examples/quantum-skill-call/index.mq.md index fb3ae94..9741e9b 100644 --- a/examples/quantum-skill-call/index.mq.md +++ b/examples/quantum-skill-call/index.mq.md @@ -10,12 +10,16 @@ import: # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Build Phi-plus with domain skills, then print ideal probabilities. Prefer the same steps via marqdo call with --effects plugin and toget when an agent drives the session. -**qc = > circuit.new qubits=2 steps=None** -**qc = > circuit.hadamard circuit=`qc` qubit=0** -**qc = > circuit.cnot circuit=`qc` control=0 target=1** -**p = > simulate.probabilities circuit=`qc`** -> print text=`p` +We first **qc = [Compute qc](circuit.new(qubits=2, steps=None))** for the next step. +We first **qc = [Compute qc](circuit.hadamard(circuit=`qc`, qubit=0))** for the next step. +We first **qc = [Compute qc](circuit.cnot(circuit=`qc`, control=0, target=1))** for the next step. +We first **p = [Compute p](simulate.probabilities(circuit=`qc`))** for the next step. +We now **[Display this step's result](> print text=`p`)**. diff --git a/examples/stdlib-handbook/index.mq.md b/examples/stdlib-handbook/index.mq.md index da648ce..36ecfcc 100644 --- a/examples/stdlib-handbook/index.mq.md +++ b/examples/stdlib-handbook/index.mq.md @@ -33,137 +33,168 @@ separate operations, not a transaction. For high-volume inputs use the batched collection transforms; this report uses batch transforms, including grouping and aggregation. ## inventory - + `root` -| 参数 | 类型 | 说明 | -|---|---|---| -| root | text | Directory relative to the granted filesystem root | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| root | text | required | Directory relative to the granted filesystem root | | 返回 | 类型 | 说明 | |---|---|---| | result | list | One path/ok/characters/error record per Markdown file | -Discover Markdown files, then retain each read outcome. A bad UTF-8 document -is represented as an error record; valid documents still contribute counts. +Use `root` under the explicitly granted filesystem root with fs.read. +Discover Markdown files recursively, then preserve each recoverable read outcome. +A bad UTF-8 file has an error record while other documents still contribute +their actual character counts. Discovery does not execute imported source, +Markdown links, code fences or the main function of a discovered document. + +The paths in the returned records are relative to the selected directory; +joining them for a read does not grant access outside --fs-root. Character counts +measure decoded text, not file byte sizes. This distinction matters for Chinese +and other multibyte content. Missing directories and traversal errors retain +native discovery diagnostics; per-file read failures remain ordinary Result data. + +We **names = [Discover Markdown paths below the selected directory](fs.find(path=`root`, pattern="**/*.md"))** and **out = [Start the observed file records](table.empty_list())**. +- [Retain the actual outcome of each independent read](for names as name) + We **file = [Resolve this discovered path under the selected directory](path.join(a=`root`, b=`name`))** and **read = [Read text without aborting other file records](fs.try_read_text(path=`file`))** and **characters = None**. + 1. [This file decoded successfully](access(`read`, "ok")) + We **body = [Read the decoded UTF-8 source](access(read, "value"))** and **characters = [Count text characters rather than bytes](len(`body`))**. + We **success = [Retain the recoverable read state](access(read, "ok"))** and **error = [Keep the original read diagnostic](access(read, "error"))**. -**names = fs.find path=`root` pattern="**/*.md"** -**out = table.empty_list** -- [inspect each discovered file](遍历 names 为 name) - **file = path.join a=`root` b=`name`** - **read = fs.try_read_text path=`file`** - **characters = None** - 1. [read succeeded](access(`read`, "ok")) - **body = access(read, "value")** - **characters = len `body`** - 2. * - **characters = None** - **success = access(read, "ok")** - **error = access(read, "error")** `record` = | path | ok | characters | error | |---|---|---|---| | `name` | `success` | `characters` | `error` | - **out = table.append list=`out` item=`record`** -*out* + We **out = [Retain the successful count or original failure](table.append(list=`out`, item=`record`))**. +After inspecting the selected directory we return *out*. ## summarize_csv - + `text` -| 参数 | 类型 | 说明 | -|---|---|---| -| text | text | Header-based CSV: team, amount and active fields | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Header-based CSV with team, amount and active fields | | 返回 | 类型 | 说明 | |---|---|---| | result | text | CSV with team/total/count for active rows | -CSV cells start as text. Convert them deliberately, select active rows, group -by team, and sum integer amounts with overflow checks. Nothing passes through SQL. +Use `text` as CSV content, not a filename. Parsing begins with text cells. +The visible schema deliberately converts amount to an integer and active to a +boolean before filtering. Only active rows enter grouping; amounts are summed +per team with the table library's integer checks. Invalid cells retain their +conversion diagnostics instead of silently becoming zero. + +The two-column rename record maps the summarizer's key and value fields to team +and total. The final field list fixes exported column order, including count. +No SQL, foreign interpreter, plugin, file or network operation participates. +If input comes from a file, use the native file library before this pure task. +The output is an actual CSV report that another task can write or transmit; +printing it is not required for later Marqdo functions to consume the value. + +We **rows = [Parse the caller-provided CSV text](csv.parse(text=`text`))**. -**rows = csv.parse text=`text`** `schema` = | amount | active | |---|---| -| int | bool | +| "int" | "bool" | + +We **typed = [Convert the business fields before filtering or arithmetic](table.cast(rows=`rows`, schema=`schema`))** and +**selected = [Select only explicitly active records](table.where(list=`typed`, key="active", value=True))** and +**summary = [Sum checked amounts and count records per team](table.summarize(list=`selected`, key="team", field="amount"))**. -**typed = table.cast rows=`rows` schema=`schema`** -**selected = table.where list=`typed` key="active" value=True** -**summary = table.summarize list=`selected` key="team" field="amount"** `names` = | key | value | |---|---| -| team | total | +| "team" | "total" | + +We **renamed = [Name the group key and total for report consumers](table.rename(list=`summary`, fields=`names`))**. -**renamed = table.rename list=`summary` fields=`names`** `fields` = | field | |---| -| team | -| total | -| count | +| "team" | +| "total" | +| "count" | -**report = table.project list=`renamed` keys=`fields`** -*> csv.stringify rows=`report`* +We **report = [Keep an explicit exported column order](table.project(list=`renamed`, keys=`fields`))**. +After the native transforms we return *[Serialize the actual row records as CSV](csv.stringify(rows=`report`))*. ## update_section - + `path` - + `title` - + `body` -| 参数 | 类型 | 说明 | -|---|---|---| -| path | text | Existing Markdown file under the granted root | -| title | text | Exact, unique heading title | -| body | text | Replacement section body, without its heading | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Existing Markdown file under --fs-root | +| title | text | required | Exact unique heading title | +| body | text | required | Replacement section body without its heading | | 返回 | 类型 | 说明 | |---|---|---| -| result | map | Recoverable replacement/write outcome | +| result | map | Recoverable section replacement or checked-write outcome | -Compute the expected digest from the exact source that was read. Transform -only the selected body; fs.write_checked detects stale content before replacing. -Concurrent writers still need coordination: this is not a kernel CAS primitive. +Use `path`, `title` and `body` with fs.write. Read the original UTF-8 +source once and hash that exact text. The document library replaces only the +selected heading body; a missing or ambiguous title remains its failed Result. +The other sections and heading are retained by the structural transform. -**source = fs.read_text path=`path`** -**expected = hash.sha256 text=`source`** -**changed = document.replace_section text=`source` title=`title` body=`body`** -1. [section replacement succeeded](access(`changed`, "ok")) - **next = access(changed, "value")** - *> fs.write_checked path=`path` text=`next` expected_sha256=`expected`* -2. * - *changed* +Write only after a successful transform, passing the observed digest to the +native checked writer. A stale source is refused instead of overwriting an +edit that occurred after review. This is a preflight digest check, not a kernel +CAS or a transaction spanning several files. Concurrent writers still need +coordination, and a source-read policy error is a native diagnostic rather +than a fabricated recoverable success. No external text-processing program +participates in reading, section replacement, hashing or writing. + +We **source = [Read the exact reviewed Markdown source](fs.read_text(path=`path`))** and **expected = [Hash that returned source rather than another read](hash.sha256(text=`source`))** and +**changed = [Replace only the explicitly selected section body](document.replace_section(text=`source`, title=`title`, body=`body`))**. +1. [The structural replacement succeeded](access(`changed`, "ok")) + We **next = [Read the successful document transform](access(changed, "value"))**. + Return *[Refuse drift before writing the reviewed document](fs.write_checked(path=`path`, text=`next`, expected_sha256=`expected`))*. +Return *changed* with its original structural failure. ## demo | 返回 | 类型 | 说明 | |---|---|---| -| result | map | Actual file inventory, CSV report and document update | +| result | map | Observed file inventory, CSV report and actual document update | -Prepare a small valid corpus and an invalid UTF-8 file, then run all three -operations. Validate the returned data; this function never fabricates a pass flag. +Run this complete workflow with fs.write under a disposable --fs-root. +A fresh directory holds one valid Markdown document and one invalid UTF-8 +document. Inventory should preserve both read outcomes. The malformed file is +intentional data for error recovery; it is never imported or executed. + +The CSV sample contains two active team-a amounts and one inactive team-b row. +Its report therefore retains team a with a total of thirty and a count of two. +The section update changes Status while preserving Appendix. After reading +the saved document, normal completion removes this task's own temporary tree; +a failure before cleanup may retain it for diagnosis. Do not remove arbitrary +caller directories to make a test pass. + +The returned record contains these actual values, including the update Result, +so callers can check content and failure details. It is not a fixed compliance +flag and does not claim an atomic transaction across inventory, reporting and +editing. Every operation composes the public native library, with no Python, +shell text processing, JSON construction chain or hidden source-file bridge. + +We **work = [Create a unique directory inside the granted root](fs.temp_dir(prefix="stdlib-demo"))** and +**note = [Name this task own Markdown document](path.join(a=`work`, b="notes.md"))** and **bad = [Name the intentionally invalid text fixture](path.join(a=`work`, b="invalid.md"))**. +We **corpus = "# Notes\n\n## Status\n\nOld status.\n\n# Appendix\n\nKeep this paragraph.\n"** as the complete source that will be edited. +We **[Write the actual starting document](fs.atomic_write(path=`note`, text=`corpus`))** and **binary = [Construct the single invalid UTF-8 byte](bytes.from_base64(text="/w=="))**. +We **[Write the deliberate per-file failure fixture](fs.write_bytes(path=`bad`, data=`binary`))**. +We **files = [Keep both successful and failed native reads](inventory(root=`work`))** and **data = "team,amount,active\na,10,true\nb,4,false\na,20,true\n"**. +We **report = [Run the pure typed aggregation on the visible sample](summarize_csv(text=`data`))** and +**update = [Replace the chosen status section with drift protection](update_section(path=`note`, title="Status", body="Updated through public standard libraries."))** and +**after = [Observe the document that was actually saved](fs.read_text(path=`note`))**. +We **[Remove only this task unique temporary directory](fs.remove_tree(path=`work`))** after the observed results are available. -**work = fs.temp_dir prefix="stdlib-demo"** -**note = path.join a=`work` b="notes.md"** -**bad = path.join a=`work` b="invalid.md"** -**corpus = "# Notes\n\n## Status\n\nOld status.\n\n# Appendix\n\nKeep this paragraph.\n"** -> fs.atomic_write path=`note` text=`corpus` -**binary = bytes.from_base64 text="/w=="** -> fs.write_bytes path=`bad` data=`binary` -**files = inventory root=`work`** -**data = "team,amount,active\na,10,true\nb,4,false\na,20,true\n"** -**report = summarize_csv text=`data`** -**update = update_section path=`note` title="Status" body="Updated through public standard libraries."** -**after = fs.read_text path=`note`** -> fs.remove_tree path=`work` `out` = | inventory | csv | update | document | |---|---|---|---| | `files` | `report` | `update` | `after` | -*out* +After completing these native tasks we return *out*. diff --git a/examples/stdlib-handbook/worker.mq.md b/examples/stdlib-handbook/worker.mq.md index e6cc49b..436f4da 100644 --- a/examples/stdlib-handbook/worker.mq.md +++ b/examples/stdlib-handbook/worker.mq.md @@ -4,6 +4,10 @@ markup: occlusion # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | The value explicitly returned below; conditional returns follow the selected branch | + A file task returns its answer; stdout is not the answer channel. -*17* +After these steps, return *17*. diff --git a/examples/stdlib-handbook/索引.mq.md b/examples/stdlib-handbook/索引.mq.md index 2a70af7..b99b6ff 100644 --- a/examples/stdlib-handbook/索引.mq.md +++ b/examples/stdlib-handbook/索引.mq.md @@ -26,4 +26,4 @@ marqdo call examples/stdlib-handbook/索引.mq.md 演示 --fs-root "$MQ_WORK" -- 执行同源工程,保留所有实际返回数据和失败行为。 -*> practice.demo* +完成上述步骤后,返回*practice.demo()*。 diff --git a/examples/syntax-tour/index.mq.md b/examples/syntax-tour/index.mq.md index 36c6869..0448a62 100644 --- a/examples/syntax-tour/index.mq.md +++ b/examples/syntax-tour/index.mq.md @@ -2,31 +2,47 @@ markup: occlusion import: table: lib/table.mq.md -title: Marqdo 语法全景(v1.6 现状) +title: Marqdo 可读语法全景 description: 一页看完全部现行语法:遮蔽、调用、取值、循环、分支、表格、契约 --- -# main +从仓库根目录执行:`marqdo call examples/syntax-tour/index.mq.md main --effects output.write --json`。 + +## main + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 本次演示实际得到的名字长度、求和结果、嵌套调用值及空载荷值 | + +从本节开始按顺序执行一份完整程序;命令行可以直接 call 本文件的 main 得到计算记录;View 或 run 另行展示打印步骤。call 需要 output.write 授权,因为本例确实执行打印,但它的业务结果以返回记录为准。下方辅助函数也可以按自己的标题独立调用,不需要先理解一套另外维护的工具签名。执行位置中的变量会保存本轮实际结果,说明文字则交代这些结果为什么出现在这里。 + +变量、参数和字段名有不同职责。变量保存已经得到的值,参数把外部输入交给函数,字段名标识记录中的数据;看见同样的文字不能把三者混为一谈。读取已有值时使用反引号,文本字面值加引号,命令选项也遵守这个规则。表格先说明形态,再绑定为值;字段与返回契约则紧接对应标题,帮助读者在看实现前决定如何调用。 + +本例没有文件写入、网络请求或外联解释器。空载荷是刻意保留的教学桩:它返回空值并给出 warning,用来展示待补充逻辑如何被看见,而不是模拟搜索已经完成。默认分支也只是此例选择的业务规则,不代表库能够自行推断所有未知输入。循环会改变示例中的计数变量,返回会立即结束函数,所以所有后续演示都安排在最终返回之前。 + +一列表是列表,一行多列是记录;行记录集合使用首列标记区分。表头标识业务字段,标记列不成为业务值。需要按列保存多行数据时,应明确选择对应形态,不能只凭视觉排列猜运行时结构。 + +程序最后返回真实中间值,便于调用方逐项验证。打印文字是给人观察的另一条通道,不应再被解析成下一步的输入。要改变演示数据,先检查对应契约和索引约定,再重复实际调用;不能仅凭标签读起来正确就认定其中实现符合描述。 —— 1. 变量与插值 —— -**π = 3.14159** -**名 = "Marqdo"** -**开 = True** +我们先**π = 3.14159**,供下一步使用。 +我们先**名 = "Marqdo"**,供下一步使用。 +我们先**开 = True**,供下一步使用。 -> print text=名字是`名`,π 约等于 `π` +随后我们**[显示当前步骤的结果](> print text="名字是`名`,π 约等于 `π`")**。 反引号取值,正文里的反引号是插值: -`长度` = [名字长度](len(`名`)) +我们先**长度 = [名字长度](len(`名`))**,供下一步使用。 -> print text=`名` 的长度是 `长度` +随后我们**[显示当前步骤的结果](> print text="`名` 的长度是 `长度`")**。 —— 2. 函数:参数、返回、契约 —— 税率函数接收档位与金额,返回应缴税额。 -> 计税 档位=2 金额=100 +随后我们**[执行 计税](> 计税 档位=2 金额=100)**。 `税率表` = @@ -36,19 +52,19 @@ description: 一页看完全部现行语法:遮蔽、调用、取值、循环 | 2 | 0.1 | | 3 | 0.2 | -—— 3. 调用的四种形态 —— +—— 3. 调用形式 —— -> print text="形态一:> 前缀 + 具名实参" +随后我们**[显示当前步骤的结果](> print text="形态一:> 前缀 + 具名实参")**。 -**甲 = 加(1 2)** -**乙 = 加(1, 2)** -**丙 = 加(加(1 2), 10)** +我们先**甲 = 加(1 2)**,验证空格分隔的位置参数。 +我们先**乙 = [计算并保存 乙](加(1, 2))**,供下一步使用。 +我们先**丙 = [计算并保存 丙](加(加(1, 2), 10))**,供下一步使用。 **丁 = 加一 号(31)** -> print text=形态二 括号位置实参:`甲` -> print text=形态三 括号逗号:`乙` -> print text=形态四 嵌套:`丙` -> print text=形态五 带空格的函数名:`丁` +随后我们**[显示当前步骤的结果](> print text="形态二 括号位置实参:`甲`")**。 +随后我们**[显示当前步骤的结果](> print text="形态三 括号逗号:`乙`")**。 +随后我们**[显示当前步骤的结果](> print text="形态四 嵌套:`丙`")**。 +随后我们**[显示当前步骤的结果](> print text="形态五 带空格的函数名:`丁`")**。 —— 4. 取值:access / at / get —— @@ -65,54 +81,55 @@ description: 一页看完全部现行语法:遮蔽、调用、取值、循环 |------|------| | 28 | 18 | -`取第一` = [第一颗](access(`篮子`, "1")) -`取配置` = [拿铁多少钱](access(`饮品价`, "拿铁")) -`个数` = [篮子有几颗](table.len(`篮子`)) -`表取` = [用 table.get 读同一个键](table.get(`饮品价`, "美式")) +我们先**取第一 = [第一颗](access(`篮子`, "1"))**,供下一步使用。 +我们先**取配置 = [拿铁多少钱](access(`饮品价`, "拿铁"))**,供下一步使用。 +我们先**个数 = [篮子有几颗](table.len(`篮子`))**,供下一步使用。 +我们先**表取 = [用 table.get 读同一个键](table.get(`饮品价`, "美式"))**,供下一步使用。 -> print text=access 取列表第 1 项:`取第一` -> print text=access 取 Map 的键:`取配置` -> print text=table.len 数个数:`个数` -> print text=table.get 读键:`表取` +随后我们**[显示当前步骤的结果](> print text="access 取列表第 1 项:`取第一`")**。 +随后我们**[显示当前步骤的结果](> print text="access 取 Map 的键:`取配置`")**。 +随后我们**[显示当前步骤的结果](> print text="table.len 数个数:`个数`")**。 +随后我们**[显示当前步骤的结果](> print text="table.get 读键:`表取`")**。 —— 5. 遮蔽:把实现藏进括号 —— 描述给人读,`()` 里才是机器执行的部分。 -写法用 `` `名` = [描述](实现) ``(裸赋值),而不是 `**名 = [描述](实现)**`: -粗体会把描述也包成"代码味",读者一眼看到的是强调而不是人话。 +推荐把赋值写进叙述句:`先**值 = [取得需要的结果](实际表达式)**,再使用这个值。` +粗体给出执行位置,方括号解释意图,圆括号保留实际逻辑。三者共同形成可读程序; +普通正文里的导航链接不会因此自动执行。下方也保留表格绑定形式,方便比较数据与操作的职责。 -`留存` = [客户留存率,模拟数据](0.42) +我们先**留存 = [客户留存率,模拟数据](0.42)**,供下一步使用。 -> print text=遮蔽的值:`留存` +随后我们**[显示当前步骤的结果](> print text="遮蔽的值:`留存`")**。 未接通的功能用空载荷申报(会得到一条 warning,提醒写清返回值): -`待接` = [搜索接入,接口未接,待开发]() +我们先**待接 = [搜索接入,接口未接,待开发]()**,供下一步使用。 -> print text=空载荷桩的值:`待接` +随后我们**[显示当前步骤的结果](> print text="空载荷桩的值:`待接`")**。 —— 6. 循环 —— - [篮子里的每个果子](遍历 `篮子` 为 `果`) - > print text=果子:`果` + 随后我们**[显示当前步骤的结果](> print text="果子:`果`")**。 -`n` = 3 +我们先**n = 3**,供下一步使用。 - `n` > 0 - > print text=倒数 `n` - **n = n - 1** + 随后我们**[显示当前步骤的结果](> print text="倒数 `n`")**。 + 我们先**n = (`n` - 1)**,供下一步使用。 —— 7. 分支 —— -**分数 = 86** +我们先**分数 = 86**,供下一步使用。 1. `分数` >= 90 - > print text=等级 A + 随后我们**[显示当前步骤的结果](> print text="等级 A")**。 2. `分数` >= 60 - > print text=等级 B + 随后我们**[显示当前步骤的结果](> print text="等级 B")**。 3. * - > print text=等级 C + 随后我们**[显示当前步骤的结果](> print text="等级 C")**。 —— 8. 表格的三态 —— @@ -143,47 +160,81 @@ description: 一页看完全部现行语法:遮蔽、调用、取值、循环 | 2 | 梨 | 3 | - [每条订单](遍历 `订单` 为 `单`) - > print text=订单:`单` + 随后我们**[显示当前步骤的结果](> print text="订单:`单`")**。 -> print text=配置超时是 `配置` +随后我们**[显示当前步骤的结果](> print text="配置超时是 `配置`")**。 —— 9. 值类型 —— -**整数 = 42** -**小数 = 1.5** -**真值 = True** -**空值 = None** -**串 = "引号里的文本"** +我们先**整数 = 42**,供下一步使用。 +我们先**小数 = 1.5**,供下一步使用。 +我们先**真值 = True**,供下一步使用。 +我们先**空值 = None**,供下一步使用。 +我们先**串 = "引号里的文本"**,供下一步使用。 -> print text=整数 `整数` 小数 `小数` 真值 `真值` 空值 `空值` -> print text=`串` +随后我们**[显示当前步骤的结果](> print text="整数 `整数` 小数 `小数` 真值 `真值` 空值 `空值`")**。 +随后我们**[显示当前步骤的结果](> print text=`串`)**。 —— 10. 收尾 —— -> print text="以上全部可执行;描述只是描述,机器只跑括号里的东西。" +随后我们**[显示当前步骤的结果](> print text="演示结束:执行位置决定是否运行,动作标签说明目的,括号保存实际逻辑。")**。 +`summary` = + +| name_length | sum | comma_sum | nested_sum | spaced_name | unfinished | +|---|---|---|---|---|---| +| `长度` | `甲` | `乙` | `丙` | `丁` | `待接` | + +完成所有演示后,我们返回*summary*,供调用方直接检查数值与未完成项。 ## 计税 - + `档位` - + `金额` -**率 = 0.1** +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 档位 | any | required | 税率档位;1 取 3%,3 取 20%,其他值沿用本例 10% | +| 金额 | any | required | 待计税金额;需要支持与选定税率相乘 | +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 金额乘以本例选定税率;不包含额外舍入 | + +输入`档位`与`金额`,先按明确的分支选择税率,再计算同一份输入的税额。这是教学规则,不读取外部税表,也不把未知档位推断成新的税率。返回值由乘法得到,调用方根据自己的金额单位继续处理。 + +本函数不做货币舍入、不写日志或文件。普通数值可以直接传入;不支持乘法的值保留原生诊断,而不是悄悄当作零。观察选中哪个分支,比只看最后的打印标记更容易核对规则。 + +先**率 = 0.1**作为本例的默认税率。 1. `档位` == 1 - **率 = 0.03** + 此档位使用**率 = 0.03**。 2. `档位` == 3 - **率 = 0.2** + 此档位使用**率 = 0.2**。 3. * - **率 = 0.1** - -*`金额` * `率`* + 其余输入沿用**率 = 0.1**。 +选定税率后,我们返回*[按本例规则计算税额](金额 * 率)*。 ## 加 - + `a` - + `b` -*`a` + `b`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | 左操作数;与 b 使用兼容的加法语义 | +| b | any | required | 右操作数;与 a 使用兼容的加法语义 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 两个操作数按原生加法语义得到的新值 | + +输入`a`和`b`,直接组合两个已提供的值。本例用整数调用以展示位置实参、逗号分隔和嵌套调用;函数不会修改调用者变量,也不读取打印输出。需要类型转换时在调用前显式完成,不让这个简单函数猜测字符串是否代表数字。 + +得到两个输入后,我们返回*[按相同规则相加两个操作数](a + b)*。 ## 加一 号 - + `n` -*`n` + 1* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| n | any | required | 参与加一的输入值;本例以数字演示 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 输入加一的新值,函数名中的空格仍保留 | + +输入`n`之后,按原生加法与一相加。这个函数刻意保留带空格的名称,以展示可读名称与命令行参数引用之间的关系。调用者仍通过完整标题定位它;空格不代表参数,也不需要额外的隐藏入口。 + +完成这次计算后,我们返回*[把输入推进一位](n + 1)*。 diff --git a/examples/web-client-site/serve.mq.md b/examples/web-client-site/serve.mq.md index 1736a9e..5771872 100644 --- a/examples/web-client-site/serve.mq.md +++ b/examples/web-client-site/serve.mq.md @@ -7,6 +7,10 @@ import: # main -**`embed` = > web.client_embed source="/static/client.mq.md"** -> print text=embed-ready -> web.serve root="." host="127.0.0.1" port=18090 static_dir="static" +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + +We first **embed = [Compute embed](web.client_embed(source="/static/client.mq.md"))** for the next step. +We now **[Display this step's result](> print text="embed-ready")**. +We now **[Call web.serve](> web.serve root="." host="127.0.0.1" port=18090 static_dir="static")**. diff --git a/examples/web-client-site/static/client.mq.md b/examples/web-client-site/static/client.mq.md index 929618f..a65f600 100644 --- a/examples/web-client-site/static/client.mq.md +++ b/examples/web-client-site/static/client.mq.md @@ -9,7 +9,15 @@ import: # main -**`count` = 0** +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | The value explicitly returned below; conditional returns follow the selected branch | + +This client module starts one counter, registers bump/reset controls and returns a ready message with the wire table. The server-side page supplies #bump, #reset, #count and #log; the client does not build a second page from raw HTML. + +The browser bridge applies the returned instructions and preserves state between callbacks. Initial readiness only shows that mounting occurred. Verify a click and reset separately to check the counter behavior, and keep selector names aligned with the page's Markdown view structure. + +We first **count = 0** for the next step. `wire` = @@ -18,15 +26,29 @@ import: | 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* +We first **ready = [Compute ready](browser.set_text(sel="#log", text="client.mq.md ready"))** for the next step. +We first **boot = [Compute boot](table.put(in=None, at="wire", value=`wire`))** for the next step. +After these steps, return *browser.merge(a=`boot`, b=`ready`)*. ## bump -**`count` = count + 1** -**`label` = > str count** -*> browser.set_text sel="#count" text=label* + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | A plain set_text instruction with the next counter value | + +This click callback reads the count already retained by the browser session. It takes no event input and does not ask the caller to supply the current state. After incrementing the native integer, convert it to text for the existing count target. Returning an instruction still relies on the official bridge to update the visible page. + +We **count = count + 1** and **label = [Convert the updated native count to text](str(count))**. +Return *[Display this session's new count](browser.set_text(sel="#count", text=`label`))*. + ## reset -**`count` = 0** -*> browser.set_text sel="#count" text="0"* + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | A plain set_text instruction showing zero | + +Reset changes the same session count used by bump. It takes no argument and does not create a new browser instance. The displayed text and retained integer are set together, so the next bump should show one. The callback describes a DOM effect and performs no direct server or file operation. + +We **count = 0** before describing the visible result. +Return *[Show the reset state](browser.set_text(sel="#count", text="0"))*. diff --git a/examples/web-collab-doc/README.md b/examples/web-collab-doc/README.md index dafce54..937250d 100644 --- a/examples/web-collab-doc/README.md +++ b/examples/web-collab-doc/README.md @@ -1,12 +1,16 @@ # web-collab-doc -Two-browser collaborative notepad over WebSocket room (last-write-wins text). +这个工程演示同源 WebSocket 房间中的双浏览器记事本。客户端发送完整文本快照,收到的较新消息覆盖本地内容;它不实现 CRDT、离线合并或持久化历史。服务只在本机演示端口提供匿名房间,部署前应配置真实鉴权。 -```bash -marqdo wasm build -o examples/web-collab-doc/static -cd examples/web-collab-doc -marqdo run index.mq.md -# open http://127.0.0.1:18094 twice +从仓库根目录构建当前浏览器运行时,再启动服务: + +```sh +marqdo call skills/marqdo-dev/index.mq.md build_browser 'out="examples/web-collab-doc/static"' --effects plugin,process.exec,fs.write --fs-root . --require-ok --json +marqdo call examples/web-collab-doc/index.mq.md serve --effects plugin,fs.read,network.write --fs-root . --json ``` -Design: [ext-web-collab.md](../../doc/design/ext-web-collab.md). +打开 http://127.0.0.1:18094 两次,在任一窗口编辑文本。另一窗口收到快照后仍可继续本地编辑,空文本也是有效快照。构建缺少兼容 WASM 目标时,先按 [工具链手册](../../skills/marqdo-dev/toolchain.mq.md) 准备工作区编译器,把返回的 compiler 传给 build_browser。 + +入口 [index.mq.md](index.mq.md) 负责页面发现与房间绑定;[home.mq.md](home.mq.md) 组合说明、编辑器和状态,末端内容与控件分别可读;[客户端](static/client.mq.md) 直接表达输入、消息和在线状态处理。 + +[开发手册](../../skills/marqdo-dev/index.mq.md) 的 test_browser 使用当前构建运行真实双页交互,覆盖远端更新后的下一次本地输入、空文本与在线状态。设计背景见 [协作设计](../../doc/design/ext-web-collab.md)。 diff --git a/examples/web-collab-doc/editor.mq.md b/examples/web-collab-doc/editor.mq.md new file mode 100644 index 0000000..97f7aa2 --- /dev/null +++ b/examples/web-collab-doc/editor.mq.md @@ -0,0 +1,28 @@ +--- +markup: occlusion +title: Native collaborative editor leaf +import: + component: ext/web/component/index.mq.md + table: lib/table.mq.md +--- + +This intrinsic label/textarea pair contains no socket, page shell or generated HTML. + +## nodes + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Accessible native multiline editor rows | + +The label names the same doc id used by the client input binding. Rows and columns are typed native attributes rather than interpolated markup. Initial content is empty and ordinary text; the bridge later changes its value. Geometry outside this intrinsic field pair belongs to the parent page component. + +We **label_attrs = [Associate the visible label with the editor](table.put(in=None, at="for", value="doc"))** and **label = [Describe the plain editor label](component.element(kind="label", value="Shared text", attrs=`label_attrs`, slot="editor-label"))**. + +`attrs` = + +| id | rows | cols | aria-label | +|---|---|---|---| +| doc | 16 | 72 | Shared text | + +We **editor = [Describe the native multiline control](component.element(kind="textarea", attrs=`attrs`, slot="editor"))**. +Return *[Keep the field label before its native control](table.concat(a=`label`, b=`editor`))*. diff --git a/examples/web-collab-doc/home.mq.md b/examples/web-collab-doc/home.mq.md new file mode 100644 index 0000000..42d1bb0 --- /dev/null +++ b/examples/web-collab-doc/home.mq.md @@ -0,0 +1,25 @@ +--- +markup: occlusion +title: Collaborative page assembly +import: + component: ext/web/component/index.mq.md + client: ext/web/client/index.mq.md + editor: editor.mq.md + status: status.mq.md + fs: lib/fs.mq.md + table: lib/table.mq.md +--- + +The page composes a terminal Markdown introduction, intrinsic native controls and an official runtime Resource. + +## nodes + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Complete structured collaborative page | + +The introduction is read as ordinary Markdown from intro.md within the granted site root. The editor and status are independent control leaves, while the script Resource refers to the actual built bridge and WASM files. This assembly describes one page and starts no server or socket. Transport policy remains in serve and client behavior remains in static/client.mq.md. + +We **text = [Read the terminal Markdown introduction](fs.read_text(path="intro.md"))** and **intro = [Describe the introduction as Markdown](component.markdown(text=`text`, slot="intro"))** and **field = [Assemble the independent native editor](editor.nodes())** and **feedback = [Assemble presence and connection status](status.nodes())** and **runtime = [Reference the official client program](client.nodes(source="/static/client.mq.md"))**. +We **body = [Keep introduction before the editor](table.concat(a=`intro`, b=`field`))** and **visible = [Place independent feedback after the field](table.concat(a=`body`, b=`feedback`))**. +Return *[Retain runtime loading as a separate resource](table.concat(a=`visible`, b=`runtime`))*. diff --git a/examples/web-collab-doc/index.mq.md b/examples/web-collab-doc/index.mq.md index c90e9fc..57a74b3 100644 --- a/examples/web-collab-doc/index.mq.md +++ b/examples/web-collab-doc/index.mq.md @@ -1,26 +1,39 @@ --- markup: occlusion -title: web-collab-doc -description: Two-browser collaborative plain-text editor over WS room (LWW snapshot sync) +type: web +view: main +route: / +title: Collaborative document — declared layout and room Resource import: + home: home.mq.md web: ext/web/web.mq.md + socket: ext/net/websocket.mq.md --- -# main +Open two controlled browser tabs to observe complete text snapshots and room presence. This loopback demonstration explicitly permits anonymous room access. It is not durable storage, a CRDT or a history replay service. Build the current browser assets into static before serving. -Collaborative notepad: open the page in two browsers; edits fan out via -`/live/{room}` WebSocket (mode=room + presence). Build WASM first: +## main -``` -marqdo wasm build -o examples/web-collab-doc/static -``` +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Collaborative page View rows | -**`embed` = > web.client_embed bridge="/static/marqdo-bridge.js" wasm="/static/marqdo_wasm.wasm" source="/static/client.mq.md" boot=True** +The Document delegates to the readable page assembly. Follow its imports to the Markdown introduction, native editor and status leaves; none assembles a raw HTML shell. The bridge is a structured Resource. Page assembly reads the selected site root and returns structure before any listener starts. -**`intro` = "

      Room demo · open twice to co-edit.

      presence: —

      " + embed**
      +Return *[Assemble the native collaborative page](home.nodes())*.
       
      -**page = > web.page title="Collab doc" intro=intro layout="bare"**
      -**app = > web.app page=page host="127.0.0.1" port=18094**
      -**app = > app.static dir="static" mount="/static"**
      -**app = > `app`.route_ws path="/live/{id}" mode="room" room_key="doc.{id}" presence=True**
      -> `app`.listen
      +## serve
      +
      +| 参数 | 类型 | 默认 | 说明 |
      +|---|---|---|---|
      +| root | text | "examples/web-collab-doc" | Explicit site directory relative to the checkout root |
      +| port | number | 18094 | Loopback server port |
      +
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| result | map | Blocking listener for the declared page and collaboration room |
      +
      +Use `root`="examples/web-collab-doc" and `port`=18094. Prepare the page and static mount, bind the network-owned /live/{id} room and its presence channel, then listen with the retained site context. Anonymous access is deliberate for this localhost demonstration; a deployed application should attach authentication and retain private room defaults. The client uses a relative WebSocket address, so changing this port keeps the same page/client contract.
      +
      +We **app = [Discover the page and its static resources](web.prepare(root=`root`, host="127.0.0.1", port=`port`, static_dir="static"))** and **app = [Bind the declared snapshot and presence room](socket.route(app=`app`, path="/live/{id}", mode="room", room_key="doc.{id}", presence=True, require_auth=False))**.
      +Return *[Listen after layout and transport are ready](web.listen(app=`app`))*.
      diff --git a/examples/web-collab-doc/intro.md b/examples/web-collab-doc/intro.md
      new file mode 100644
      index 0000000..0ebd7a1
      --- /dev/null
      +++ b/examples/web-collab-doc/intro.md
      @@ -0,0 +1,5 @@
      +# Shared notepad
      +
      +Open this page in **two browser tabs**. Both join `/live/demo` and display native room presence.
      +
      +Each edit sends a complete text snapshot. The last received snapshot wins; this demonstration does not store document history or synchronize edits as a CRDT.
      diff --git a/examples/web-collab-doc/static/client.mq.md b/examples/web-collab-doc/static/client.mq.md
      index 816348f..02ef459 100644
      --- a/examples/web-collab-doc/static/client.mq.md
      +++ b/examples/web-collab-doc/static/client.mq.md
      @@ -1,87 +1,124 @@
       ---
       markup: occlusion
      -title: collab client
      -description: LWW text sync over WS room + presence (DOC\\t protocol)
      +title: Collaborative client — native text snapshots and presence
       import:
         browser: lib/browser.mq.md
         table: lib/table.mq.md
         text: lib/text.mq.md
       ---
       
      +This program owns document text and event transitions. The Document supplies the native textarea and status leaves; the network resource supplies a same-origin room. All business state stays in Marqdo.
      +
       # main
       
      -**`ws_id` = "doc"**
      -**`applying` = False**
      -**`doc` = ""**
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| result | map | Client wiring, room connection and initial status effects |
      +
      +The client keeps only the last locally observed document text in native entry state. Each edit sends a complete DOC-tab-text snapshot; this is a last-received-message demonstration, not a CRDT, document database or history synchronization service. The relative socket path follows the page's host and port, so a different loopback listen port does not require editing client code. Presence and document messages use separate displayed targets. The official bridge changes textarea.value without emitting a new input event, so applying remote text needs no flag that would discard the next real local edit. BrowserSession retains entry bindings between event callbacks.
      +
      +We **ws_id = "doc"** and **doc = ""** before connecting.
       
       `wire` =
       
       | @ | 选择器 | 事件 | 调用 | 值选择器 |
      -|---|--------|------|------|----------|
      +|---|---|---|---|---|
       | 1 | "#doc" | input | on_edit | "#doc" |
       
       `open` =
       
       | op | id | url | then_open | then_message | then_error | then_close |
      -|----|----|-----|-----------|--------------|------------|------------|
      -| open | `ws_id` | "ws://127.0.0.1:18094/live/demo" | on_open | on_msg | on_err | on_close |
      +|---|---|---|---|---|---|---|
      +| open | `ws_id` | /live/demo | on_open | on_msg | on_err | on_close |
       
      -**`w` = > table.put in=None at="wire" value=wire**
      -**`ws` = > browser.ws spec=open**
      -**`boot` = > browser.merge a=w b=ws**
      -**`ready` = > browser.set_text sel="#log" text="connecting…"**
      -*> browser.merge a=boot b=ready*
      +We **wiring = [Bind the existing native textarea](table.put(in=None, at="wire", value=`wire`))** and **socket = [Describe the same-origin room connection](browser.ws(spec=`open`))** and **boot = [Keep wiring and transport together](browser.merge(a=`wiring`, b=`socket`))** and **ready = [Describe the initial connection status](browser.set_text(sel="#log", text="connecting…"))**.
      +Return *[Keep initial status with the boot instructions](browser.merge(a=`boot`, b=`ready`))*.
       
       ## on_open
      -    + `ok`=True
       
      -*> browser.set_text sel="#log" text="ws open · room demo"*
      +| 参数 | 类型 | 默认 | 说明 |
      +|---|---|---|---|
      +| ok | bool | True | Success flag from the bridge's open callback |
      +
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| result | map | Plain connection status effect |
      +
      +Use `ok`=True from the open callback. A successful transport opening says that the room is connected; it does not prove that previous document content was replayed. This callback updates only the log. Presence frames arrive independently through on_msg, and actual editing remains available through the existing textarea binding.
      +
      +1. `ok`
      +  Return *[Show that the native room connection opened](browser.set_text(sel="#log", text="ws open · room demo"))*.
      +Return *[Keep an unsuccessful open visible](browser.set_text(sel="#log", text="ws open failed"))*.
       
       ## on_err
      -    + `error`=""
       
      -**`msg` = "ws error: " + error**
      -*> browser.set_text sel="#log" text=msg*
      +| 参数 | 类型 | 默认 | 说明 |
      +|---|---|---|---|
      +| error | text | "" | Error text supplied by the browser transport |
      +
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| result | map | Plain error text effect |
      +
      +Use `error`="" from the bridge. Preserve its text in the status log rather than treating a failed connection as an empty successful document. This callback neither rewrites shared text nor retries a send, so the caller can observe the actual transport state without a hidden duplicate update.
      +
      +We **message = "ws error: " + error**.
      +Return *[Display the actual transport failure as text](browser.set_text(sel="#log", text=`message`))*.
       
       ## on_close
      -*> browser.set_text sel="#log" text="ws closed"*
      +
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| result | map | Closed connection status effect |
      +
      +A close notification updates the log while retaining the last displayed document text. This demonstration does not silently reconnect or persist data elsewhere. Reopening the page starts a fresh client session, and subsequent edits need a live socket before peers can receive them.
      +
      +Return *[Keep closure visible beside the editor](browser.set_text(sel="#log", text="ws closed"))*.
       
       ## on_edit
      -    + `value`=""
       
      -1. `applying`
      -    **`applying` = False**
      -    ****
      -2. *
      -    **`doc` = value**
      -    **`payload` = "DOC\t" + value**
      -    `send` =
      +| 参数 | 类型 | 默认 | 说明 |
      +|---|---|---|---|
      +| value | text | "" | Current plain textarea contents, including an intentionally empty document |
       
      -    | op | id | data |
      -    |----|----|------|
      -    | send | `ws_id` | `payload` |
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| result | any | One complete snapshot send instruction, or None for unchanged text |
       
      -    *> browser.ws spec=send*
      +Use `value`="" from the input binding. A changed value replaces the native observed text and becomes one DOC-tab snapshot; an empty value is a valid deletion, not a missing edit. Identical input produces no send. Incoming set_value effects do not emit input, so the next real user edit after a remote update must be sent immediately. The callback describes a browser WebSocket action and opens no native socket itself.
      +
      +1. `value` == `doc`
      +  Return *None* because the observed text is unchanged.
      +We **doc = [Retain the complete new native text](value)** and **payload = "DOC\t" + value**.
      +
      +`send` =
      +
      +| op | id | data |
      +|---|---|---|
      +| send | `ws_id` | `payload` |
      +
      +Return *[Send the complete snapshot through the existing room connection](browser.ws(spec=`send`))*.
       
       ## on_msg
      -    + `data`=""
       
      -1. `data` != ""
      -    **`is_pres` = > text.starts_with text=data prefix="{"**
      -    1. `is_pres`
      -        **`msg` = "presence: " + data**
      -        *> browser.set_text sel="#presence" text=msg*
      -    2. *
      -        **`is_doc` = > text.starts_with text=data prefix="DOC\t"**
      -        1. `is_doc`
      -            **`remote` = > text.replace text=data old="DOC\t" new="" count=1**
      -            1. `remote` != `doc`
      -                **`doc` = remote**
      -                **`applying` = True**
      -                *> browser.set_value sel="#doc" value=remote*
      -            2. *
      -                ****
      -        2. *
      -            ****
      -2. *
      -    ****
      +| 参数 | 类型 | 默认 | 说明 |
      +|---|---|---|---|
      +| data | text | "" | One text frame from the room or its presence channel |
      +
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| result | any | Presence text, a remote textarea value, or None for ignored/echoed frames |
      +
      +Use `data`="" from the transport callback. Presence records are displayed separately and never interpreted as document text. A DOC-tab frame contains the entire replacement document, including a possible empty string. Retain that observed text before returning its set_value instruction; an echoed snapshot equal to local state then becomes a no-op. Unknown messages and empty frames leave content unchanged. No JavaScript, HTML or external interpreter parses the document payload.
      +
      +1. `data` == ""
      +  Return *None* for an empty frame.
      +1. [A native presence record](text.starts_with(text=`data`, prefix="{"))
      +  We **message = "presence: " + data**.
      +  Return *[Display room presence independently](browser.set_text(sel="#presence", text=`message`))*.
      +1. [A complete document snapshot](text.starts_with(text=`data`, prefix="DOC\t"))
      +  We **remote = [Remove only the leading protocol marker](text.replace(text=`data`, old="DOC\t", new="", count=1))**.
      +  1. `remote` != `doc`
      +    We **doc = [Retain the received native text](remote)**.
      +    Return *[Apply remote text without manufacturing an input event](browser.set_value(sel="#doc", value=`remote`))*.
      +Otherwise return *None* for unrelated frames or an already observed snapshot.
      diff --git a/examples/web-collab-doc/status.mq.md b/examples/web-collab-doc/status.mq.md
      new file mode 100644
      index 0000000..7a2df21
      --- /dev/null
      +++ b/examples/web-collab-doc/status.mq.md
      @@ -0,0 +1,32 @@
      +---
      +markup: occlusion
      +title: Presence and transport status leaves
      +import:
      +  component: ext/web/component/index.mq.md
      +  table: lib/table.mq.md
      +---
      +
      +Presence information and connection diagnostics have separate native text targets.
      +
      +## nodes
      +
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| result | list | Ordered presence and log leaves |
      +
      +Presence frames update one plain-text region, while connection lifecycle messages update a preformatted log. Their stable ids match client callbacks, and neither contains document text or performs transport operations. The parent places these leaves around the independent editor; messages are escaped by the native renderer and later set_text effects.
      +
      +`presence_attrs` =
      +
      +| id | role | aria-live |
      +|---|---|---|
      +| presence | status | polite |
      +
      +`log_attrs` =
      +
      +| id | role |
      +|---|---|
      +| log | log |
      +
      +We **presence = [Describe the plain presence target](component.element(kind="text", value="Waiting for peers.", attrs=`presence_attrs`, slot="presence"))** and **log = [Describe connection feedback separately](component.element(kind="pre", value="connecting…", attrs=`log_attrs`, slot="log"))**.
      +Return *[Keep presence before transport feedback](table.concat(a=`presence`, b=`log`))*.
      diff --git a/examples/web-layout-handbook-zh/api/ping.mq.md b/examples/web-layout-handbook-zh/api/ping.mq.md
      index 684ef31..bee4f0c 100644
      --- a/examples/web-layout-handbook-zh/api/ping.mq.md
      +++ b/examples/web-layout-handbook-zh/api/ping.mq.md
      @@ -9,10 +9,14 @@ markup: occlusion
       
       # main
       
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| result | any | The value explicitly returned below; conditional returns follow the selected branch |
      +
       `result` =
       
       | ok | ping |
       |----|------|
       | True | pong |
       
      -*result*
      +After these steps, return *result*.
      diff --git a/examples/web-layout-handbook-zh/components/footer/brand/index.mq.md b/examples/web-layout-handbook-zh/components/footer/brand/index.mq.md
      index 1222668..e945e6f 100644
      --- a/examples/web-layout-handbook-zh/components/footer/brand/index.mq.md
      +++ b/examples/web-layout-handbook-zh/components/footer/brand/index.mq.md
      @@ -14,5 +14,5 @@ import:
       此叶子只负责footer/brand 的 Markdown 内容,父组件决定排列。修改文字只改相邻 content.md,
       不添加 HTML 标签或内部分栏;出现第二种布局职责时再开子目录。
       
      -**body = 文件.读文本 路径="components/footer/brand/content.md"**
      -*> 组件.正文 文本=`body` 槽="footer-brand"*
      +We first **body = [Compute body](文件.读文本(路径="components/footer/brand/content.md"))** for the next step.
      +After these steps, return *组件.正文(文本=`body`, 槽="footer-brand")*.
      diff --git a/examples/web-layout-handbook-zh/components/footer/index.mq.md b/examples/web-layout-handbook-zh/components/footer/index.mq.md
      index 0a69fd8..c264b90 100644
      --- a/examples/web-layout-handbook-zh/components/footer/index.mq.md
      +++ b/examples/web-layout-handbook-zh/components/footer/index.mq.md
      @@ -17,8 +17,8 @@ import:
       若子块仍含独立分栏,就继续沿对应目录的 index.mq.md 分解。
       不要把渲染后的字符串放回值列,子节点在整个装配过程中保持结构。
       
      -**brand_nodes = > brand.节点**
      -**links_nodes = > links.节点**
      -**siblings = 组件.合并 甲=`brand_nodes` 乙=`links_nodes`**
      -**footer_columns = 布局.分栏 子节点=`siblings` 槽="footer"**
      -*> 组件.包裹 子节点=`footer_columns` 种类="footer" 槽="footer"*
      +We first **brand_nodes = [Compute brand_nodes](brand.节点())** for the next step.
      +We first **links_nodes = [Compute links_nodes](links.节点())** for the next step.
      +We first **siblings = [Compute siblings](组件.合并(甲=`brand_nodes`, 乙=`links_nodes`))** for the next step.
      +We first **footer_columns = [Compute footer_columns](布局.分栏(子节点=`siblings`, 槽="footer"))** for the next step.
      +After these steps, return *组件.包裹(子节点=`footer_columns`, 种类="footer", 槽="footer")*.
      diff --git a/examples/web-layout-handbook-zh/components/footer/links/community/index.mq.md b/examples/web-layout-handbook-zh/components/footer/links/community/index.mq.md
      index 0b6d8b0..d2b964e 100644
      --- a/examples/web-layout-handbook-zh/components/footer/links/community/index.mq.md
      +++ b/examples/web-layout-handbook-zh/components/footer/links/community/index.mq.md
      @@ -14,5 +14,5 @@ import:
       此叶子只负责footer/links/community 的 Markdown 内容,父组件决定排列。修改文字只改相邻 content.md,
       不添加 HTML 标签或内部分栏;出现第二种布局职责时再开子目录。
       
      -**body = 文件.读文本 路径="components/footer/links/community/content.md"**
      -*> 组件.正文 文本=`body` 槽="footer-links-community"*
      +We first **body = [Compute body](文件.读文本(路径="components/footer/links/community/content.md"))** for the next step.
      +After these steps, return *组件.正文(文本=`body`, 槽="footer-links-community")*.
      diff --git a/examples/web-layout-handbook-zh/components/footer/links/docs/index.mq.md b/examples/web-layout-handbook-zh/components/footer/links/docs/index.mq.md
      index 7f17e65..fd230f6 100644
      --- a/examples/web-layout-handbook-zh/components/footer/links/docs/index.mq.md
      +++ b/examples/web-layout-handbook-zh/components/footer/links/docs/index.mq.md
      @@ -14,5 +14,5 @@ import:
       此叶子只负责footer/links/docs 的 Markdown 内容,父组件决定排列。修改文字只改相邻 content.md,
       不添加 HTML 标签或内部分栏;出现第二种布局职责时再开子目录。
       
      -**body = 文件.读文本 路径="components/footer/links/docs/content.md"**
      -*> 组件.正文 文本=`body` 槽="footer-links-docs"*
      +We first **body = [Compute body](文件.读文本(路径="components/footer/links/docs/content.md"))** for the next step.
      +After these steps, return *组件.正文(文本=`body`, 槽="footer-links-docs")*.
      diff --git a/examples/web-layout-handbook-zh/components/footer/links/index.mq.md b/examples/web-layout-handbook-zh/components/footer/links/index.mq.md
      index 14b2672..e95bf7c 100644
      --- a/examples/web-layout-handbook-zh/components/footer/links/index.mq.md
      +++ b/examples/web-layout-handbook-zh/components/footer/links/index.mq.md
      @@ -17,7 +17,7 @@ import:
       若子块仍含独立分栏,就继续沿对应目录的 index.mq.md 分解。
       不要把渲染后的字符串放回值列,子节点在整个装配过程中保持结构。
       
      -**docs_nodes = > docs.节点**
      -**community_nodes = > community.节点**
      -**siblings = 组件.合并 甲=`docs_nodes` 乙=`community_nodes`**
      -*> 布局.分栏 子节点=`siblings` 槽="footer-links"*
      +We first **docs_nodes = [Compute docs_nodes](docs.节点())** for the next step.
      +We first **community_nodes = [Compute community_nodes](community.节点())** for the next step.
      +We first **siblings = [Compute siblings](组件.合并(甲=`docs_nodes`, 乙=`community_nodes`))** for the next step.
      +After these steps, return *布局.分栏(子节点=`siblings`, 槽="footer-links")*.
      diff --git a/examples/web-layout-handbook-zh/components/index.mq.md b/examples/web-layout-handbook-zh/components/index.mq.md
      index 2cf4f29..e407dfc 100644
      --- a/examples/web-layout-handbook-zh/components/index.mq.md
      +++ b/examples/web-layout-handbook-zh/components/index.mq.md
      @@ -18,9 +18,9 @@ import:
       若子块仍含独立分栏,就继续沿对应目录的 index.mq.md 分解。
       不要把渲染后的字符串放回值列,子节点在整个装配过程中保持结构。
       
      -**nav_nodes = > nav.节点**
      -**content_nodes = > content.节点**
      -**footer_nodes = > footer.节点**
      -**upper_regions = 组件.合并 甲=`nav_nodes` 乙=`content_nodes`**
      -**home_regions = 组件.合并 甲=`upper_regions` 乙=`footer_nodes`**
      -*> 布局.纵排 子节点=`home_regions` 槽="home"*
      +We first **nav_nodes = [Compute nav_nodes](nav.节点())** for the next step.
      +We first **content_nodes = [Compute content_nodes](content.节点())** for the next step.
      +We first **footer_nodes = [Compute footer_nodes](footer.节点())** for the next step.
      +We first **upper_regions = [Compute upper_regions](组件.合并(甲=`nav_nodes`, 乙=`content_nodes`))** for the next step.
      +We first **home_regions = [Compute home_regions](组件.合并(甲=`upper_regions`, 乙=`footer_nodes`))** for the next step.
      +After these steps, return *布局.纵排(子节点=`home_regions`, 槽="home")*.
      diff --git a/examples/web-layout-handbook-zh/components/main/index.mq.md b/examples/web-layout-handbook-zh/components/main/index.mq.md
      index 59de24e..88c7b74 100644
      --- a/examples/web-layout-handbook-zh/components/main/index.mq.md
      +++ b/examples/web-layout-handbook-zh/components/main/index.mq.md
      @@ -14,5 +14,5 @@ import:
       此叶子只负责main 的 Markdown 内容,父组件决定排列。修改文字只改相邻 content.md,
       不添加 HTML 标签或内部分栏;出现第二种布局职责时再开子目录。
       
      -**body = 文件.读文本 路径="components/main/content.md"**
      -*> 组件.正文 文本=`body` 槽="main"*
      +We first **body = [Compute body](文件.读文本(路径="components/main/content.md"))** for the next step.
      +After these steps, return *组件.正文(文本=`body`, 槽="main")*.
      diff --git a/examples/web-layout-handbook-zh/components/nav/index.mq.md b/examples/web-layout-handbook-zh/components/nav/index.mq.md
      index cca0dee..0e0ad07 100644
      --- a/examples/web-layout-handbook-zh/components/nav/index.mq.md
      +++ b/examples/web-layout-handbook-zh/components/nav/index.mq.md
      @@ -14,5 +14,5 @@ import:
       此叶子只负责nav 的 Markdown 内容,父组件决定排列。修改文字只改相邻 content.md,
       不添加 HTML 标签或内部分栏;出现第二种布局职责时再开子目录。
       
      -**body = 文件.读文本 路径="components/nav/content.md"**
      -*> 组件.正文 文本=`body` 槽="nav"*
      +We first **body = [Compute body](文件.读文本(路径="components/nav/content.md"))** for the next step.
      +After these steps, return *组件.正文(文本=`body`, 槽="nav")*.
      diff --git a/examples/web-layout-handbook-zh/index.mq.md b/examples/web-layout-handbook-zh/index.mq.md
      index d540fb5..d7555ad 100644
      --- a/examples/web-layout-handbook-zh/index.mq.md
      +++ b/examples/web-layout-handbook-zh/index.mq.md
      @@ -10,7 +10,11 @@ import:
       
       # main
       
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| result | any | The value explicitly returned below; conditional returns follow the selected branch |
      +
       页面只选择布局根,具体拆分沿 components/index.mq.md 继续。
       此主程序返回结构而不是 HTML;view 元数据让服务在启动时执行它。
       
      -*> home.节点*
      +After these steps, return *home.节点()*.
      diff --git a/examples/web-layout-handbook-zh/pages/about.mq.md b/examples/web-layout-handbook-zh/pages/about.mq.md
      index 9d49066..c321ac8 100644
      --- a/examples/web-layout-handbook-zh/pages/about.mq.md
      +++ b/examples/web-layout-handbook-zh/pages/about.mq.md
      @@ -7,4 +7,5 @@ markup: occlusion
       
       # 关于
       
      +
       这是普通 Markdown Document,不执行布局函数。
      diff --git a/examples/web-layout-handbook-zh/preview.mq.md b/examples/web-layout-handbook-zh/preview.mq.md
      index 9f3088e..81304e0 100644
      --- a/examples/web-layout-handbook-zh/preview.mq.md
      +++ b/examples/web-layout-handbook-zh/preview.mq.md
      @@ -1,12 +1,20 @@
       ---
       markup: occlusion
      +title: 可直接调用的布局预览
       import:
         home: ./components/index.mq.md
         网页: ext/web/网页.mq.md
       ---
       
      -# main
      +预览从站点组件根开始,不拼接另一份页面。
       
      -**nodes = > home.节点**
      -**html = 网页.渲染 节点=`nodes` 标题="Marqdo 布局实践"**
      -> 打印 内容=`html`
      +## main
      +
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| result | text | 与原有运行输出一致的 HTML 文本 |
      +
      +本函数既可以用 marqdo call 直接取得 HTML 返回值,也保留 marqdo run 原有的预览输出。组件内容相对站点根目录读取,因此从仓库根调用时应将 --fs-root 指向 examples/web-layout-handbook-zh,并授予 fs.read、plugin 和 output.write。预览不会开启网络监听,也不修改内容文件;线上服务与本函数共享节点渲染器,页脚左右区域和嵌套链接列应保持一致。检查返回的 HTML 不能代替浏览器中的布局和交互验证。
      +
      +我们 **nodes = [沿组件入口装配全部布局](home.节点())**,再 **html = [使用线上相同的节点渲染器](网页.渲染(节点=`nodes`, 标题="Marqdo 布局实践"))**。
      +我们 **[为原有运行预览输出页面](打印(内容=`html`))**,随后直接返回 *html*。
      diff --git a/examples/web-layout-handbook-zh/serve.mq.md b/examples/web-layout-handbook-zh/serve.mq.md
      index fc0d8b0..f9e12a9 100644
      --- a/examples/web-layout-handbook-zh/serve.mq.md
      +++ b/examples/web-layout-handbook-zh/serve.mq.md
      @@ -6,7 +6,15 @@ import:
       
       # main
       
      +| 参数 | 类型 | 默认 | 说明 |
      +|---|---|---|---|
      +| 端口 | any | 18081 | 本地 HTTP 监听端口;服务启动后持续运行直到调用方停止 |
      +
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| result | any | None; execute this page's documented steps in order and observe their output or stated effects |
      +
       端口 `端口`=18081 可通过 --bind 覆盖。启动器不包含页面布局。
       
      -**监听端口 = 整数 值=`端口`**
      -> 网页.服务 根="." 主机="127.0.0.1" 端口=`监听端口`
      +We first **监听端口 = [Compute 监听端口](整数(值=`端口`))** for the next step.
      +We now **[Call 网页.服务](> 网页.服务 根="." 主机="127.0.0.1" 端口=`监听端口`)**.
      diff --git a/examples/web-layout-handbook/api/ping.mq.md b/examples/web-layout-handbook/api/ping.mq.md
      index fa83812..c788372 100644
      --- a/examples/web-layout-handbook/api/ping.mq.md
      +++ b/examples/web-layout-handbook/api/ping.mq.md
      @@ -9,10 +9,14 @@ response: json
       
       # main
       
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| result | any | The value explicitly returned below; conditional returns follow the selected branch |
      +
       `result` =
       
       | ok | ping |
       |----|------|
       | True | pong |
       
      -*result*
      +After these steps, return *result*.
      diff --git a/examples/web-layout-handbook/components/footer/brand/index.mq.md b/examples/web-layout-handbook/components/footer/brand/index.mq.md
      index 4380b29..51f36f0 100644
      --- a/examples/web-layout-handbook/components/footer/brand/index.mq.md
      +++ b/examples/web-layout-handbook/components/footer/brand/index.mq.md
      @@ -15,5 +15,5 @@ This leaf owns only the footer/brand Markdown content; its parent owns placement
       Edit adjacent content.md to change prose. Add a child directory when a second
       layout responsibility appears instead of introducing HTML into the content.
       
      -**body = fs.read_text path="components/footer/brand/content.md"**
      -*> component.markdown text=`body` slot="footer-brand"*
      +We first **body = [Compute body](fs.read_text(path="components/footer/brand/content.md"))** for the next step.
      +After these steps, return *component.markdown(text=`body`, slot="footer-brand")*.
      diff --git a/examples/web-layout-handbook/components/footer/index.mq.md b/examples/web-layout-handbook/components/footer/index.mq.md
      index 85dbe69..783af90 100644
      --- a/examples/web-layout-handbook/components/footer/index.mq.md
      +++ b/examples/web-layout-handbook/components/footer/index.mq.md
      @@ -17,8 +17,8 @@ This parent arranges brand content and the link-region subtree. Content stays
       in their Markdown leaves; this file owns their one placement relationship. Continue into each child index when another independent layout
       remains. Preserve node lists rather than rendering children into HTML strings.
       
      -**brand_nodes = > brand.nodes**
      -**links_nodes = > links.nodes**
      -**siblings = component.merge a=`brand_nodes` b=`links_nodes`**
      -**footer_columns = layout.columns children=`siblings` slot="footer"**
      -*> component.wrap children=`footer_columns` kind="footer" slot="footer"*
      +We first **brand_nodes = [Compute brand_nodes](brand.nodes())** for the next step.
      +We first **links_nodes = [Compute links_nodes](links.nodes())** for the next step.
      +We first **siblings = [Compute siblings](component.merge(a=`brand_nodes`, b=`links_nodes`))** for the next step.
      +We first **footer_columns = [Compute footer_columns](layout.columns(children=`siblings`, slot="footer"))** for the next step.
      +After these steps, return *component.wrap(children=`footer_columns`, kind="footer", slot="footer")*.
      diff --git a/examples/web-layout-handbook/components/footer/links/community/index.mq.md b/examples/web-layout-handbook/components/footer/links/community/index.mq.md
      index 155fdf9..b2a15e9 100644
      --- a/examples/web-layout-handbook/components/footer/links/community/index.mq.md
      +++ b/examples/web-layout-handbook/components/footer/links/community/index.mq.md
      @@ -15,5 +15,5 @@ This leaf owns only the footer/links/community Markdown content; its parent owns
       Edit adjacent content.md to change prose. Add a child directory when a second
       layout responsibility appears instead of introducing HTML into the content.
       
      -**body = fs.read_text path="components/footer/links/community/content.md"**
      -*> component.markdown text=`body` slot="footer-links-community"*
      +We first **body = [Compute body](fs.read_text(path="components/footer/links/community/content.md"))** for the next step.
      +After these steps, return *component.markdown(text=`body`, slot="footer-links-community")*.
      diff --git a/examples/web-layout-handbook/components/footer/links/docs/index.mq.md b/examples/web-layout-handbook/components/footer/links/docs/index.mq.md
      index 8c341a2..5843b34 100644
      --- a/examples/web-layout-handbook/components/footer/links/docs/index.mq.md
      +++ b/examples/web-layout-handbook/components/footer/links/docs/index.mq.md
      @@ -15,5 +15,5 @@ This leaf owns only the footer/links/docs Markdown content; its parent owns plac
       Edit adjacent content.md to change prose. Add a child directory when a second
       layout responsibility appears instead of introducing HTML into the content.
       
      -**body = fs.read_text path="components/footer/links/docs/content.md"**
      -*> component.markdown text=`body` slot="footer-links-docs"*
      +We first **body = [Compute body](fs.read_text(path="components/footer/links/docs/content.md"))** for the next step.
      +After these steps, return *component.markdown(text=`body`, slot="footer-links-docs")*.
      diff --git a/examples/web-layout-handbook/components/footer/links/index.mq.md b/examples/web-layout-handbook/components/footer/links/index.mq.md
      index 60da42c..d94bf86 100644
      --- a/examples/web-layout-handbook/components/footer/links/index.mq.md
      +++ b/examples/web-layout-handbook/components/footer/links/index.mq.md
      @@ -17,7 +17,7 @@ This parent arranges documentation links and community links. Content stays
       in their Markdown leaves; this file owns their one placement relationship. Continue into each child index when another independent layout
       remains. Preserve node lists rather than rendering children into HTML strings.
       
      -**docs_nodes = > docs.nodes**
      -**community_nodes = > community.nodes**
      -**siblings = component.merge a=`docs_nodes` b=`community_nodes`**
      -*> layout.columns children=`siblings` slot="footer-links"*
      +We first **docs_nodes = [Compute docs_nodes](docs.nodes())** for the next step.
      +We first **community_nodes = [Compute community_nodes](community.nodes())** for the next step.
      +We first **siblings = [Compute siblings](component.merge(a=`docs_nodes`, b=`community_nodes`))** for the next step.
      +After these steps, return *layout.columns(children=`siblings`, slot="footer-links")*.
      diff --git a/examples/web-layout-handbook/components/index.mq.md b/examples/web-layout-handbook/components/index.mq.md
      index 63f00d1..e48a373 100644
      --- a/examples/web-layout-handbook/components/index.mq.md
      +++ b/examples/web-layout-handbook/components/index.mq.md
      @@ -18,9 +18,9 @@ This parent arranges navigation, main content and footer. Content stays
       in their Markdown leaves; this file owns their one placement relationship. Continue into each child index when another independent layout
       remains. Preserve node lists rather than rendering children into HTML strings.
       
      -**nav_nodes = > nav.nodes**
      -**content_nodes = > content.nodes**
      -**footer_nodes = > footer.nodes**
      -**upper_regions = component.merge a=`nav_nodes` b=`content_nodes`**
      -**home_regions = component.merge a=`upper_regions` b=`footer_nodes`**
      -*> layout.stack children=`home_regions` slot="home"*
      +We first **nav_nodes = [Compute nav_nodes](nav.nodes())** for the next step.
      +We first **content_nodes = [Compute content_nodes](content.nodes())** for the next step.
      +We first **footer_nodes = [Compute footer_nodes](footer.nodes())** for the next step.
      +We first **upper_regions = [Compute upper_regions](component.merge(a=`nav_nodes`, b=`content_nodes`))** for the next step.
      +We first **home_regions = [Compute home_regions](component.merge(a=`upper_regions`, b=`footer_nodes`))** for the next step.
      +After these steps, return *layout.stack(children=`home_regions`, slot="home")*.
      diff --git a/examples/web-layout-handbook/components/main/index.mq.md b/examples/web-layout-handbook/components/main/index.mq.md
      index 708942e..80b39c6 100644
      --- a/examples/web-layout-handbook/components/main/index.mq.md
      +++ b/examples/web-layout-handbook/components/main/index.mq.md
      @@ -15,5 +15,5 @@ This leaf owns only the main Markdown content; its parent owns placement.
       Edit adjacent content.md to change prose. Add a child directory when a second
       layout responsibility appears instead of introducing HTML into the content.
       
      -**body = fs.read_text path="components/main/content.md"**
      -*> component.markdown text=`body` slot="main"*
      +We first **body = [Compute body](fs.read_text(path="components/main/content.md"))** for the next step.
      +After these steps, return *component.markdown(text=`body`, slot="main")*.
      diff --git a/examples/web-layout-handbook/components/nav/index.mq.md b/examples/web-layout-handbook/components/nav/index.mq.md
      index 16e4c57..e769907 100644
      --- a/examples/web-layout-handbook/components/nav/index.mq.md
      +++ b/examples/web-layout-handbook/components/nav/index.mq.md
      @@ -15,5 +15,5 @@ This leaf owns only the nav Markdown content; its parent owns placement.
       Edit adjacent content.md to change prose. Add a child directory when a second
       layout responsibility appears instead of introducing HTML into the content.
       
      -**body = fs.read_text path="components/nav/content.md"**
      -*> component.markdown text=`body` slot="nav"*
      +We first **body = [Compute body](fs.read_text(path="components/nav/content.md"))** for the next step.
      +After these steps, return *component.markdown(text=`body`, slot="nav")*.
      diff --git a/examples/web-layout-handbook/index.mq.md b/examples/web-layout-handbook/index.mq.md
      index d7681f7..e91d2b9 100644
      --- a/examples/web-layout-handbook/index.mq.md
      +++ b/examples/web-layout-handbook/index.mq.md
      @@ -10,7 +10,11 @@ import:
       
       # main
       
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| result | any | The value explicitly returned below; conditional returns follow the selected branch |
      +
       The page selects the layout root; follow components/index.mq.md for decomposition.
       This main returns rows rather than HTML; view metadata opts into startup assembly.
       
      -*> home.nodes*
      +After these steps, return *home.nodes()*.
      diff --git a/examples/web-layout-handbook/preview.mq.md b/examples/web-layout-handbook/preview.mq.md
      index 9c2c925..453201a 100644
      --- a/examples/web-layout-handbook/preview.mq.md
      +++ b/examples/web-layout-handbook/preview.mq.md
      @@ -1,12 +1,20 @@
       ---
       markup: occlusion
      +title: Callable preview of the actual layout tree
       import:
         home: ./components/index.mq.md
         web: ext/web/web.mq.md
       ---
       
      -# main
      +Preview begins at the site component root and shares its renderer with the server.
       
      -**nodes = > home.nodes**
      -**html = web.render nodes=`nodes` title="Marqdo layout handbook"**
      -> print text=`html`
      +## main
      +
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| result | text | HTML text identical to the existing printed preview |
      +
      +Call this ordinary main function to obtain the actual HTML value; run still prints the same preview for existing callers. Markdown leaves are read relative to the granted site root, so use --fs-root examples/web-layout-handbook from the checkout root, with fs.read, plugin and output.write. Preview opens no listener and changes no content. The same node renderer serves the Document, including both footer regions and the nested link columns. Inspecting this returned HTML does not replace browser geometry or interaction checks.
      +
      +We **nodes = [Assemble the complete component tree](home.nodes())**, then **html = [Use the same node renderer as the served Document](web.render(nodes=`nodes`, title="Marqdo layout handbook"))**.
      +We **[Keep the existing run preview output](print(text=`html`))**, then return *html*.
      diff --git a/examples/web-layout-handbook/serve.mq.md b/examples/web-layout-handbook/serve.mq.md
      index cbd003a..1930589 100644
      --- a/examples/web-layout-handbook/serve.mq.md
      +++ b/examples/web-layout-handbook/serve.mq.md
      @@ -6,7 +6,15 @@ import:
       
       # main
       
      +| 参数 | 类型 | 默认 | 说明 |
      +|---|---|---|---|
      +| port | any | 18081 | Local HTTP listening port; starting the server owns its lifecycle until stopped |
      +
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| result | any | None; execute this page's documented steps in order and observe their output or stated effects |
      +
       The `port`=18081 may be overridden with --bind. This launcher owns no layout.
       
      -**listen_port = int value=`port`**
      -> web.serve root="." host="127.0.0.1" port=`listen_port`
      +We first **listen_port = [Compute listen_port](int(value=`port`))** for the next step.
      +We now **[Call web.serve](> web.serve root="." host="127.0.0.1" port=`listen_port`)**.
      diff --git a/examples/web-net-site-zh/README.md b/examples/web-net-site-zh/README.md
      index 2e53745..0190205 100644
      --- a/examples/web-net-site-zh/README.md
      +++ b/examples/web-net-site-zh/README.md
      @@ -1,19 +1,24 @@
      -# examples/web-net-site-zh
      +# web-net-site-zh
       
      -中文作者面示例:只导入 `ext/web/网页.mq.md`(不用英文 `web.mq.md`),并用 `lib/网络.mq.md` 的解析原语。
      +本工程保留文章列表、关于页、文章表单、Cookie/Multipart 工具页、登录后的原生管理后台,以及 /live WebSocket 回显。中文作者使用网页、表单、后台、鉴权和实时资源入口。页面递归组合到 Markdown 和原生控件;浏览器交互由 public/client.mq.md 表达,旧 public/live.js 已被实际验证后的 Marqdo 客户端替代。
       
      -```bash
      -cargo build -p marqdo_plugin_web
      -cargo run -- examples/web-net-site-zh/index.mq.md
      +从仓库根目录准备当前 CLI 与工程插件后,使用同一份开发手册构建 Web 和浏览器运行时:
      +
      +```sh
      +target/debug/marqdo call skills/marqdo-dev/index.mq.md prepare_engineering --effects process.exec --fs-root . --require-ok --json
      +target/debug/marqdo call skills/marqdo-dev/index.mq.md prepare_web --effects plugin --fs-root . --require-ok --json
      +target/debug/marqdo call skills/marqdo-dev/index.mq.md build_browser 'out="examples/web-net-site-zh/public/generated"' --effects plugin,process.exec,fs.write --fs-root . --require-ok --json
      +target/debug/marqdo call examples/web-net-site-zh/index.mq.md serve --effects plugin,fs.write,network.write --fs-root examples/web-net-site-zh --require-ok --json
       ```
       
      -从仓库根目录或示例目录运行都可以:`static_dir`(如 `public`)与相对 db 路径(如 `data/site-net-zh.db`)都会基于**入口脚本所在目录**解析,而不是终端的当前目录。
      +打开 http://127.0.0.1:18084。默认数据库位于站点文件根的 data/site-net-zh.db,重启保留已有文章。缺少兼容 WASM 目标时,先按 [工具链任务](../../skills/marqdo-dev/toolchain.mq.md) 准备工作区编译器,再把返回的 compiler 传给 build_browser。
       
      -打开 http://127.0.0.1:18084/:
      +- [布局入口](components/index.mq.md) 组合导航、侧栏、主体和页脚,叶子在 components/content。
      +- [文章表单](forms.mq.md) 统一定义字段与服务端规则;校验失败后保留真实 CSRF,成功回到文章列表。
      +- [工具页](pages/tools.mq.md) 展示真实网络解析结果,不请求远端服务。
      +- [客户端](public/client.mq.md) 保留按钮与 Enter 发送、去除首尾空白、忽略空输入及连续回显日志。
      +- 管理后台登录使用本机演示账号 admin / secret。部署时替换账号与访问策略。
       
      -- `/` — SQLite 文章列表 + `/live` WebSocket 实时小部件(`public/live.js`)
      -- `/about`
      -- `/new` — 表单 POST 到 `/_form/article`
      -- `/tools` — `lib/net`(`解析Cookie` / `解析多部分`)的解析演示
      -- `/admin` — 会话门禁后台,用 `admin` / `secret` 登录
      -- `/live` — WebSocket 回显端点(首页小部件或 `网页.实时` 的 `连接` 接入)
      +请求资源沿用五列 View;数据库查询随每次请求更新,表单引用解析当前会话。详情见 [请求资源设计](../../doc/design/web-view-resources.md)。
      +
      +开发入口的 test_browser 使用实际当前 WASM 验证回显、表单重试、新增文章、后台登录与窄屏布局。HTTP 回归 web_handbook 在 Tree 与 Bytecode 两个后端启动临时站点,验证数据和鉴权,避免操作用户数据库。
      diff --git a/examples/web-net-site-zh/components/content/about.md b/examples/web-net-site-zh/components/content/about.md
      new file mode 100644
      index 0000000..cf07779
      --- /dev/null
      +++ b/examples/web-net-site-zh/components/content/about.md
      @@ -0,0 +1,5 @@
      +# 关于
      +
      +演示网络扩展后的网页库:会话、登录鉴权、WebSocket,以及 multipart 与 Cookie 解析。
      +
      +各个职责都有独立模块:父组件组合布局,叶子使用 Markdown,数据与表单在请求期间读取当前状态。
      diff --git a/examples/web-net-site-zh/components/content/foot.md b/examples/web-net-site-zh/components/content/foot.md
      new file mode 100644
      index 0000000..e579e6b
      --- /dev/null
      +++ b/examples/web-net-site-zh/components/content/foot.md
      @@ -0,0 +1 @@
      +[Marqdo 网络扩展示例](https://github.com) · [文档](/tools)
      diff --git a/examples/web-net-site-zh/components/content/home.md b/examples/web-net-site-zh/components/content/home.md
      new file mode 100644
      index 0000000..3fb6ea4
      --- /dev/null
      +++ b/examples/web-net-site-zh/components/content/home.md
      @@ -0,0 +1,3 @@
      +# 网络扩展站
      +
      +SQLite 文章列表、WebSocket 实时小部件、登录门禁后台,以及标准网络库的解析工具。
      diff --git a/examples/web-net-site-zh/components/content/multipart.txt b/examples/web-net-site-zh/components/content/multipart.txt
      new file mode 100644
      index 0000000..f1882fd
      --- /dev/null
      +++ b/examples/web-net-site-zh/components/content/multipart.txt
      @@ -0,0 +1,10 @@
      +--net-boundary
      +Content-Disposition: form-data; name="title"
      +
      +你好
      +--net-boundary
      +Content-Disposition: form-data; name="cover"; filename="pic.png"
      +Content-Type: image/png
      +
      +<字节>
      +--net-boundary--
      diff --git a/examples/web-net-site-zh/components/content/nav.md b/examples/web-net-site-zh/components/content/nav.md
      new file mode 100644
      index 0000000..9ea33ac
      --- /dev/null
      +++ b/examples/web-net-site-zh/components/content/nav.md
      @@ -0,0 +1 @@
      +[首页](/) · [关于](/about) · [发布](/new) · [工具](/tools) · [后台](/admin)
      diff --git a/examples/web-net-site-zh/components/content/new.md b/examples/web-net-site-zh/components/content/new.md
      new file mode 100644
      index 0000000..1fb44b9
      --- /dev/null
      +++ b/examples/web-net-site-zh/components/content/new.md
      @@ -0,0 +1,3 @@
      +# 发布
      +
      +表单按共享规则校验后插入 articles 表,成功返回首页。标题必填,正文可空。
      diff --git a/examples/web-net-site-zh/components/content/side.md b/examples/web-net-site-zh/components/content/side.md
      new file mode 100644
      index 0000000..0fff560
      --- /dev/null
      +++ b/examples/web-net-site-zh/components/content/side.md
      @@ -0,0 +1,7 @@
      +## 功能导航
      +
      +- [文章](/)
      +- [WebSocket](/#live)
      +- [登录鉴权](/admin)
      +- [表单](/new)
      +- [lib/net](/tools)
      diff --git a/examples/web-net-site-zh/components/foot.mq.md b/examples/web-net-site-zh/components/foot.mq.md
      index b176732..284ec12 100644
      --- a/examples/web-net-site-zh/components/foot.mq.md
      +++ b/examples/web-net-site-zh/components/foot.mq.md
      @@ -1,14 +1,20 @@
       ---
       markup: occlusion
      +title: 页脚的 Markdown 内容组件
      +import:
      +  组件: ext/web/网页/组件/索引.mq.md
      +  文件: lib/文件.mq.md
       ---
       
      +页脚保留原示例的项目链接与工具文档入口。本块只有一组简单链接,没有双栏布局;将来出现独立品牌栏与链接栏时再继续拆成两个子组件。
      +
       ## 页脚
       
      -`页脚` =
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| 结果 | list | 包含终端 Markdown 的单个语义区域 |
       
      -| 属性 | 值 | 样式 |
      -|------|-----|------|
      -| Marqdo 网络扩展示例 | https://github.com | |
      -| 文档 | /tools | |
      +本组件只拥有本块内容与语义容器。以站点为 --fs-root 授予 fs.read,正文读取相邻内容目录的 Markdown 叶子,不查询记录或启动服务器。父布局决定本块位置;修改文字与链接只编辑叶子。保留稳定槽名与样式类,使片段和主题继续找到本区域,内容不会先被渲染成不透明字符串。
       
      -*`页脚`*
      \ No newline at end of file
      +我们 **文本 = [读取本区域的终端 Markdown](文件.读文本(路径="components/content/foot.md"))** 和 **叶子 = [保持简单 Markdown 内容](组件.正文(文本=`文本`, 槽="foot-content"))**。
      +准备好内容后返回 *[保留这一块的语义与样式](组件.包裹(子节点=`叶子`, 种类="footer", 槽="foot", 样式="foot"))*。
      diff --git a/examples/web-net-site-zh/components/home.mq.md b/examples/web-net-site-zh/components/home.mq.md
      new file mode 100644
      index 0000000..3791127
      --- /dev/null
      +++ b/examples/web-net-site-zh/components/home.mq.md
      @@ -0,0 +1,24 @@
      +---
      +markup: occlusion
      +title: 首页主体的三个独立职责
      +import:
      +  组件: ext/web/网页/组件/索引.mq.md
      +  视图: ext/data/视图.mq.md
      +  实时: live.mq.md
      +  文件: lib/文件.mq.md
      +  表: lib/表.mq.md
      +---
      +
      +首页主体继续拆为介绍、原生实时控件和当前文章查询。介绍是静态 Markdown,控件交互归浏览器程序,文章由每个真实请求查询。父模块只保留这三个责任的顺序。
      +
      +## 节点
      +
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| 结果 | list | 介绍、实时控件与请求期间文章查询的结构节点 |
      +
      +只在启动阶段装配页面结构,授予 fs.read 以读取介绍。文章资源使用监听应用绑定的同一个 articles 表,按 id 排序;发布新文章后下一次请求直接查询当前记录,不保留旧的启动列表。查询描述是纯数据,不从猜测的相对文件名另开数据库。回显的运输路由由服务入口绑定,构造控件不会打开连接。
      +
      +我们 **文本 = [读取首页介绍](文件.读文本(路径="components/content/home.md"))**、**介绍 = [保留终端 Markdown](组件.正文(文本=`文本`, 槽="intro"))** 和 **控件 = [组合实时交互区域](实时.节点())**。
      +接着 **查询 = [描述当前业务文章](视图.查询(源="articles", 排序="id", 链接前缀=""))** 和 **文章 = [安放动态查询资源](组件.请求资源(值=`查询`, 槽="articles"))**。
      +我们 **正文 = [介绍位于交互之前](表.拼接(a=`介绍`, b=`控件`))**,最后返回 *[把当前文章放在交互之后](表.拼接(a=`正文`, b=`文章`))*。
      diff --git a/examples/web-net-site-zh/components/index.mq.md b/examples/web-net-site-zh/components/index.mq.md
      new file mode 100644
      index 0000000..ca95e04
      --- /dev/null
      +++ b/examples/web-net-site-zh/components/index.mq.md
      @@ -0,0 +1,29 @@
      +---
      +markup: occlusion
      +title: 网络站点的递归布局入口
      +import:
      +  组件: ext/web/网页/组件/索引.mq.md
      +  导航: nav.mq.md
      +  侧栏: side.mq.md
      +  页脚: foot.mq.md
      +  表: lib/表.mq.md
      +---
      +
      +本入口只管理各块的位置关系。先拆导航、侧栏与主体行、页脚,再由子模块读终端 Markdown。请求期间的查询和表单保留在主体内,不把渲染结果拼回 HTML 字符串。调整文案沿子模块找到内容叶子,调整几何只修改本层。
      +
      +## 框架
      +
      +| 参数 | 类型 | 默认 | 说明 |
      +|---|---|---|---|
      +| 正文 | list | 必填 | 页面自身已经构造的主体节点 |
      +
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| 结果 | list | 有序导航、侧栏/主体双栏、页脚与主题资源 |
      +
      +输入`正文`,本层不查询数据库、不验证身份,也不负责启动监听。侧栏和主体是行容器的两个子块,窄屏折叠由已有 View 运行时负责。节点始终保留结构值,主题只引用 serve 已编译并写入的文件;纯构造不会读取或下载样式。共享 Markdown 的读取需要 fs.read。
      +
      +我们 **顶部 = [读取导航内容](导航.导航())** 和 **旁栏 = [读取侧栏内容](侧栏.侧栏())**,**主体 = [给页面正文稳定区域名](组件.包裹(子节点=`正文`, 种类="column", 槽="main"))**。
      +接着 **双栏 = [保留侧栏与主体的兄弟关系](表.拼接(a=`旁栏`, b=`主体`))**、**中部 = [声明响应式横向几何](组件.包裹(子节点=`双栏`, 种类="row", 槽="page-body"))** 和 **底部 = [读取结束链接](页脚.页脚())**。
      +我们 **页面 = [导航位于内容之前](表.拼接(a=`顶部`, b=`中部`))**、**页面 = [页脚位于内容之后](表.拼接(a=`页面`, b=`底部`))** 和 **样式 = [引用明确生成的声明式主题](组件.资源(地址="/static/generated/theme.css", 种类="stylesheet"))**。
      +完成布局后返回 *[让结构与样式资源一起保留](表.拼接(a=`页面`, b=`样式`))*。
      diff --git a/examples/web-net-site-zh/components/live.mq.md b/examples/web-net-site-zh/components/live.mq.md
      new file mode 100644
      index 0000000..442b523
      --- /dev/null
      +++ b/examples/web-net-site-zh/components/live.mq.md
      @@ -0,0 +1,83 @@
      +---
      +markup: occlusion
      +title: 原生 WebSocket 控件叶子
      +import:
      +  组件: ext/web/网页/组件/索引.mq.md
      +  客户端: ext/web/网页/客户端/索引.mq.md
      +  表: lib/表.mq.md
      +---
      +
      +本区域拆到简单 Markdown 与原生控件即停止,不写 HTML 或业务 JavaScript。浏览器客户端负责事件与状态,服务入口负责 /live 运输。控件标识是双方契约,修改文案时保留这些标识。
      +
      +## _状态
      +
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| 结果 | list | 独立的连接状态文本目标 |
      +
      +连接与消息是两个不同的反馈区域。状态使用稳定 live-status 标识及礼貌的辅助通知,初始文字不表示已连接。真实连接的开、错、关由浏览器客户端更新。本构造是纯计算,不加载运行时或尝试网络;状态文字按文本转义,不能变成页面结构。
      +
      +`属性` =
      +
      +| id | aria-live |
      +|---|---|
      +| live-status | polite |
      +
      +我们返回 *[创建独立的连接反馈目标](组件.控件(种类="text", 值="正在连接…", 属性=`属性`, 槽="live-status"))*。
      +
      +## _操作
      +
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| 结果 | list | 输入与发送按钮组成的响应式行 |
      +
      +输入提供消息值,按钮启动时使用真实布尔 disabled,只有连接成功后才移除该属性。字符串 false 仍会让 HTML 布尔属性存在,因此不能用它替代 False。控件 id 和客户端事件绑定一致,标题可改,标识应同步修改。
      +
      +这两个叶子已经无法再拆成 Markdown,因为需要原生输入与点击目标。横向排列仍交给统一 View 行容器,窄屏按运行时规则折叠;这里不固定像素宽度、不安装事件处理器,也不在构造期间发送任何消息。按钮显式 type=button,因此嵌入其他内容时不会意外触发表单提交;placeholder 只提示输入,不作为实际消息值。
      +
      +`输入属性` =
      +
      +| id | placeholder | type |
      +|---|---|---|
      +| live-msg | 输入一条消息… | text |
      +
      +`按钮属性` =
      +
      +| id | type | disabled |
      +|---|---|---|
      +| live-send | button | True |
      +
      +我们 **输入 = [声明原生消息输入框](组件.控件(种类="input", 属性=`输入属性`, 槽="live-input"))** 和 **按钮 = [连接前保持发送禁用](组件.控件(种类="button", 值="发送", 属性=`按钮属性`, 槽="live-send"))**。
      +随后 **操作 = [保持输入与发送相邻](表.拼接(a=`输入`, b=`按钮`))**,最后返回 *[声明可折叠的操作行](组件.包裹(子节点=`操作`, 种类="row", 槽="live-controls"))*。
      +
      +## _输出
      +
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| 结果 | list | 保留纯文本回显的预格式区域 |
      +
      +消息由客户端收到真实帧后追加,页面构造不伪造初始回显。pre 保留换行,稳定 live-out 标识供文本效果更新;辅助通知采用 polite,避免将输入误当作实时状态。尖括号、引号与协议内容都应显示字面字符,不能通过设 HTML 展示。
      +
      +`属性` =
      +
      +| id | aria-live |
      +|---|---|
      +| live-out | polite |
      +
      +结构明确后返回 *[创建转义文本消息目标](组件.控件(种类="pre", 属性=`属性`, 槽="live-output"))*。
      +
      +## 节点
      +
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| 结果 | list | 实时区域的标题、状态、操作、输出与官方桥资源 |
      +
      +本层只确定四个子块的顺序,终端控件由上面三个职责提供。标题用普通 Markdown,区域 id 保留侧栏 /#live 目的地。构造无需插件,不连接服务器;监听和网络策略仍归服务入口。
      +
      +官方桥从明确静态地址加载当前 WASM 与 public/client.mq.md。调用前应构建匹配版本并放入 public/generated,构造节点本身不检查存在性。启动时的空日志仅代表尚未收到消息;错误与关闭不能被解释为成功传输。客户端源是 Marqdo,页面不嵌入手写业务 JavaScript。运行时资源与页面内容并列保留,不能先调用旧字符串挂载再塞进正文。页面只有一个客户端源和一条连接,不因为组件拆分而重复启动同一个小部件。
      +
      +我们 **标题 = [说明实时区域](组件.正文(文本="## 实时 WebSocket", 槽="live-heading"))**、**状态 = [独立装配连接反馈](_状态())**、**操作 = [独立装配原生输入与发送](_操作())** 和 **输出 = [独立装配文本消息目标](_输出())**。
      +接着 **正文 = [先呈现标题与状态](表.拼接(a=`标题`, b=`状态`))**、**正文 = [再放置输入操作](表.拼接(a=`正文`, b=`操作`))** 和 **正文 = [最后展示真实回显](表.拼接(a=`正文`, b=`输出`))**。
      +我们 **属性 = [保留既有页内目的地](表.设(map=None, key="id", value="live"))** 和 **区域 = [组合一个语义区域](组件.包裹(子节点=`正文`, 种类="section", 属性=`属性`, 槽="live"))**。
      +随后 **运行时 = [引用官方桥与 Marqdo 客户端](客户端.挂载节点(源="/static/client.mq.md", wasm="/static/generated/marqdo_wasm.wasm", 桥="/static/generated/marqdo-bridge.js"))**。
      +完成后返回 *[保留区域与运行时结构](表.拼接(a=`区域`, b=`运行时`))*。
      diff --git a/examples/web-net-site-zh/components/nav.mq.md b/examples/web-net-site-zh/components/nav.mq.md
      index d03b57a..eb96050 100644
      --- a/examples/web-net-site-zh/components/nav.mq.md
      +++ b/examples/web-net-site-zh/components/nav.mq.md
      @@ -1,19 +1,20 @@
       ---
       markup: occlusion
      +title: 导航的 Markdown 内容组件
      +import:
      +  组件: ext/web/网页/组件/索引.mq.md
      +  文件: lib/文件.mq.md
       ---
       
      +顶层导航保留首页、关于、发布、工具与后台链接。链接可见不表示目标已获授权,后台实际由服务入口绑定的会话门禁保护。
      +
       ## 导航
       
      -站点顶部导航。`后台` 指向需要登录的 `/admin`。
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| 结果 | list | 包含终端 Markdown 的单个语义区域 |
       
      -`导航` =
      +本组件只拥有本块内容与语义容器。以站点为 --fs-root 授予 fs.read,正文读取相邻内容目录的 Markdown 叶子,不查询记录或启动服务器。父布局决定本块位置;修改文字与链接只编辑叶子。保留稳定槽名与样式类,使片段和主题继续找到本区域,内容不会先被渲染成不透明字符串。
       
      -| 属性 | 值 | 样式 |
      -|------|-----|------|
      -| 首页 | / | |
      -| 关于 | /about | |
      -| 发布 | /new | |
      -| 工具 | /tools | |
      -| 后台 | /admin | |
      -
      -*`导航`*
      \ No newline at end of file
      +我们 **文本 = [读取本区域的终端 Markdown](文件.读文本(路径="components/content/nav.md"))** 和 **叶子 = [保持简单 Markdown 内容](组件.正文(文本=`文本`, 槽="nav-content"))**。
      +准备好内容后返回 *[保留这一块的语义与样式](组件.包裹(子节点=`叶子`, 种类="nav", 槽="nav", 样式="topnav"))*。
      diff --git a/examples/web-net-site-zh/components/side.mq.md b/examples/web-net-site-zh/components/side.mq.md
      index 2cd0971..74695e2 100644
      --- a/examples/web-net-site-zh/components/side.mq.md
      +++ b/examples/web-net-site-zh/components/side.mq.md
      @@ -1,19 +1,20 @@
       ---
       markup: occlusion
      +title: 侧栏的 Markdown 内容组件
      +import:
      +  组件: ext/web/网页/组件/索引.mq.md
      +  文件: lib/文件.mq.md
       ---
       
      +侧栏提供文章、实时连接、鉴权、表单与网络解析的任务跳转。WebSocket 的页内锚点保持 /#live,改变文字无需修改连接实现。
      +
       ## 侧栏
       
      -本示例展示了哪些特性。
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| 结果 | list | 包含终端 Markdown 的单个语义区域 |
       
      -`侧栏` =
      +本组件只拥有本块内容与语义容器。以站点为 --fs-root 授予 fs.read,正文读取相邻内容目录的 Markdown 叶子,不查询记录或启动服务器。父布局决定本块位置;修改文字与链接只编辑叶子。保留稳定槽名与样式类,使片段和主题继续找到本区域,内容不会先被渲染成不透明字符串。
       
      -| 属性 | 值 | 样式 |
      -|------|-----|------|
      -| 文章 | / | |
      -| WebSocket | /#live | |
      -| 登录鉴权 | /admin | |
      -| 表单 | /new | |
      -| lib/net | /tools | |
      -
      -*`侧栏`*
      \ No newline at end of file
      +我们 **文本 = [读取本区域的终端 Markdown](文件.读文本(路径="components/content/side.md"))** 和 **叶子 = [保持简单 Markdown 内容](组件.正文(文本=`文本`, 槽="side-content"))**。
      +准备好内容后返回 *[保留这一块的语义与样式](组件.包裹(子节点=`叶子`, 种类="aside", 槽="side", 样式="side"))*。
      diff --git a/examples/web-net-site-zh/db/articles.mq.md b/examples/web-net-site-zh/db/articles.mq.md
      index 7beebcf..aeb980e 100644
      --- a/examples/web-net-site-zh/db/articles.mq.md
      +++ b/examples/web-net-site-zh/db/articles.mq.md
      @@ -1,27 +1,32 @@
       ---
       markup: occlusion
      +title: 文章结构与种子调用手册
      +import:
      +  document: lib/document.mq.md
       ---
       
      +本文件解释各个调用的用途;相邻的 [articles.tables.md](articles.tables.md) 保存可直接阅读的字面表。把 --fs-root 指向站点目录,读取需要 fs.read。字段、样式与正文是数据,读取不会执行文件中的说明。
      +
       ## 结构
       
      -`字段` =
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| result | any | 原生字面表的原始类型与列式数据形态 |
       
      -| 字段 | 类型 | 可空 |
      -|------|------|------|
      -| id | integer | false |
      -| title | text | false |
      -| body | text | true |
      +声明文章的字段、原生类型与可空约束;id 的数值类型和必填字段保持不变。数据库初始化器使用此表保证结构,不负责猜测用户数据的迁移。
       
      -*`字段`*
      +授予站点文件根的 fs.read 后可独立调用。章节名精确匹配且必须唯一;表头、行列不齐或动态表达式会保留原生文档诊断。需要实际样式时再调用 css;需要数据库记录时交给数据库资源。返回值不是 HTML,也不是已应用的浏览器效果。
      +
      +完成后返回*[读取 结构 的实际字面表](document.read_table(path="db/articles.tables.md", title="结构"))*.
       
       ## 种子
       
      -`行` =
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| result | any | 原生字面表的原始类型与列式数据形态 |
       
      -| id | title | body |
      -|----|-------|------|
      -| 1 | 欢迎来到网络扩展站 | 首页列表来自 SQLite。 |
      -| 2 | 登录门禁后台 | /admin 页面需要 session 会话。 |
      -| 3 | WebSocket 实时 | /live 端点会把你的消息实时回显。 |
      +提供起始演示文章,保留原来的 id、短链、摘要与正文。只有数据库初始化器确认空表后才应插入;读取本函数不会写入或重置现有文章。
       
      -*`行`*
      \ No newline at end of file
      +授予站点文件根的 fs.read 后可独立调用。章节名精确匹配且必须唯一;表头、行列不齐或动态表达式会保留原生文档诊断。需要实际样式时再调用 css;需要数据库记录时交给数据库资源。返回值不是 HTML,也不是已应用的浏览器效果。
      +
      +完成后返回*[读取 种子 的实际字面表](document.read_table(path="db/articles.tables.md", title="种子"))*.
      diff --git a/examples/web-net-site-zh/db/articles.tables.md b/examples/web-net-site-zh/db/articles.tables.md
      new file mode 100644
      index 0000000..0e22139
      --- /dev/null
      +++ b/examples/web-net-site-zh/db/articles.tables.md
      @@ -0,0 +1,23 @@
      +# Article data
      +
      +Literal article schema and demonstration content. Reading these tables does not open a database or insert rows. Follow articles.mq.md for callable use; the database initializer decides whether seeding is appropriate.
      +
      +## 结构
      +
      +Field definitions for the native database initializer; nullable values remain booleans.
      +
      +| 字段 | 类型 | 可空 |
      +|------|------|------|
      +| id | integer | false |
      +| title | text | false |
      +| body | text | true |
      +
      +## 种子
      +
      +Initial demonstration records in their original column-oriented shape; ids and stable slugs retain their meaning.
      +
      +| id | title | body |
      +|----|-------|------|
      +| 1 | 欢迎来到网络扩展站 | 首页列表来自 SQLite。 |
      +| 2 | 登录门禁后台 | /admin 页面需要 session 会话。 |
      +| 3 | WebSocket 实时 | /live 端点会把你的消息实时回显。 |
      diff --git a/examples/web-net-site-zh/db/index.mq.md b/examples/web-net-site-zh/db/index.mq.md
      index 1b4c189..b4f4f08 100644
      --- a/examples/web-net-site-zh/db/index.mq.md
      +++ b/examples/web-net-site-zh/db/index.mq.md
      @@ -1,21 +1,37 @@
       ---
       markup: occlusion
      -title: db/index
      -description: 打开 sqlite、建表、幂等种子。
      -导入:
      -  网页: ext/web/网页.mq.md
      +title: web-net-site-zh database lifecycle
      +import:
      +  data: ext/data/db.mq.md
         articles: articles.mq.md
      +  fs: lib/fs.mq.md
      +  text: lib/text.mq.md
       ---
       
      +The database entry connects schema and literal seed leaves to the actual data resource. It no longer uses the removed web database constructor. Grant fs.write and plugin with the site directory as --fs-root; the SQLite path is resolved through that native root rather than the process working directory.
      +
       ## 打开
       
      -**store = > 网页.数据库 地址="sqlite:data/site-net-zh.db"**
      -**字段 = > articles.结构**
      -> `store`.初始化 名=articles 字段=`字段`
      -**行 = > store.查询 表="articles" 上限=1**
      -1. `行`
      -  *store*
      -2. *
      -  **种子 = > articles.种子**
      -  > `store`.插入 表=articles 行=`种子`
      -  *store*
      \ No newline at end of file
      +| 参数 | 类型 | 默认 | 说明 |
      +|---|---|---|---|
      +| url | any | None | None selects data/site-net-zh.db under the site root; tests provide a disposable explicit URI |
      +
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| result | any | Initialized articles database resource with existing rows preserved |
      +
      +Use `url`=None to open the site's local database. Create the default data directory through native file operations, then resolve the actual SQLite filename within the granted root. An explicit SQLite path goes through the same root and symlink checks before the native database resource receives it. Other supported database URIs retain their resource-specific backend contract; they are not sandboxed by filesystem permissions.
      +
      +The schema reader preserves native field types and nullability. Initialization ensures the table exists, queries one row to distinguish an empty table, and inserts the original demonstration content only into an empty table. An existing or partly populated table is kept unchanged. This is not a column migrator, data repair tool or reason to delete a user's articles. A native connection, schema or insert diagnostic stops the caller before it starts serving.
      +
      +For isolated verification choose a caller-owned temporary SQLite file and copy the article data leaf under that granted site root. Keep the returned resource in the same program for subsequent queries. Close the process before cleaning its owned directory; do not run tests against the example's existing data directory.
      +
      +1. `url` == None
      +  We **[Create only the site's default data directory](fs.make_dirs(path="data"))** and **file = [Resolve its database filename](fs.resolve(path="data/site-net-zh.db"))** and **url = "sqlite:" + file**.
      +1. [The explicit or default URI selects SQLite](text.starts_with(text=`url`, prefix="sqlite:"))
      +  We **file = [Read the selected SQLite path](text.replace(text=`url`, old="sqlite:", new="", count=1))** and **file = [Apply the native file-root policy](fs.resolve(path=`file`))** and **url = "sqlite:" + file**.
      +We **store = [Open the selected actual database resource](data.db(url=`url`))** and **fields = [Read the documented article schema](articles.结构())**.
      +We **[Ensure the table without clearing it](> `store`.init name="articles" fields=`fields`)** and **existing = [Check whether business records already exist](> `store`.select table="articles" limit=1)**.
      +1. not `existing`
      +  We **seed = [Read the original demonstration data](articles.种子())** and **[Seed only the empty article table](> `store`.insert table="articles" rows=`seed`)**.
      +Once the selected database is ready, return *store* for the site's resource bindings.
      diff --git a/examples/web-net-site-zh/forms.mq.md b/examples/web-net-site-zh/forms.mq.md
      new file mode 100644
      index 0000000..2c616d9
      --- /dev/null
      +++ b/examples/web-net-site-zh/forms.mq.md
      @@ -0,0 +1,38 @@
      +---
      +markup: occlusion
      +title: 文章发布表单的唯一规则来源
      +import:
      +  表单: ext/data/表单.mq.md
      +---
      +
      +服务入口以 article 挂载本资源,发布页只安放该标识的引用。字段、校验与提交因此共用一份定义。它是公开的演示发布表单,原生后台仍保留登录门禁;不要把两者的策略混为一谈。
      +
      +## 文章
      +
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| 结果 | any | 带标题/正文字段、原始校验规则与返回地址的插入表单 |
      +
      +调用需要 plugin。标题必填且最多 120 字符,正文可空且最多 8000 字符,保持原示例的服务器规则。表格逐行表达字段与规则,布尔必填值不是字符串。构造不插入业务记录,也不认证用户;请求提交时才使用应用实际数据库与当前 CSRF。
      +
      +成功提交显式返回首页文章列表;不合格输入保留校验消息供修正。按钮文案留在同一资源,不再手写 form HTML 或另一份客户端校验程序。调用者保留每次更新返回的新资源,再把最终值交给挂载。
      +
      +字段表中的 name 对应数据库列,label 只决定显示,type 选择输入框或多行文本。required 的可见提示不能代替服务器规则;绕过浏览器校验仍会得到“标题不能为空”的原生重试页。表单的成功返回地址为首页,失败时仍留在表单响应中,并继续保留当前 CSRF 供再次提交。
      +
      +`字段` =
      +
      +| @ | name | label | type | required |
      +|---|---|---|---|---|
      +| 1 | title | 标题 | text | True |
      +| 2 | body | 正文 | textarea | False |
      +
      +`规则` =
      +
      +| @ | field | rule | message |
      +|---|---|---|---|
      +| 1 | title | required | 标题不能为空 |
      +| 2 | title | max:120 | 标题太长 |
      +| 3 | body | max:8000 | 正文太长 |
      +
      +我们 **资源 = [构造实际文章插入资源](表单.构造(表="articles"))**、**资源 = [绑定清楚列出的字段](表单.字段(资源=`资源`, 定义=`字段`))** 和 **资源 = [绑定服务器真正执行的规则](表单.规则(资源=`资源`, 定义=`规则`))**。
      +准备完成后返回 *[保留提交文案与显式成功返回目标](表单.文案(资源=`资源`, 提交="发布", 取消="取消", 返回地址="/"))*。
      diff --git a/examples/web-net-site-zh/index.mq.md b/examples/web-net-site-zh/index.mq.md
      index 120e732..790f370 100644
      --- a/examples/web-net-site-zh/index.mq.md
      +++ b/examples/web-net-site-zh/index.mq.md
      @@ -1,113 +1,71 @@
       ---
       markup: occlusion
      -title: 网络扩展站(中文)
      -description: 首页 + /about + /new(表单)+ /tools(lib/net)+ /admin(登录鉴权)+ /live(WebSocket)。
      -导入:
      +type: web
      +view: main
      +route: /
      +title: 网络扩展站
      +import:
      +  布局: components/index.mq.md
      +  首页: components/home.mq.md
      +  数据库: db/index.mq.md
      +  表单定义: forms.mq.md
      +  主题: styles/shell.mq.md
         网页: ext/web/网页.mq.md
      -  net: lib/网络.mq.md
      -  text: lib/text.mq.md
      -  shell: styles/shell.mq.md
      -  nav: components/nav.mq.md
      -  side: components/side.mq.md
      -  foot: components/foot.mq.md
      -  articles: db/articles.mq.md
      -  db: db/index.mq.md
      +  表单: ext/data/表单.mq.md
      +  后台: ext/data/后台.mq.md
      +  鉴权: ext/security/鉴权.mq.md
      +  实时: ext/net/实时.mq.md
      +  文件: lib/文件.mq.md
      +  result: lib/result.mq.md
       ---
       
      -# main
      +从本入口依次阅读组件入口、Markdown 内容叶子、数据库、表单资源与浏览器客户端。首页、关于、发布与工具页都是显式路由 Document;后台保留原生登录门禁,/live 单独归网络资源管理。页面不再依赖已移除的装配接口,启动也不会拼接整页 HTML。
       
      -`首页` =
      +## main
       
      -| 组件 | 样式 |
      -|------|------|
      -| nav.`导航` | shell.`顶栏` |
      -| side.`侧栏` | shell.`侧栏面板` |
      -| foot.`页脚` | |
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| 结果 | list | 共享递归布局内的介绍、实时控件与请求期间的文章列表 |
       
      -`列表` =
      +启动装配只读取终端 Markdown 内容,数据库查询保留为请求资源。发布后下一次访问就能看到新文章,无需重启或重新创建页面。客户端使用原生控件和官方桥;布局本身不初始化数据库或清除业务数据。编辑一块内容时沿组件导入找到对应叶子,不在首页复制导航、侧栏和页脚。
       
      -| 属性 | 值 | 样式 |
      -|------|-----|------|
      -| title | articles.`articles`.title | shell.`卡片标题` |
      -| body | articles.`articles`.body | shell.`卡片正文` |
      +我们先 **正文 = [组合首页三个独立职责](首页.节点())**,随后返回 *[安放到共享的递归布局](布局.框架(正文=`正文`))*。
       
      -`文章字段` =
      +## serve
       
      -| 字段 | 标签 | 类型 | 必填 | 默认 |
      -|------|------|------|------|------|
      -| title | 标题 | text | true | |
      -| body | 正文 | textarea | false | |
      +| 参数 | 类型 | 默认 | 说明 |
      +|---|---|---|---|
      +| root | text | "examples/web-net-site-zh" | 相对仓库的显式站点发现目录 |
      +| port | number | 18084 | 本机回环监听端口 |
      +| url | any | None | None 使用站点根的 SQLite;验收指定独占临时 URI |
       
      -`文章规则` =
      +| 返回 | 类型 | 说明 |
      +|---|---|---|
      +| 结果 | map | 保留文章、表单、鉴权与回显资源的阻塞监听结果 |
       
      -| 字段 | 规则 | 消息 |
      -|------|------|------|
      -| title | required | 标题不能为空 |
      -| title | max:120 | 标题太长 |
      -| body | max:8000 | 正文太长 |
      +从仓库根使用`root`="examples/web-net-site-zh"、`port`=18084、`url`=None,授予 plugin,fs.write,network.write,并设置 --fs-root examples/web-net-site-zh。先通过开发手册把当前浏览器产物放进 public/generated。缺少运行时文件时停止,不呈现看似可用的空控件。
       
      -**store = > db.打开**
      -**page = > 网页.页面 标题="网络扩展站" 引言="

      网络扩展站

      SQLite 文章列表、WebSocket 实时小部件、登录门禁后台、以及标准库 lib/net 的解析工具。

      实时 WebSocket

      connecting…

      "** -**page = > page.组件装配 组件=`首页`** -**page = > page.主体装配 主体=`列表`** +数据库只为空表播种,已有文章保留。主题由原始属性表编译后显式写到生成目录,再发现页面并按顺序启用后台、绑定鉴权、挂载公开文章表单、绑定回显。每一步保留新应用,最后才监听。本地 admin/secret 是演示夹具,真实部署必须替换账户来源与网络策略;公开回显只绑定回环地址。服务阻塞于当前进程,关闭由调用者负责。显式 url 用于隔离验收,SQLite 路径仍经过授权根检查;不能为测试删除示例原有 data 目录。主题是可再生文件,写入失败会阻止后续监听,单文件原子替换不意味着数据库和样式之间存在事务。 -**about = > 网页.页面 标题="关于" 引言="

      关于

      演示网络扩展后的 web 库:会话、登录鉴权、WebSocket、multipart/cookie 解析。

      "** -**about = > about.组件装配 组件=`首页`** +`产物` = - +| 文件 | +|---| +| public/generated/marqdo_wasm.wasm | +| public/generated/marqdo-bridge.js | -**解析请求 = > net.解析Cookie 内容="session=abc123; theme=dark"** -**请求块 = [1](access(解析请求, "1"))** +- [在启动前确认实际运行时文件](for 产物 as 路径) + 1. not [运行时资源确实存在](文件.存在(路径=`路径`)) + 返回 *[指出所需浏览器准备](result.error(code="net_site.browser_assets", message="请先把当前 WASM 与官方桥构建到 public/generated", operation="serve"))*。 +我们 **存储 = [打开并保留文章数据库](数据库.打开(url=`url`))**,**样式 = [编译既有的声明式主题](主题.编译())**,并 **[建立明确的生成目录](文件.建目录(路径="public/generated"))**、**[原生写入本次主题](文件.原子写文本(路径="public/generated/theme.css", 内容=`样式`))**。 +我们 **应用 = [发现已声明页面并保留站点上下文](网页.准备站点(根=`root`, 主机="127.0.0.1", 端口=`port`, 数据库=`存储`, 静态目录="public"))** 和 **应用 = [保留原生后台能力](后台.启用(应用=`应用`))**。 -**解析响应 = > net.解析Cookie 内容="id=42; Path=/; HttpOnly; SameSite=Lax" 是响应头=True** -**响应块 = [1](access(解析响应, "1"))** +`用户` = -`边界` = ----b +| @ | username | password | role | +|---|---|---|---| +| 1 | admin | secret | admin | -`正文` = "--`边界`\nContent-Disposition: form-data; name=\"title\"\n\n你好\n--`边界`\nContent-Disposition: form-data; name=\"封面\"; filename=\"pic.png\"\nContent-Type: image/png\n\n<字节>\n--`边界`--\n" - -**多部分 = > net.解析多部分 正文=`正文` 边界=`边界`** -**字段块 = [1](access(多部分, "1"))** -**文件块 = [2](access(多部分, "2"))** - -`工具段` = - -| 段 | -|----| -|

      网络工具

      由 lib/net 提供的解析演示:解析Cookie 与 解析多部分。

      | -|

      Cookie 请求头

      | -| [name](`请求块`)=[value](`请求块`) | -|

      Set-Cookie 响应头

      | -| [name](`响应块`)=[value](`响应块`) · HttpOnly=[http_only](`响应块`) | -|

      多部分字段

      | -| [name](`字段块`)=[value](`字段块`) | -|

      多部分文件

      | -| [name](`文件块`) · [filename](`文件块`) · [content_type](`文件块`) | -|

      | - -**工具引言 = > text.str_join xs=`工具段` sep=""** -**tools = > 网页.页面 标题="工具" 引言=`工具引言`** -**tools = > tools.组件装配 组件=`首页`** - -**article_form = > 网页.表单 表="articles" 动作="插入"** -**article_form = > article_form.字段 字段=`文章字段`** -**article_form = > article_form.规则 规则=`文章规则`** - -**new = > 网页.页面 标题="发布" 引言="

      发布

      表单插入到 articles 表。

      "** -**new = > new.组件装配 组件=`首页`** -**new = > new.表单装配 id="article" 表单=article_form** - -`管理员` = - -| 行 | 用户名 | 密码 | -|----|--------|------| -| 1 | admin | secret | - -**app = > 网页.应用 页面=page 数据库=store 后台=True 主机="127.0.0.1" 端口=18084** -**app = > app.路由 路径="/about" 页面=about** -**app = > app.路由 路径="/new" 页面=new** -**app = > app.路由 路径="/tools" 页面=tools** -**app = > app.静态 目录="public" 挂载="/static"** -**app = > app.路由实时 路径="/live" 回显=True** -**app = > app.鉴权 用户表=`管理员` 会话时长=3600** -> `app`.监听 \ No newline at end of file +我们 **应用 = [绑定真实登录会话与后台门禁](鉴权.绑定(应用=`应用`, 用户=`用户`, 登录路径="/admin/login", 登录返回="/admin", 退出返回="/"))**,**文章 = [构造共享校验资源](表单定义.文章())** 和 **应用 = [明确挂载公开发布表单](表单.挂载(应用=`应用`, 标识="article", 资源=`文章`))**。 +接着 **应用 = [绑定本地演示的公开回显资源](实时.绑定(应用=`应用`, 路径="/live", 模式="echo", 需要登录=False))**。 +全部资源就绪后返回 *[在保留的站点根中开始监听](网页.监听(应用=`应用`))*。 diff --git a/examples/web-net-site-zh/pages/about.mq.md b/examples/web-net-site-zh/pages/about.mq.md new file mode 100644 index 0000000..6892fe3 --- /dev/null +++ b/examples/web-net-site-zh/pages/about.mq.md @@ -0,0 +1,24 @@ +--- +markup: occlusion +type: web +view: main +route: /about +title: 关于 +import: + 组件: ext/web/网页/组件/索引.mq.md + 布局: ../components/index.mq.md + 文件: lib/文件.mq.md +--- + +本 Document 用元数据显式声明 /about 路径。说明留在终端 Markdown,导航、侧栏和页脚归共享布局。解释页不查询数据库、不配置服务,也不会隐式注册其他业务路径。 + +## main + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | list | 共享站点框架中的关于说明 | + +启动阶段只装配结构,授予 fs.read 读取 Markdown 叶子。沿布局导入可以独立修改一个区域,无需在这里重写整页壳。内容是普通 Markdown,不把源码手册的执行标记混进用户页面。 路由来自本页声明,首次阅读即可判断入口与内容来源。 + +我们 **文本 = [读取本页的终端说明](文件.读文本(路径="components/content/about.md"))** 和 **正文 = [保留简单 Markdown 内容](组件.正文(文本=`文本`, 槽="intro"))**。 +最后返回 *[放进共享递归布局](布局.框架(正文=`正文`))*。 diff --git a/examples/web-net-site-zh/pages/new.mq.md b/examples/web-net-site-zh/pages/new.mq.md new file mode 100644 index 0000000..455b924 --- /dev/null +++ b/examples/web-net-site-zh/pages/new.mq.md @@ -0,0 +1,27 @@ +--- +markup: occlusion +type: web +view: main +route: /new +title: 发布 +import: + 组件: ext/web/网页/组件/索引.mq.md + 布局: ../components/index.mq.md + 文件: lib/文件.mq.md + 表单: ext/data/表单.mq.md + 表: lib/表.mq.md +--- + +本 Document 用元数据显式声明 /new 路径。说明留在终端 Markdown,导航、侧栏和页脚归共享布局。本页只放 article 表单引用,字段、校验与真实提交处理器由独立资源定义。 + +## main + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | list | 共享站点框架中的发布说明与表单请求资源 | + +启动阶段只装配结构,授予 fs.read 读取 Markdown 叶子。服务器在每次请求中才为实际会话准备 CSRF 与返回路径,不能在启动时写死令牌。未知表单标识是真实请求错误;页面可见不替代提交地址的访问策略。 路由来自本页声明,首次阅读即可判断入口与内容来源。 + +我们 **文本 = [读取本页的终端说明](文件.读文本(路径="components/content/new.md"))** 和 **正文 = [保留简单 Markdown 内容](组件.正文(文本=`文本`, 槽="intro"))**。 +我们 **引用 = [引用实际挂载的文章表单](表单.引用(标识="article"))**、**操作 = [安放请求期间解析的表单](组件.请求资源(值=`引用`, 槽="article-form"))** 和 **正文 = [让说明先于填写操作](表.拼接(a=`正文`, b=`操作`))**。 +最后返回 *[放进共享递归布局](布局.框架(正文=`正文`))*。 diff --git a/examples/web-net-site-zh/pages/tools.mq.md b/examples/web-net-site-zh/pages/tools.mq.md new file mode 100644 index 0000000..0b7c249 --- /dev/null +++ b/examples/web-net-site-zh/pages/tools.mq.md @@ -0,0 +1,73 @@ +--- +markup: occlusion +type: web +view: main +route: /tools +title: 网络解析工具 +import: + 网络: lib/网络.mq.md + 文件: lib/文件.mq.md + 表: lib/表.mq.md + 组件: ext/web/网页/组件/索引.mq.md + 布局: ../components/index.mq.md +--- + +本页对明确的本地夹具执行标准网络解析器,不访问外部 HTTP。Cookie 头是纯文本,multipart 正文是 content 目录中的终端协议数据。预格式文本控件展示实际记录,既不拼 HTML,也不把手抄的预期值当作执行结果。 + +## _面板 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 标题 | text | 必填 | 作者控制的观察项标题 | +| 值 | any | 必填 | 解析器实际返回的原生值 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | list | Markdown 标题与转义的预格式文本节点 | + +输入`标题`与`值`,用这个纯构造把含义与观察结果放在一起。标题来自作者,协议输入只作为文本展示,不能变成页面结构或执行表达式。原生值转为显示文本后由 pre 保留字符;即使包含尖括号或引号也不会作为 HTML 解析。本函数不读取文件,也不运行解析器。 + +我们 **标题文本 = "## " + 标题**、**说明 = [用 Markdown 解释观察项目](组件.正文(文本=`标题文本`))** 和 **文本 = [保留原生结构的实际显示值](str(值))**、**数据 = [按纯文本展示观察结果](组件.控件(种类="pre", 值=`文本`))**。 +最后返回 *[将说明与实际数据放在一起](表.拼接(a=`说明`, b=`数据`))*。 + +## _Cookie + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | list | 真实请求 Cookie 与响应 Set-Cookie 两种解析结果 | + +请求模式解析 session 与 theme 键值;响应模式把 Path、HttpOnly 与 SameSite 视为同一个 id Cookie 的属性。两次调用都使用维护中的标准库,结果形态的差异来自真实模式,不是作者拼接的展示。 + +这是确定性的文本夹具,不代表当前浏览器登录,也不会写 Cookie 或把夹具当作有效凭据。面板保留所有返回字段,读者能直接观察名称、值和标志。解析为纯计算,不需要插件或网络授权。 + +我们 **请求 = [解析明确的请求头夹具](网络.解析Cookie(内容="session=abc123; theme=dark"))** 和 **响应 = [按响应头模式解析属性](网络.解析Cookie(内容="id=42; Path=/; HttpOnly; SameSite=Lax", 是响应头=True))**。 +接着 **请求面板 = [展示真实请求键值](_面板(标题="Cookie 请求头", 值=`请求`))** 和 **响应面板 = [展示真实响应属性](_面板(标题="Set-Cookie 响应头", 值=`响应`))**。 +观察完成后返回 *[相邻保留两种解析模式](表.拼接(a=`请求面板`, b=`响应面板`))*。 + +## _多部分 + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | list | 实际 multipart 文本字段与文件部分的观察面板 | + +授予 fs.read,从站点根读取 CRLF 协议夹具,边界保持文件声明的 net-boundary。title 部分是“你好”,cover 部分标记 pic.png 与 image/png。文件值仅为字面 <字节>,不声称包含真正的二进制图片或执行上传。 + +解析器返回原生列表,使用从零开始的取项选择两个部分。夹具缺失或格式错误保留真实文件/解析诊断,不能改为固定预期答案。展示协议内容不会提取文件、访问网络或解释其中的 Markdown。 + +我们 **正文 = [原生读取精确的本地协议文本](文件.读文本(路径="components/content/multipart.txt"))** 和 **部分 = [解析边界与内容处置字段](网络.解析多部分(正文=`正文`, 边界="net-boundary"))**。 +接着 **字段 = [读取第一条真实部分记录](表.首(list=`部分`))**、**文件部分 = [读取从零开始的第二条记录](表.取(xs=`部分`, i=1))**、**字段面板 = [展示真实表单字段](_面板(标题="多部分字段", 值=`字段`))** 和 **文件面板 = [展示真实文件元数据](_面板(标题="多部分文件", 值=`文件部分`))**。 +最后返回 *[保留两种实际观察](表.拼接(a=`字段面板`, b=`文件面板`))*。 + +## main + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | list | 共享布局内的四项真实标准库解析观察 | + +装配需要 fs.read 读取 multipart 夹具与共享布局叶子,解析本身是纯计算。四个面板保留请求 Cookie、响应 Cookie、multipart 字段和文件元数据。修改夹具会改变展示结果,因为页面运行真实标准库,而不是显示事先编好的答案。 + +用户仍可从共享导航去发布、后台或实时区域。面板内只展示纯文本,协议中的 <字节> 不会成为标签。这个工具页不代表真实网络流量、登录身份或用户上传。 + +我们 **介绍 = [解释本地解析演示](组件.正文(文本="# 网络工具\n\n由标准网络库提供真实 Cookie 与 multipart 解析结果。"))**、**Cookie = [观察请求与响应两种模式](_Cookie())** 和 **多部分 = [观察实际字段及文件部分](_多部分())**。 +接着 **正文 = [说明位于观察结果之前](表.拼接(a=`介绍`, b=`Cookie`))** 和 **正文 = [保留后续 multipart 结果](表.拼接(a=`正文`, b=`多部分`))**。 +全部观察就绪后返回 *[放进共享站点框架](布局.框架(正文=`正文`))*。 diff --git a/examples/web-net-site-zh/public/client.mq.md b/examples/web-net-site-zh/public/client.mq.md new file mode 100644 index 0000000..eedff0f --- /dev/null +++ b/examples/web-net-site-zh/public/client.mq.md @@ -0,0 +1,167 @@ +--- +markup: occlusion +title: 网络站点的 Marqdo 回显客户端 +import: + 浏览器: lib/浏览器.mq.md + 表: lib/表.mq.md + text: lib/text.mq.md +--- + +客户端拥有连接标识和纯文本消息记录,原生控件由 components/live.mq.md 声明,服务端绑定同源 /live 路由。这里只生成官方桥效果,不通过外联脚本操纵页面。连接状态保留旧控件的 connected/closed 文本作为可观察协议。 + +# main + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | map | 事件绑定、套接字打开与初始状态效果 | + +入口使用对象 main 保留后续回调需要的连接标识和消息记录。点击与 Enter 都携带当前输入值,实际收到回显后才追加日志。连接成功启用发送,错误或关闭则禁用。重载重建演示状态,不声称提供持久历史或自动重连。 + +事件表中的调用名对应下面的直接回调,值选择器显式指向输入。浏览器桥负责真正的运输和 DOM 更新;这份代码的纯效果构造无需插件。普通辅助函数显式接收连接标识,避免假定任意嵌套调用都能捕获入口状态。 + +官方桥按事件表传入 value,键盘事件另外携带 key,消息回调携带 data,错误回调携带 error,所以这些公共回调保留实际字段名。声明中的 then_open、then_message 等是既有运输协议,不是新的作者语言。相对 /live 路径跟随页面真实主机与端口,避免把本地验收端口写死在客户端。 + +我们 **连接 = "live"** 和 **消息 = ""**,保留入口状态。 + +`绑定` = + +| @ | 选择器 | 事件 | 调用 | 值选择器 | +|---|---|---|---|---| +| 1 | "#live-send" | click | 发送 | "#live-msg" | +| 2 | "#live-msg" | keydown | 按键 | "#live-msg" | + +`打开` = + +| op | id | url | then_open | then_message | then_error | then_close | +|---|---|---|---|---|---|---| +| open | `连接` | /live | 已打开 | 收到消息 | 出错 | 已关闭 | + +我们 **事件 = [保留原生控件事件](表.设(map=None, key="wire", value=`绑定`))** 和 **运输 = [描述同源实时连接](浏览器.套接字(规格=`打开`))**。 +最后返回 *[将事件与运输效果一起交给官方桥](浏览器.合并(甲=`事件`, 乙=`运输`))*。 + +## _状态 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 文本 | text | 必填 | 显示给用户的纯文本连接反馈 | +| 禁用 | bool | 必填 | 发送按钮真实布尔属性 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | map | 状态文字与按钮属性两种效果的组合 | + +使用`文本`和`禁用`,让连接反馈与按钮可用性保持一致。False 令桥移除 disabled,字符串 false 则仍为存在的布尔属性,不能混用。状态更新不清空消息、不发送重试,也不创建第二个连接;它只描述两个独立效果种类。 + +我们 **属性 = [保留真实布尔禁用值](表.设(map=None, key="disabled", value=`禁用`))**、**状态 = [描述纯文本反馈](浏览器.设文本(选择器="#live-status", 文本=`文本`))** 和 **按钮 = [描述实际发送可用性](浏览器.设属性(选择器="#live-send", 属性=`属性`))**。 +最后返回 *[保留独立效果种类](浏览器.合并(甲=`状态`, 乙=`按钮`))*。 + +## 已打开 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| ok | bool | True | 官方桥给出的实际打开结果 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | map | 成功时启用发送,否则保留失败状态 | + +使用`ok`=True 接收打开回调。成功只证明运输已就绪,消息交付仍由真实回显观察。打开失败不添加假的欢迎消息,也不悄悄重连。状态和按钮通过同一个辅助函数更新,避免用户看到失败却仍能点击发送。 + +1. `ok` + 返回 *[真实打开后允许发送](_状态(文本="connected", 禁用=False))*。 +否则返回 *[保持打开失败可见](_状态(文本="connection failed", 禁用=True))*。 + +## _发送 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 值 | text | 必填 | 点击或 Enter 交来的输入文本 | +| 通道 | text | 必填 | 入口保留并显式传入的现有连接标识 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 非空消息发送效果;去空白后为空则返回 None | + +使用`值`和`通道`复用原控件的发送策略。先去掉两端空白,空消息不发送。内容只是文本,不能成为命令或 HTML;发送效果不表示已经交付,日志必须等待真实回显。这一普通辅助调用显式接收通道,不依赖直接回调才有的入口状态。 + +我们 **内容 = [保留原有去空白策略](text.str_trim(s=`值`))**。 +1. `内容` == "" + 返回 *None*,表示没有发送。 + +`操作` = + +| op | id | data | +|---|---|---| +| send | `通道` | `内容` | + +准备完成后返回 *[发送一个真实非空消息](浏览器.套接字(规格=`操作`))*。 + +## 发送 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | text | "" | 点击绑定从输入控件取得的当前文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 共享非空发送策略的结果 | + +使用`value`="" 接收点击值。直接浏览器回调读取保留的连接状态,再显式传给辅助函数。空白输入不会产生发送效果;点击也不能提前追加回显,确保页面只展示观察到的服务端帧。输入仍留在控件里,保留原示例的重复编辑方式。 + +最后返回 *[将点击交给共享发送策略](_发送(值=`value`, 通道=`连接`))*。 + +## 按键 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| key | text | "" | 官方桥提供的真实键名 | +| value | text | "" | 该事件值选择器取得的输入文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | Enter 使用共享发送策略,其他键返回 None | + +使用`key`=""与`value`="" 接收键盘回调。只在 Enter 时发送,避免每次编辑键都产生消息。点击和 Enter 共享相同的去空白、空输入忽略行为,既不重复安装处理器,也不创建另一条连接或提前生成本地回显。 + +1. `key` == "Enter" + 返回 *[使用与按钮相同的发送规则](_发送(值=`value`, 通道=`连接`))*。 +普通编辑键返回 *None*。 + +## 收到消息 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| data | text | "" | 服务器实际发来的回显文本帧 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | map | 包含已保留消息的纯文本更新 | + +使用`data`="" 接收实际消息。每个帧追加原来的 echo: 前缀与换行,保留之前的消息。文本效果通过桥安全展示,尖括号与引号按字面保留;重载才开始新的演示记录,不声称落盘。直接回调更新入口消息状态。 + +我们 **消息 = [保留下一条已观察回显](消息 + "echo: " + data + "\n")**。 +最后返回 *[以纯文本展示完整记录](浏览器.设文本(选择器="#live-out", 文本=`消息`))*。 + +## 出错 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| error | text | "" | 浏览器运输报告的实际错误描述 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | map | 可见错误反馈与禁用发送 | + +使用`error`="",把运输失败放在控件旁边。历史消息仍可阅读,失败不清空记录、不尝试新发送,也不悄悄重连。用户可重载页面建立新会话;这里的效果不等于故障恢复成功,按钮应保持不可用。 + +我们 **文本 = "error: " + error**,最后返回 *[让错误与可用性一致](_状态(文本=`文本`, 禁用=True))*。 + +## 已关闭 + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | map | 关闭反馈与禁用发送,保留历史消息 | + +连接关闭后,既有消息仍可阅读,发送按钮需要禁用。此回调不清空入口状态,也不自动创建另一条连接。后续真实发送应由新页面会话中的实际打开事件启用;不能把关闭当作正常消息交付或显示假的重连成功。 + +关闭后返回 *[保留真实结束状态](_状态(文本="closed", 禁用=True))*。 diff --git a/examples/web-net-site-zh/public/live.js b/examples/web-net-site-zh/public/live.js deleted file mode 100644 index cfd2d03..0000000 --- a/examples/web-net-site-zh/public/live.js +++ /dev/null @@ -1,40 +0,0 @@ -// /live WebSocket 端点的小部件。 -// 连接 ws://host/live,发送输入,展示回显。 -(function () { - var out = document.getElementById("live-out"); - var input = document.getElementById("live-msg"); - var btn = document.getElementById("live-send"); - var status = document.getElementById("live-status"); - if (!out || !input || !btn || !status) return; - - var proto = location.protocol === "https:" ? "wss" : "ws"; - var ws = new WebSocket(proto + "://" + location.host + "/live"); - status.textContent = "connecting…"; - - ws.onopen = function () { - status.textContent = "connected"; - btn.disabled = false; - }; - ws.onmessage = function (ev) { - var p = document.createElement("p"); - p.textContent = "echo: " + ev.data; - out.appendChild(p); - out.scrollTop = out.scrollHeight; - }; - ws.onclose = function () { - status.textContent = "closed"; - btn.disabled = true; - }; - ws.onerror = function () { - status.textContent = "error"; - btn.disabled = true; - }; - - btn.onclick = function () { - var m = input.value.trim(); - if (m) ws.send(m); - }; - input.addEventListener("keydown", function (e) { - if (e.key === "Enter") btn.onclick(); - }); -})(); diff --git a/examples/web-net-site-zh/styles/shell.mq.md b/examples/web-net-site-zh/styles/shell.mq.md index ea8d88a..a284355 100644 --- a/examples/web-net-site-zh/styles/shell.mq.md +++ b/examples/web-net-site-zh/styles/shell.mq.md @@ -1,46 +1,100 @@ --- markup: occlusion +title: 原始主题属性与显式编译 +import: + 网页: ext/web/网页.mq.md + text: lib/text.mq.md --- +主题保留原站的四组属性值,控件与容器只引用类名。它没有大段作者 CSS 或页面字符串。服务入口调用编译,将结果通过原生文件写到明确的生成路径,再让布局引用该资源。 + ## 顶栏 -`顶栏` = +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 导航背景与底部分隔线 | + +导航内容采用白色背景,并以浅色细线与下方内容分开。返回值保留原有颜色和边框,不负责导航链接或几何布局。它是纯属性数据,调用不加载插件、不写文件;编译阶段才把它映射到原生导航类。 + +`属性` = | 属性 | 值 | -|------|-----| +|---|---| | background | #ffffff | | border-bottom | 1px solid #e7e5e4 | -*`顶栏`* +属性明确后返回 *属性*,供主题编译继续使用。 ## 侧栏面板 -`侧栏面板` = +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 侧栏背景属性 | + +侧栏用浅色背景区分任务跳转与主体内容。这里只保留原有背景值,不重复设置父行宽度或移动端折叠行为。纯属性表可以独立阅读和比较,调用不查询数据,也不生成样式文件;父布局继续拥有侧栏位置。 + +`属性` = | 属性 | 值 | -|------|-----| +|---|---| | background | #f5f5f4 | -*`侧栏面板`* +属性明确后返回 *属性*,供主题编译继续使用。 ## 卡片标题 -`卡片标题` = +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 文章标题字号与间距属性 | + +请求查询资源生成的文章卡片使用这些标题声明,保留原始字号和下边距。标题内容仍由真实记录提供且经过转义,样式不会注入文章文字或链接。属性构造为纯计算,不运行查询;选择器在编译阶段与原生卡片结构对齐。 + +`属性` = | 属性 | 值 | -|------|-----| +|---|---| | font-size | 1.15rem | | margin | 0 0 0.35rem | -*`卡片标题`* +属性明确后返回 *属性*,供主题编译继续使用。 ## 卡片正文 -`卡片正文` = +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 文章正文颜色与间距属性 | + +文章正文保留原站的次级文字颜色和零外边距。此表不截断或替换正文,也不改变 Markdown 与数据字段之间的约定。它只提供纯属性数据,布局、渲染和数据库生命周期都在各自模块,编译后再引用共同的主题文件。 + +`属性` = | 属性 | 值 | -|------|-----| +|---|---| | color | #57534e | | margin | 0 | -*`卡片正文`* \ No newline at end of file +属性明确后返回 *属性*,供主题编译继续使用。 + +## 编译 + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | text | 四个原始属性表编译成的有序 CSS | + +调用需要 plugin,按导航、侧栏、卡片标题和正文的顺序编译。选择器直接对应原生组件与查询卡片,避免重复声明一份旧页面绑定布局。所有属性值保留原站定义;通用响应式几何仍由 View 运行时负责。 + +本函数不写文件或挂载资源,调用者收到文本后通过原生文件能力写入明确目标。编译失败应阻止监听,不能退回旧样式假装本轮成功。修改单块属性只改上面的对应函数,验证编译结果与真实窄屏页面,避免颜色保留却丢失结构作用。生成文件可以重建,原始声明仍以本文件为准。 + +我们 **导航 = [读取原有导航属性](顶栏())**、**侧栏 = [读取原有侧栏属性](侧栏面板())**、**标题 = [读取原有标题属性](卡片标题())** 和 **正文 = [读取原有正文属性](卡片正文())**。 +随后 **导航样式 = [编译导航类](网页.编译样式(名称="topnav", 属性=`导航`))**、**侧栏样式 = [编译侧栏类](网页.编译样式(名称="side", 属性=`侧栏`))**、**标题样式 = [编译实际卡片标题选择器](网页.编译样式(名称="content.cards h2", 属性=`标题`))** 和 **正文样式 = [编译实际卡片正文选择器](网页.编译样式(名称="content.cards p", 属性=`正文`))**。 + +`片段` = + +| 样式 | +|---| +| `导航样式` | +| `侧栏样式` | +| `标题样式` | +| `正文样式` | + +编译完成后返回 *[保留声明顺序](text.str_join(xs=`片段`, sep="\n"))*。 diff --git a/examples/web-net-site/README.md b/examples/web-net-site/README.md index 124863c..ff64e4d 100644 --- a/examples/web-net-site/README.md +++ b/examples/web-net-site/README.md @@ -1,19 +1,24 @@ -# examples/web-net-site +# web-net-site -Demonstrates the network-extended `ext/web` + `lib/net` surface (design `doc/design/ext-web-net.md`). +本工程保留文章列表、关于页、文章表单、Cookie/Multipart 工具页、登录后的原生管理后台,以及 /live WebSocket 回显。页面递归组合到 Markdown 和原生控件;浏览器交互由 public/client.mq.md 表达。 -```bash -cargo build -p marqdo_plugin_web -cargo run -- examples/web-net-site/index.mq.md +从仓库根目录准备当前 CLI 与工程插件后,使用同一份开发手册构建 Web 和浏览器运行时: + +```sh +target/debug/marqdo call skills/marqdo-dev/index.mq.md prepare_engineering --effects process.exec --fs-root . --require-ok --json +target/debug/marqdo call skills/marqdo-dev/index.mq.md prepare_web --effects plugin --fs-root . --require-ok --json +target/debug/marqdo call skills/marqdo-dev/index.mq.md build_browser 'out="examples/web-net-site/public/generated"' --effects plugin,process.exec,fs.write --fs-root . --require-ok --json +target/debug/marqdo call examples/web-net-site/index.mq.md serve --effects plugin,fs.write,network.write --fs-root examples/web-net-site --require-ok --json ``` -Then open http://127.0.0.1:18083/: +打开 http://127.0.0.1:18083。默认数据库位于站点文件根的 data/site-net.db,重启保留已有文章。缺少兼容 WASM 目标时,先按 [工具链任务](../../skills/marqdo-dev/toolchain.mq.md) 准备工作区编译器,再把返回的 compiler 传给 build_browser。 -- `/` — articles from SQLite plus a live WebSocket widget (`/live`, served by `public/live.js`) -- `/about` -- `/new` — form POST to `/_form/article` -- `/tools` — parsing demos powered by `lib/net`: `net.cookie_parse` and `net.multipart_parse` -- `/admin` — session-gated admin; sign in with `admin` / `secret` -- `/live` — WebSocket echo endpoint (try it from the home widget, or with `web.ws.connect`) +- [布局入口](components/index.mq.md) 组合导航、侧栏、主体和页脚,叶子在 components/content。 +- [文章表单](forms.mq.md) 统一定义字段与服务端规则;校验失败后保留真实 CSRF,成功回到文章列表。 +- [工具页](pages/tools.mq.md) 展示真实网络解析结果,不请求远端服务。 +- [客户端](public/client.mq.md) 保留按钮与 Enter 发送、去除首尾空白、忽略空输入及连续回显日志。 +- 管理后台登录使用本机演示账号 admin / secret。部署时替换账号与访问策略。 -You may run it from the repo root or from this directory: relative `static_dir` (e.g. `public`) and relative db paths (e.g. `data/site-net.db`) resolve against the **entry script's directory**, not the terminal's current working directory. +请求资源沿用五列 View;数据库查询随每次请求更新,表单引用解析当前会话。详情见 [请求资源设计](../../doc/design/web-view-resources.md)。 + +开发入口的 test_browser 使用实际当前 WASM 验证回显、表单重试、新增文章、后台登录与窄屏布局。HTTP 回归 web_handbook 在 Tree 与 Bytecode 两个后端启动临时站点,验证数据和鉴权,避免操作用户数据库。 diff --git a/examples/web-net-site/components/content/about.md b/examples/web-net-site/components/content/about.md new file mode 100644 index 0000000..1118d65 --- /dev/null +++ b/examples/web-net-site/components/content/about.md @@ -0,0 +1,3 @@ +# About + +This example combines database records, server-side form validation, login sessions, WebSocket echo and the standard network library's cookie/multipart parsing. Each responsibility has its own source file; layouts end in plain Markdown leaves. diff --git a/examples/web-net-site/components/content/foot.md b/examples/web-net-site/components/content/foot.md new file mode 100644 index 0000000..87b488f --- /dev/null +++ b/examples/web-net-site/components/content/foot.md @@ -0,0 +1 @@ +[Marqdo web-net example](https://github.com) · [Docs](/tools) diff --git a/examples/web-net-site/components/content/home.md b/examples/web-net-site/components/content/home.md new file mode 100644 index 0000000..fa5dbe7 --- /dev/null +++ b/examples/web-net-site/components/content/home.md @@ -0,0 +1,3 @@ +# Net Site + +Articles from SQLite, a live WebSocket widget, login-gated administration, and network parsing tools share this readable project. New articles appear on the next request. diff --git a/examples/web-net-site/components/content/multipart.txt b/examples/web-net-site/components/content/multipart.txt new file mode 100644 index 0000000..af081b1 --- /dev/null +++ b/examples/web-net-site/components/content/multipart.txt @@ -0,0 +1,10 @@ +--net-boundary +Content-Disposition: form-data; name="title" + +Hello +--net-boundary +Content-Disposition: form-data; name="cover"; filename="pic.png" +Content-Type: image/png + + +--net-boundary-- diff --git a/examples/web-net-site/components/content/nav.md b/examples/web-net-site/components/content/nav.md new file mode 100644 index 0000000..c89e156 --- /dev/null +++ b/examples/web-net-site/components/content/nav.md @@ -0,0 +1 @@ +[Home](/) · [About](/about) · [Publish](/new) · [Tools](/tools) · [Admin](/admin) diff --git a/examples/web-net-site/components/content/new.md b/examples/web-net-site/components/content/new.md new file mode 100644 index 0000000..3a14311 --- /dev/null +++ b/examples/web-net-site/components/content/new.md @@ -0,0 +1,3 @@ +# Publish + +This form inserts into the shared articles table. Title is required and limited to 120 characters; body is optional and limited to 8000. A rejected field keeps the actual session token so it can be corrected and submitted again. diff --git a/examples/web-net-site/components/content/side.md b/examples/web-net-site/components/content/side.md new file mode 100644 index 0000000..eece4fe --- /dev/null +++ b/examples/web-net-site/components/content/side.md @@ -0,0 +1,7 @@ +## Try the capabilities + +- [Articles](/) +- [WebSocket](/#live) +- [Authentication](/admin) +- [Forms](/new) +- [Network parsing](/tools) diff --git a/examples/web-net-site/components/foot.mq.md b/examples/web-net-site/components/foot.mq.md index 5cf5167..0302a3b 100644 --- a/examples/web-net-site/components/foot.mq.md +++ b/examples/web-net-site/components/foot.mq.md @@ -1,14 +1,20 @@ --- markup: occlusion +title: foot Markdown component +import: + component: ext/web/component/index.mq.md + fs: lib/fs.mq.md --- +This leaf module owns foot content and its semantic region. Parent layout only places the returned nodes. Edit the adjacent Markdown leaf to change wording or links; the component does not query records, authenticate users or generate a raw HTML string. + ## foot -`foot` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | One footer region containing terminal Markdown content | -| 属性 | 值 | 样式 | -|------|-----|------| -| Marqdo web-net example | https://github.com | | -| Docs | /tools | | +Read the Markdown leaf relative to the granted site root with fs.read. Its links keep the original example's destinations; actual routing and access policy remain in the serving entry. This region is already simple enough to express as Markdown, so further wrappers or a custom table dialect would add no responsibility. The semantic container and class preserve its role for the native layout and theme. -*`foot`* \ No newline at end of file +We **text = [Read this region's terminal Markdown](fs.read_text(path="components/content/foot.md"))** and **leaf = [Retain content as native Markdown](component.markdown(text=`text`, slot="foot-content"))**. +Return *[Place that leaf in its semantic region](component.wrap(children=`leaf`, kind="footer", slot="foot", style="foot"))*. diff --git a/examples/web-net-site/components/home.mq.md b/examples/web-net-site/components/home.mq.md new file mode 100644 index 0000000..dba972b --- /dev/null +++ b/examples/web-net-site/components/home.mq.md @@ -0,0 +1,25 @@ +--- +markup: occlusion +title: Network-site home content +import: + component: ext/web/component/index.mq.md + query: ext/data/view.mq.md + socket: live.mq.md + fs: lib/fs.mq.md + table: lib/table.mq.md +--- + +The home body has three responsibilities: a Markdown introduction, the original WebSocket widget, and a current article list. Each remains a separate component or resource. The database query is described at startup and executed per request, so publishing an article appears without restarting the site. + +## nodes + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Introduction, native live widget and request-time article query nodes | + +Read the terminal introduction with fs.read. The live component owns only native controls and the official bridge reference; network binding belongs to serve. The query uses the application's retained articles resource and stable id ordering. It neither caches startup records nor opens a second database using a guessed relative filename. + +We **text = [Read the home introduction](fs.read_text(path="components/content/home.md"))** and **intro = [Describe it as Markdown](component.markdown(text=`text`, slot="intro"))** and **live = [Assemble the native WebSocket widget](socket.nodes())**. +We **current = [Describe the current article query](query.query(source="articles", order="id", link_prefix=""))** and **articles = [Place the dynamic data resource](component.resource(value=`current`, slot="articles"))**. +We **body = [Keep introduction before interaction](table.concat(a=`intro`, b=`live`))**. +Return *[Keep the actual database list after the live widget](table.concat(a=`body`, b=`articles`))*. diff --git a/examples/web-net-site/components/index.mq.md b/examples/web-net-site/components/index.mq.md new file mode 100644 index 0000000..a3a1acf --- /dev/null +++ b/examples/web-net-site/components/index.mq.md @@ -0,0 +1,29 @@ +--- +markup: occlusion +title: Network-site recursive layout entry +import: + component: ext/web/component/index.mq.md + nav: nav.mq.md + side: side.mq.md + foot: foot.mq.md + table: lib/table.mq.md +--- + +Read this entry before changing page geometry. Navigation, side rail and footer end in Markdown leaves; the caller supplies main content nodes. Database queries and form references remain resources inside that main region, preserving fresh request behavior without rebuilding layout or concatenating HTML. + +## frame + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| body | list | required | Main content nodes supplied by the page's own component | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Ordered navigation, side/main row, footer and stylesheet resource | + +Use `body` to assemble one page in the same site frame. Each child module owns its content; this parent only declares order and one side-by-side relationship. The native row layout collapses on narrow screens. No child is rendered into a string before composition. The theme URL points to a file explicitly compiled by serve before discovery starts. + +We **top = [Read the navigation component](nav.nav())** and **rail = [Read the side-rail component](side.side())** and **main = [Name the supplied main region](component.wrap(children=`body`, kind="column", slot="main"))**. +We **columns = [Keep side rail and main as sibling components](table.concat(a=`rail`, b=`main`))** and **center = [Declare the shared row geometry](component.wrap(children=`columns`, kind="row", slot="page-body"))** and **bottom = [Read the closing links](foot.foot())**. +We **page = [Keep navigation before content](table.concat(a=`top`, b=`center`))** and **page = [Keep the footer after content](table.concat(a=`page`, b=`bottom`))** and **style = [Reference the compiled declarative theme](component.asset(url="/static/generated/theme.css", kind="stylesheet"))**. +Return *[Retain the style resource with the readable page structure](table.concat(a=`page`, b=`style`))*. diff --git a/examples/web-net-site/components/live.mq.md b/examples/web-net-site/components/live.mq.md new file mode 100644 index 0000000..d925b00 --- /dev/null +++ b/examples/web-net-site/components/live.mq.md @@ -0,0 +1,53 @@ +--- +markup: occlusion +title: Native WebSocket widget +import: + component: ext/web/component/index.mq.md + client: ext/web/client/index.mq.md + table: lib/table.mq.md +--- + +This component ends at simple Markdown and native controls. It owns no network listener or hand-written HTML. The client program supplies events through the official bridge; serve separately binds the native /live echo resource. Keep control ids stable when editing wording so the client contract stays readable. + +## nodes + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | WebSocket heading, status, input/send controls, message log and bridge resource | + +The heading explains the interaction. Status and output use independent plain-text targets, input supplies the send value, and the button starts disabled until a real connection opens. Values and attributes remain typed data. Each echoed message is appended by the Marqdo client state and shown as text, so message content cannot become HTML. This construction does not open a socket. + +The bridge addresses are explicit resources under the site's static mount. Prepare the current WASM and bridge in public/generated before serving; copying an older bridge can change event behavior even when the page still renders. The source at public/client.mq.md is served as UTF-8 client code and runs in the official browser runtime. To inspect construction alone, call this file's nodes function with no effects: it returns typed structure and performs no network request. + +We **heading = [Describe the widget in ordinary Markdown](component.markdown(text="## Live WebSocket", slot="live-heading"))**. + +`status_attrs` = + +| id | aria-live | +|---|---| +| live-status | polite | + +`input_attrs` = + +| id | placeholder | type | +|---|---|---| +| live-msg | type a message… | text | + +`button_attrs` = + +| id | type | disabled | +|---|---|---| +| live-send | button | True | + +`output_attrs` = + +| id | aria-live | +|---|---| +| live-out | polite | + +We **status = [Keep connection state separate from messages](component.element(kind="text", value="connecting…", attrs=`status_attrs`, slot="live-status"))** and **input = [Describe the native message input](component.element(kind="input", attrs=`input_attrs`, slot="live-input"))** and **button = [Describe the initially disabled send action](component.element(kind="button", value="Send", attrs=`button_attrs`, slot="live-send"))**. +We **controls = [Keep the input beside its send button](table.concat(a=`input`, b=`button`))** and **controls = [Declare responsive control geometry](component.wrap(children=`controls`, kind="row", slot="live-controls"))** and **output = [Describe the plain message log](component.element(kind="pre", attrs=`output_attrs`, slot="live-output"))**. +We **body = [Start with the explanatory heading](table.concat(a=`heading`, b=`status`))** and **body = [Place interaction after status](table.concat(a=`body`, b=`controls`))** and **body = [Keep the echoed messages after controls](table.concat(a=`body`, b=`output`))**. +We **id = [Name the widget's existing fragment destination](table.put(in=None, at="id", value="live"))** and **widget = [Keep the terminal pieces in one semantic region](component.wrap(children=`body`, kind="section", attrs=`id`, slot="live"))**. +We **runtime = [Declare the official runtime and Marqdo client source](client.nodes(source="/static/client.mq.md", wasm="/static/generated/marqdo_wasm.wasm", bridge="/static/generated/marqdo-bridge.js"))**. +Return *[Retain widget and runtime as structured nodes](table.concat(a=`widget`, b=`runtime`))*. diff --git a/examples/web-net-site/components/nav.mq.md b/examples/web-net-site/components/nav.mq.md index fda9f11..37c95ec 100644 --- a/examples/web-net-site/components/nav.mq.md +++ b/examples/web-net-site/components/nav.mq.md @@ -1,19 +1,20 @@ --- markup: occlusion +title: nav Markdown component +import: + component: ext/web/component/index.mq.md + fs: lib/fs.mq.md --- +This leaf module owns nav content and its semantic region. Parent layout only places the returned nodes. Edit the adjacent Markdown leaf to change wording or links; the component does not query records, authenticate users or generate a raw HTML string. + ## nav -Site top navigation. The Admin tab points at the login-gated admin page. +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | One nav region containing terminal Markdown content | -`nav` = +Read the Markdown leaf relative to the granted site root with fs.read. Its links keep the original example's destinations; actual routing and access policy remain in the serving entry. This region is already simple enough to express as Markdown, so further wrappers or a custom table dialect would add no responsibility. The semantic container and class preserve its role for the native layout and theme. -| 属性 | 值 | 样式 | -|------|-----|------| -| Home | / | | -| About | /about | | -| Publish | /new | | -| Tools | /tools | | -| Admin | /admin | | - -*`nav`* +We **text = [Read this region's terminal Markdown](fs.read_text(path="components/content/nav.md"))** and **leaf = [Retain content as native Markdown](component.markdown(text=`text`, slot="nav-content"))**. +Return *[Place that leaf in its semantic region](component.wrap(children=`leaf`, kind="nav", slot="nav", style="topnav"))*. diff --git a/examples/web-net-site/components/side.mq.md b/examples/web-net-site/components/side.mq.md index d294b80..0c15129 100644 --- a/examples/web-net-site/components/side.mq.md +++ b/examples/web-net-site/components/side.mq.md @@ -1,19 +1,20 @@ --- markup: occlusion +title: side Markdown component +import: + component: ext/web/component/index.mq.md + fs: lib/fs.mq.md --- +This leaf module owns side content and its semantic region. Parent layout only places the returned nodes. Edit the adjacent Markdown leaf to change wording or links; the component does not query records, authenticate users or generate a raw HTML string. + ## side -Sidebar index of what this example demonstrates. +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | One aside region containing terminal Markdown content | -`side` = +Read the Markdown leaf relative to the granted site root with fs.read. Its links keep the original example's destinations; actual routing and access policy remain in the serving entry. This region is already simple enough to express as Markdown, so further wrappers or a custom table dialect would add no responsibility. The semantic container and class preserve its role for the native layout and theme. -| 属性 | 值 | 样式 | -|------|-----|------| -| Articles | / | | -| WebSocket | /#live | | -| Auth | /admin | | -| Forms | /new | | -| net lib | /tools | | - -*`side`* \ No newline at end of file +We **text = [Read this region's terminal Markdown](fs.read_text(path="components/content/side.md"))** and **leaf = [Retain content as native Markdown](component.markdown(text=`text`, slot="side-content"))**. +Return *[Place that leaf in its semantic region](component.wrap(children=`leaf`, kind="aside", slot="side", style="side"))*. diff --git a/examples/web-net-site/db/articles.mq.md b/examples/web-net-site/db/articles.mq.md index 5484078..7ba5bb6 100644 --- a/examples/web-net-site/db/articles.mq.md +++ b/examples/web-net-site/db/articles.mq.md @@ -1,27 +1,32 @@ --- markup: occlusion +title: Article schema and seed handbook +import: + document: lib/document.mq.md --- +This file explains callable use; [articles.tables.md](articles.tables.md) holds the readable literal tables. Set --fs-root to the site directory and grant fs.read. Reading returns data without running prose, opening a database or changing a page. + ## schema -`fields` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Native table value, preserving literal types and column geometry | -| 字段 | 类型 | 可空 | -|------|------|------| -| id | integer | false | -| title | text | false | -| body | text | true | +Declare article fields, native types and nullability. The initializer consumes this table to ensure structure; it must not guess a migration or erase existing rows. -*`fields`* +Call independently with fs.read on the site root. The section must match exactly and uniquely. Malformed tables or dynamic expressions retain native document diagnostics. A returned style declaration still needs compilation; returned database data still needs an explicit initializer. This value is neither HTML nor an applied browser effect. + +Return *[读取 schema 的实际字面表](document.read_table(path="db/articles.tables.md", title="schema"))*. ## seed -`rows` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Native table value, preserving literal types and column geometry | -| id | title | body | -|----|-------|------| -| 1 | Welcome to the web-net site | Home page lists rows from SQLite. | -| 2 | Login-gated admin | The /admin page requires a session cookie. | -| 3 | WebSocket live | The /live endpoint echoes your message in real time. | +Provide initial demonstration articles with their original ids, stable slugs and content. Insert only after the database initializer confirms an empty table; this reader never changes existing articles. -*`rows`* \ No newline at end of file +Call independently with fs.read on the site root. The section must match exactly and uniquely. Malformed tables or dynamic expressions retain native document diagnostics. A returned style declaration still needs compilation; returned database data still needs an explicit initializer. This value is neither HTML nor an applied browser effect. + +Return *[读取 seed 的实际字面表](document.read_table(path="db/articles.tables.md", title="seed"))*. diff --git a/examples/web-net-site/db/articles.tables.md b/examples/web-net-site/db/articles.tables.md new file mode 100644 index 0000000..f45bf3b --- /dev/null +++ b/examples/web-net-site/db/articles.tables.md @@ -0,0 +1,23 @@ +# Article data + +Literal article schema and demonstration content. Reading these tables does not open a database or insert rows. Follow articles.mq.md for callable use; the database initializer decides whether seeding is appropriate. + +## schema + +Field definitions for the native database initializer; nullable values remain booleans. + +| 字段 | 类型 | 可空 | +|------|------|------| +| id | integer | false | +| title | text | false | +| body | text | true | + +## seed + +Initial demonstration records in their original column-oriented shape; ids and stable slugs retain their meaning. + +| id | title | body | +|----|-------|------| +| 1 | Welcome to the web-net site | Home page lists rows from SQLite. | +| 2 | Login-gated admin | The /admin page requires a session cookie. | +| 3 | WebSocket live | The /live endpoint echoes your message in real time. | diff --git a/examples/web-net-site/db/index.mq.md b/examples/web-net-site/db/index.mq.md index 74eb540..20e3294 100644 --- a/examples/web-net-site/db/index.mq.md +++ b/examples/web-net-site/db/index.mq.md @@ -1,21 +1,37 @@ --- markup: occlusion -title: db/index -description: Open sqlite, init articles, seed once. +title: web-net-site database lifecycle import: - web: ext/web/web.mq.md + data: ext/data/db.mq.md articles: articles.mq.md + fs: lib/fs.mq.md + text: lib/text.mq.md --- +The database entry connects schema and literal seed leaves to the actual data resource. It no longer uses the removed web database constructor. Grant fs.write and plugin with the site directory as --fs-root; the SQLite path is resolved through that native root rather than the process working directory. + ## open -**store = > web.db url="sqlite:data/site-net.db"** -**fields = > articles.schema** -> `store`.init name=articles fields=`fields` -**rows = > store.select table="articles" limit=1** -1. `rows` - *store* -2. * - **seed = > articles.seed** - > `store`.insert table=articles rows=`seed` - *store* \ No newline at end of file +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | any | None | None selects data/site-net.db under the site root; tests provide a disposable explicit URI | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Initialized articles database resource with existing rows preserved | + +Use `url`=None to open the site's local database. Create the default data directory through native file operations, then resolve the actual SQLite filename within the granted root. An explicit SQLite path goes through the same root and symlink checks before the native database resource receives it. Other supported database URIs retain their resource-specific backend contract; they are not sandboxed by filesystem permissions. + +The schema reader preserves native field types and nullability. Initialization ensures the table exists, queries one row to distinguish an empty table, and inserts the original demonstration content only into an empty table. An existing or partly populated table is kept unchanged. This is not a column migrator, data repair tool or reason to delete a user's articles. A native connection, schema or insert diagnostic stops the caller before it starts serving. + +For isolated verification choose a caller-owned temporary SQLite file and copy the article data leaf under that granted site root. Keep the returned resource in the same program for subsequent queries. Close the process before cleaning its owned directory; do not run tests against the example's existing data directory. + +1. `url` == None + We **[Create only the site's default data directory](fs.make_dirs(path="data"))** and **file = [Resolve its database filename](fs.resolve(path="data/site-net.db"))** and **url = "sqlite:" + file**. +1. [The explicit or default URI selects SQLite](text.starts_with(text=`url`, prefix="sqlite:")) + We **file = [Read the selected SQLite path](text.replace(text=`url`, old="sqlite:", new="", count=1))** and **file = [Apply the native file-root policy](fs.resolve(path=`file`))** and **url = "sqlite:" + file**. +We **store = [Open the selected actual database resource](data.db(url=`url`))** and **fields = [Read the documented article schema](articles.schema())**. +We **[Ensure the table without clearing it](> `store`.init name="articles" fields=`fields`)** and **existing = [Check whether business records already exist](> `store`.select table="articles" limit=1)**. +1. not `existing` + We **seed = [Read the original demonstration data](articles.seed())** and **[Seed only the empty article table](> `store`.insert table="articles" rows=`seed`)**. +Once the selected database is ready, return *store* for the site's resource bindings. diff --git a/examples/web-net-site/forms.mq.md b/examples/web-net-site/forms.mq.md new file mode 100644 index 0000000..13ac172 --- /dev/null +++ b/examples/web-net-site/forms.mq.md @@ -0,0 +1,36 @@ +--- +markup: occlusion +title: Article form resource +import: + form: ext/data/form.mq.md +--- + +The same form resource supplies the page controls and validates the system submission route. The serving entry mounts it as article. The page only places a reference, so fields, limits and errors cannot drift between two separate form implementations. + +## article + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Native insert form with title/body fields and original validation rules | + +Call with plugin before listening. Title is required and limited to 120 characters; body remains optional with an 8000-character limit. These are the original site's server-side rules. Rendering neither inserts a row nor authenticates a user; submission uses the application's actual articles database and current CSRF context. + +The field and rule tables stay immediately visible beside their explanation. No raw form HTML or client validation program is authored. After a valid submission the resource returns to the article list; rejected values retain field errors for correction. This public demonstration form is distinct from the login-gated native administration surface. + +`fields` = + +| name | label | type | required | +|---|---|---|---| +| title | Title | text | True | +| body | Body | textarea | False | + +`rules` = + +| field | rule | message | +|---|---|---| +| title | required | Title is required | +| title | max:120 | Title is too long | +| body | max:8000 | Body is too long | + +We **selected = [Create the actual article insert resource](form.form(table="articles", action="insert"))** and **selected = [Attach the readable field definitions](> `selected`.fields fields=`fields`)** and **selected = [Attach the server validation rules](> `selected`.rules rules=`rules`)**. +Return *[Keep submission and cancellation copy with this resource](> `selected`.labels submit="Publish" cancel="Cancel" cancel_href="/")*. diff --git a/examples/web-net-site/index.mq.md b/examples/web-net-site/index.mq.md index df40a1d..551af4b 100644 --- a/examples/web-net-site/index.mq.md +++ b/examples/web-net-site/index.mq.md @@ -1,131 +1,72 @@ --- markup: occlusion -title: web-net-site -description: Home + /about + /new (form) + /tools (net lib) + /admin (auth) + /live (WebSocket). +type: web +view: main +route: / +title: Marqdo Net Site import: + layout: components/index.mq.md + home: components/home.mq.md + database: db/index.mq.md + forms: forms.mq.md + styles: styles/shell.mq.md web: ext/web/web.mq.md - net: lib/net.mq.md - text: lib/text.mq.md - shell: styles/shell.mq.md - nav: components/nav.mq.md - side: components/side.mq.md - foot: components/foot.mq.md - articles: db/articles.mq.md - db: db/index.mq.md + form: ext/data/form.mq.md + admin: ext/data/admin.mq.md + auth: ext/security/auth.mq.md + socket: ext/net/websocket.mq.md + fs: lib/fs.mq.md + result: lib/result.mq.md --- -# main +Read this entry, then the layout index, content leaves, database entry, form resource and browser client. Home, About, Publish and Tools are declared Documents. Native administration remains enabled and login-gated. The /live socket is a separate network resource. No page uses the removed compose APIs or a raw HTML shell. -`home` = +## main -| 组件 | 样式 | -|------|------| -| nav.`nav` | shell.`topnav` | -| side.`side` | shell.`side_panel` | -| foot.`foot` | | +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Shared recursive frame around introduction, echo controls and current articles | -`index` = +This startup function describes structure, reading only the terminal Markdown leaves. The database query remains a typed resource resolved per request, while the client uses native controls and the official bridge. Rendering the page cannot initialize or clear business records. Follow each component import to edit one responsibility instead of reproducing the complete page. -| 属性 | 值 | 样式 | -|------|-----|------| -| title | articles.`articles`.title | shell.`card_title` | -| body | articles.`articles`.body | shell.`card_body` | +We **body = [Assemble the three independent home responsibilities](home.nodes())**. +Return *[Place them in the shared recursive site frame](layout.frame(body=`body`))*. -Home intro also embeds the live WebSocket widget (HTML is served raw). +## serve -**store = > db.open** -**page = > web.page title="Marqdo Net Site" intro="

      Net Site

      Articles from SQLite, a live WebSocket widget, login-gated admin, and net-library parsing tools.

      Live WebSocket

      connecting…

      "** -**page = > page.compose_components components=home** -**page = > page.compose_main main=index** +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| root | text | "examples/web-net-site" | Explicit discovery directory relative to the checkout | +| port | number | 18083 | Local demonstration listen port | +| url | any | None | None chooses the site-root SQLite file; tests use an owned temporary URI | -About page: same shell. +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Blocking listener with retained article data, forms, authentication and echo | -**about = > web.page title="About" intro="

      About

      Demonstrates the network-extended web library: sessions, auth, WebSocket, multipart/cookie parsing.

      "** -**about = > about.compose_components components=home** +Use `root`="examples/web-net-site", `port`=18083 and `url`=None from the checkout, with --fs-root examples/web-net-site and plugin,fs.write,network.write. Build current browser assets into public/generated through the development handbook first. Missing runtime assets stop before listening rather than leaving the widget apparently ready. - +Initialization preserves existing articles and seeds only an empty table. Theme compilation uses the original property declarations and writes only the explicit generated stylesheet. Discovery assembles the readable Documents, then the workflow enables native administration, attaches local fixture credentials, mounts the public article form and binds anonymous loopback echo. Real deployment must replace fixture credentials and its network policy. Keep each returned app before listening. -Parse a `Cookie` request header with the standard library. +`assets` = -**parsed_req = > net.cookie_parse text="session=abc123; theme=dark"** -**req_cookie = [1](access(parsed_req, "1"))** +| file | +|---| +| public/generated/marqdo_wasm.wasm | +| public/generated/marqdo-bridge.js | -Parse a `Set-Cookie` response header. +- [Require the actual runtime resources before serving](for assets as file) + 1. not [The selected runtime asset exists](fs.exists(path=`file`)) + Return *[Explain the required browser preparation](result.error(code="net_site.browser_assets", message="build current browser assets into public/generated before serve", operation="serve"))*. +We **store = [Initialize the retained article database](database.open(url=`url`))** and **css = [Compile the actual declarative theme](styles.css())** and **[Create only the generated resource directory](fs.make_dirs(path="public/generated"))** and **[Write that explicit stylesheet through native IO](fs.atomic_write(path="public/generated/theme.css", text=`css`))**. +We **app = [Discover all declared Documents and the static root](web.prepare(root=`root`, host="127.0.0.1", port=`port`, db=`store`, static_dir="public"))** and **app = [Retain the existing native administration capability](admin.enable(app=`app`))**. -**parsed_resp = > net.cookie_parse text="id=42; Path=/; HttpOnly; SameSite=Lax" is_response=True** -**resp_cookie = [1](access(parsed_resp, "1"))** +`users` = -Parse a `multipart/form-data` body. +| @ | username | password | role | +|---|---|---|---| +| 1 | admin | secret | admin | -`_b` = net-boundary - -`_body` = "--`_b`\nContent-Disposition: form-data; name=\"title\"\n\nHello\n--`_b`\nContent-Disposition: form-data; name=\"cover\"; filename=\"pic.png\"\nContent-Type: image/png\n\n\n--`_b`--\n" - -**mp = > net.multipart_parse body=`_body` boundary=`_b`** -**mp_title = [1](access(mp, "1"))** -**mp_cover = [2](access(mp, "2"))** - -Build the tools page as one HTML intro (intro is served raw). - -`tools_parts` = - -| 段 | -|----| -|

      Net tools

      Parsing demos powered by lib/net: cookie_parse and multipart_parse.

      | -|

      Cookie request

      | -| [name](`req_cookie`)=[value](`req_cookie`) | -|

      Set-Cookie response

      | -| [name](`resp_cookie`)=[value](`resp_cookie`) · HttpOnly=[http_only](`resp_cookie`) | -|

      Multipart field

      | -| [name](`mp_title`)=[value](`mp_title`) | -|

      Multipart file

      | -| [name](`mp_cover`) · [filename](`mp_cover`) · [content_type](`mp_cover`) | -|

      | - -**tools_intro = > text.str_join xs=`tools_parts` sep=""** -**tools = > web.page title="Tools" intro=`tools_intro`** -**tools = > tools.compose_components components=home** - -Article create form: field table + rules table. - -`article_fields` = - -| 字段 | 标签 | 类型 | 必填 | 默认 | -|------|------|------|------|------| -| title | Title | text | true | | -| body | Body | textarea | false | | - -`article_rules` = - -| 字段 | 规则 | 消息 | -|------|------|------| -| title | required | Title is required | -| title | max:120 | Title is too long | -| body | max:8000 | Body is too long | - -**article_form = > web.form table="articles" action="insert"** -**article_form = > article_form.fields fields=article_fields** -**article_form = > article_form.rules rules=article_rules** - -New article page: form embedded in the main slot. - -**new = > web.page title="Publish" intro="

      Publish

      Form inserts into articles.

      "** -**new = > new.compose_components components=home** -**new = > new.compose_form id="article" form=article_form** - -Admin users table (english + chinese column headers both work). - -`admins` = - -| 行 | username | password | -|----|----------|----------| -| 1 | admin | secret | - -**app = > web.app page=page db=store admin=True host="127.0.0.1" port=18083** -**app = > app.route path="/about" page=about** -**app = > app.route path="/new" page=new** -**app = > app.route path="/tools" page=tools** -**app = > app.static dir="public" mount="/static"** -**app = > app.route_ws path="/live" echo=True** -**app = > app.auth users=`admins` session_ttl=3600** -> `app`.listen \ No newline at end of file +We **app = [Attach actual login sessions and the native admin gate](auth.attach(app=`app`, users=`users`, login_path="/admin/login", login_redirect="/admin", logout_redirect="/"))** and **article = [Build the shared validation resource](forms.article())** and **app = [Mount the public creation form explicitly](form.mount(app=`app`, id="article", form=`article`))**. +We **app = [Bind the original local WebSocket echo route](socket.route(app=`app`, path="/live", mode="echo", require_auth=False))**. +Return *[Listen only after data, resources and policy are ready](web.listen(app=`app`))*. diff --git a/examples/web-net-site/pages/about.mq.md b/examples/web-net-site/pages/about.mq.md new file mode 100644 index 0000000..4452010 --- /dev/null +++ b/examples/web-net-site/pages/about.mq.md @@ -0,0 +1,24 @@ +--- +markup: occlusion +type: web +view: main +route: /about +title: About +import: + component: ext/web/component/index.mq.md + layout: ../components/index.mq.md + fs: lib/fs.mq.md +--- + +This Document declares its actual /about route. Its terminal explanation stays in Markdown and its parent frame owns navigation, side rail and footer. No data query or server setup occurs while reading this explanatory page. + +## main + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Shared site frame containing this page's explanation | + +The server assembles these nodes once, then resolves request resources only while serving. Reading requires fs.read. Follow the shared layout imports to change one region without reproducing an HTML shell here. The route remains discoverable from metadata rather than an implicit mutation chain. + +We **text = [Read the page's terminal explanation](fs.read_text(path="components/content/about.md"))** and **body = [Describe ordinary Markdown content](component.markdown(text=`text`, slot="intro"))**. +Return *[Place this page within the shared recursive frame](layout.frame(body=`body`))*. diff --git a/examples/web-net-site/pages/new.mq.md b/examples/web-net-site/pages/new.mq.md new file mode 100644 index 0000000..48f868f --- /dev/null +++ b/examples/web-net-site/pages/new.mq.md @@ -0,0 +1,27 @@ +--- +markup: occlusion +type: web +view: main +route: /new +title: Publish +import: + component: ext/web/component/index.mq.md + layout: ../components/index.mq.md + fs: lib/fs.mq.md + form: ext/data/form.mq.md + table: lib/table.mq.md +--- + +This Document declares its actual /new route. Its terminal explanation stays in Markdown and its parent frame owns navigation, side rail and footer. The form is referenced by its explicit mounted id; the resource and real submission policy are defined outside this page. + +## main + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Shared site frame containing this page's explanation and mounted form reference | + +The server assembles these nodes once, then resolves request resources only while serving. Reading requires fs.read. The current session's CSRF token and return path are supplied by the form renderer, so the page cannot embed a stale startup token. Missing form registration is a real request error. The route remains discoverable from metadata rather than an implicit mutation chain. + +We **text = [Read the page's terminal explanation](fs.read_text(path="components/content/new.md"))** and **body = [Describe ordinary Markdown content](component.markdown(text=`text`, slot="intro"))**. +We **selected = [Reference the actual mounted article form](form.reference(id="article"))** and **controls = [Place that request resource](component.resource(value=`selected`, slot="article-form"))** and **body = [Keep instructions before the form](table.concat(a=`body`, b=`controls`))**. +Return *[Place this page within the shared recursive frame](layout.frame(body=`body`))*. diff --git a/examples/web-net-site/pages/tools.mq.md b/examples/web-net-site/pages/tools.mq.md new file mode 100644 index 0000000..03bfd7d --- /dev/null +++ b/examples/web-net-site/pages/tools.mq.md @@ -0,0 +1,73 @@ +--- +markup: occlusion +type: web +view: main +route: /tools +title: Network parsing tools +import: + net: lib/net.mq.md + fs: lib/fs.mq.md + table: lib/table.mq.md + component: ext/web/component/index.mq.md + layout: ../components/index.mq.md +--- + +This Document executes the standard network parsers against explicit local fixtures. It makes no external HTTP request. Cookie headers remain text, and the multipart fixture is terminal protocol data in components/content/multipart.txt. The page shows actual returned records as plain preformatted text instead of concatenating raw HTML. + +## _panel + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| title | text | required | Author-controlled heading describing one observed parser value | +| value | any | required | Actual native parser result to display literally | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Markdown heading followed by an escaped native preformatted value | + +Use `title` and `value` to keep each observed value beside its purpose. A parser record is data, not an HTML fragment; convert it to its native display text and let the pre element preserve characters. The author supplies headings, while protocol content never becomes a heading or executable expression. This pure helper performs no IO or parsing itself. + +We **heading = "## " + title** and **label = [Describe the observation in Markdown](component.markdown(text=`heading`))** and **text = [Retain the actual structured parser value](str(value))** and **data = [Show that value literally](component.element(kind="pre", value=`text`))**. +Return *[Keep meaning and actual evidence together](table.concat(a=`label`, b=`data`))*. + +## _cookies + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Actual Cookie request and Set-Cookie response observations | + +The first parser call reads a request Cookie header containing session and theme pairs. The second deliberately enables response-header mode, where Path, HttpOnly and SameSite describe the id cookie rather than becoming independent request cookies. Both results come from the maintained standard library. These are deterministic text fixtures, not real credentials or a browser session lookup. + +Keeping both modes visible preserves the original network-tools capability and explains why their output shapes differ. No cookie is written, accepted for authentication or sent to a remote service. The output panes expose all native fields, so a reader can inspect names, values and flags without decoding a generated HTML string. + +We **request = [Parse the explicit request-cookie fixture](net.cookie_parse(text="session=abc123; theme=dark"))** and **response = [Parse one actual response-cookie fixture](net.cookie_parse(text="id=42; Path=/; HttpOnly; SameSite=Lax", is_response=True))**. +We **request_panel = [Show actual request pairs](_panel(title="Cookie request", value=`request`))** and **response_panel = [Show actual response attributes](_panel(title="Set-Cookie response", value=`response`))**. +Return *[Keep the two parser modes adjacent](table.concat(a=`request_panel`, b=`response_panel`))*. + +## _multipart + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Actual multipart field and file-part observations | + +Read the protocol fixture with fs.read from the site root, then parse it using net-boundary, the delimiter declared by that fixture. The title part contains Hello. The cover part names pic.png with image/png content type; its value is the literal demonstration text , not an uploaded binary image. This distinction keeps the example's claims aligned with the bytes actually parsed. + +The result is a native part list, so the field and file panes select its first and second records through collection helpers. A missing or malformed fixture remains a parser or filesystem diagnostic rather than a hand-authored expected result. No upload, file extraction or network access occurs, and the fixture is not interpreted as Markdown code. + +We **body = [Read the exact local multipart protocol bytes as text](fs.read_text(path="components/content/multipart.txt"))** and **parts = [Parse the real boundary and disposition fields](net.multipart_parse(body=`body`, boundary="net-boundary"))**. +We **field = [Select the first parsed part](table.first(list=`parts`))** and **file = [Select the second parsed part](table.at(xs=`parts`, i=1))** and **field_panel = [Show the actual form field](_panel(title="Multipart field", value=`field`))** and **file_panel = [Show actual file metadata](_panel(title="Multipart file", value=`file`))**. +Return *[Keep both actual parser observations](table.concat(a=`field_panel`, b=`file_panel`))*. + +## main + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Shared site frame around all four native parser observations | + +This startup assembly requires fs.read only for the terminal multipart fixture and the shared Markdown layout leaves. The standard parser calls themselves are pure. The four panes preserve request cookies, response cookies, a multipart field and multipart file metadata. None represents a request to an external site or a user upload. + +Changing a fixture should change the displayed result because the page runs the real parser, not a copied expected answer. Keep the explanatory heading and the observed values together, and retain the shared navigation to Publish, administration and the live widget. + +We **intro = [Explain the deterministic tools page](component.markdown(text="# Net tools\n\nParsing demonstrations powered by the actual standard network library."))** and **cookies = [Observe both cookie modes](_cookies())** and **parts = [Observe both multipart part types](_multipart())**. +We **body = [Keep the explanation before observations](table.concat(a=`intro`, b=`cookies`))** and **body = [Retain multipart observations after cookies](table.concat(a=`body`, b=`parts`))**. +Return *[Place all observations in the shared site frame](layout.frame(body=`body`))*. diff --git a/examples/web-net-site/public/client.mq.md b/examples/web-net-site/public/client.mq.md new file mode 100644 index 0000000..eee3e21 --- /dev/null +++ b/examples/web-net-site/public/client.mq.md @@ -0,0 +1,164 @@ +--- +markup: occlusion +title: Network-site echo client +import: + browser: lib/browser.mq.md + table: lib/table.mq.md + text: lib/text.mq.md +--- + +The client owns connection state and a plain text message log. Native controls are declared by components/live.mq.md. The relative socket path follows the page's actual host and port, while the server resource owns echo behavior. + +# main + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Native event wiring, socket opening and initial status effects | + +The button click carries the current input value to send. A connection opening enables the button; closure or error disables it. Incoming text appends to retained entry state and never becomes HTML. This is a live echo demonstration, not durable storage or an automatic reconnection loop. BrowserSession keeps entry bindings for callbacks, so they are state rather than fictitious public parameters. + +We **ws_id = "live"** and **messages = ""** before describing the transport. + +`wire` = + +| @ | 选择器 | 事件 | 调用 | 值选择器 | +|---|---|---|---|---| +| 1 | "#live-send" | click | send | "#live-msg" | +| 2 | "#live-msg" | keydown | on_key | "#live-msg" | + +`open` = + +| op | id | url | then_open | then_message | then_error | then_close | +|---|---|---|---|---|---|---| +| open | `ws_id` | /live | on_open | on_message | on_error | on_close | + +We **bindings = [Bind the existing send control](table.put(in=None, at="wire", value=`wire`))** and **socket = [Describe the same-origin WebSocket connection](browser.ws(spec=`open`))**. +Return *[Keep transport and native control wiring together](browser.merge(a=`bindings`, b=`socket`))*. + +## _status + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Plain connection status to display | +| disabled | bool | required | Actual native disabled state for the send button | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Combined status-text and button-attribute effects | + +Use `text` and `disabled` to keep connection feedback consistent with the send control. The attribute must remain a boolean: the bridge removes disabled when False, while the string "false" would still be a present HTML boolean attribute. These effects describe a DOM update and do not send or retry a message. + +We **attributes = [Keep the actual boolean attribute value](table.put(in=None, at="disabled", value=`disabled`))** and **status = [Describe plain connection feedback](browser.set_text(sel="#live-status", text=`text`))** and **button = [Describe actual send availability](browser.set_attr(sel="#live-send", attrs=`attributes`))**. +Return *[Keep the independent effect kinds together](browser.merge(a=`status`, b=`button`))*. + +## on_open + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| ok | bool | True | Actual browser transport opening result | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Connected feedback and enabled send, or failed feedback and disabled send | + +Use `ok`=True from the opening callback. A successful opening proves only the transport is ready; an echoed message is observed separately. Failed opening keeps send disabled and visible as failure. The client does not publish a fake initial echo or silently retry. + +1. `ok` + Return *[Enable sending only after transport opens](_status(text="connected", disabled=False))*. +Return *[Keep failed opening visible](_status(text="connection failed", disabled=True))*. + +## _send + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | text | required | Input text supplied by a click or Enter callback | +| channel | text | required | Existing socket id retained by the client entry | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | One actual send instruction, or None for empty trimmed input | + +Use `value` and `channel` to share the original widget's send policy. Trim surrounding whitespace and ignore an empty result. A nonempty message remains plain text, never a command or HTML. The official bridge reports transport errors separately. This helper receives its channel explicitly rather than assuming an ordinary nested call automatically captures entry state. + +We **payload = [Keep the original trim-before-send behavior](text.str_trim(s=`value`))**. +1. `payload` == "" + Return *None* because an empty or whitespace-only input performs no send. + +`operation` = + +| op | id | data | +|---|---|---| +| send | `channel` | `payload` | + +Return *[Send one nonempty message through the existing connection](browser.ws(spec=`operation`))*. + +## send + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | text | "" | Current text supplied by the send-button wiring | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Send effect for nonempty trimmed input, otherwise None | + +Use `value`="" from a button click. The direct browser callback can read retained entry state and passes that socket id explicitly to the pure send helper. The log updates only after an actual echo arrives, so clicking cannot fabricate successful delivery. Whitespace-only input retains the original widget's no-send behavior. + +Return *[Apply the shared send policy to this click](_send(value=`value`, channel=`ws_id`))*. + +## on_key + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| key | text | "" | Actual key name supplied by the official bridge | +| value | text | "" | Current message input supplied by this control's value selector | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Enter uses the same send policy as the button; other keys return None | + +Use `key`="" and `value`="" from the keyboard wiring. Preserve the original Enter shortcut without sending on every keydown. Enter and click share trimming and empty-input behavior, and neither appends a local echo before a real frame arrives. This callback does not install another DOM handler or start a second socket. + +1. `key` == "Enter" + Return *[Apply exactly the button's send policy](_send(value=`value`, channel=`ws_id`))*. +Return *None* for an ordinary editing key. + +## on_message + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| data | text | "" | Actual echoed text frame from the server | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Plain text update containing the retained echo log | + +Use `data`="" from the message callback. Append each real frame and a newline to entry state, preserving earlier messages as the old widget did. set_text escapes content through the bridge; a message containing markup is shown literally. Reloading starts a fresh demonstration log and no durable history is claimed. + +We **messages = [Retain the next observed echo](messages + "echo: " + data + "\n")**. +Return *[Display the complete observed log as text](browser.set_text(sel="#live-out", text=`messages`))*. + +## on_error + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| error | text | "" | Browser transport error description | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Error feedback and disabled sending | + +Use `error`="" to retain the actual transport failure beside the controls. No previous message is erased and no new send is attempted. The page can be reloaded for a fresh connection; this demonstration has no hidden reconnect policy. + +We **message = "error: " + error**. +Return *[Keep failure and send availability consistent](_status(text=`message`, disabled=True))*. + +## on_close + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Closed feedback with disabled send control | + +A close notification keeps the message log readable while marking the socket unavailable. It neither clears entry state nor silently creates another connection. Subsequent sends require a newly opened page session rather than a fabricated successful transport. + +Return *[Keep closure visible](_status(text="closed", disabled=True))*. diff --git a/examples/web-net-site/public/live.js b/examples/web-net-site/public/live.js deleted file mode 100644 index 74dd8c9..0000000 --- a/examples/web-net-site/public/live.js +++ /dev/null @@ -1,40 +0,0 @@ -// Live widget for the /live WebSocket endpoint. -// Connects to ws://host/live, sends the input, shows the echo. -(function () { - var out = document.getElementById("live-out"); - var input = document.getElementById("live-msg"); - var btn = document.getElementById("live-send"); - var status = document.getElementById("live-status"); - if (!out || !input || !btn || !status) return; - - var proto = location.protocol === "https:" ? "wss" : "ws"; - var ws = new WebSocket(proto + "://" + location.host + "/live"); - status.textContent = "connecting…"; - - ws.onopen = function () { - status.textContent = "connected"; - btn.disabled = false; - }; - ws.onmessage = function (ev) { - var p = document.createElement("p"); - p.textContent = "echo: " + ev.data; - out.appendChild(p); - out.scrollTop = out.scrollHeight; - }; - ws.onclose = function () { - status.textContent = "closed"; - btn.disabled = true; - }; - ws.onerror = function () { - status.textContent = "error"; - btn.disabled = true; - }; - - btn.onclick = function () { - var m = input.value.trim(); - if (m) ws.send(m); - }; - input.addEventListener("keydown", function (e) { - if (e.key === "Enter") btn.onclick(); - }); -})(); diff --git a/examples/web-net-site/styles/shell.mq.md b/examples/web-net-site/styles/shell.mq.md index 5a665b8..e8c020b 100644 --- a/examples/web-net-site/styles/shell.mq.md +++ b/examples/web-net-site/styles/shell.mq.md @@ -1,9 +1,16 @@ --- markup: occlusion +import: + web: ext/web/web.mq.md + text: lib/text.mq.md --- ## topnav +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | The value explicitly returned below; conditional returns follow the selected branch | + `topnav` = | 属性 | 值 | @@ -11,20 +18,28 @@ markup: occlusion | background | #ffffff | | border-bottom | 1px solid #e7e5e4 | -*`topnav`* +After these steps, return *topnav*. ## side_panel +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | The value explicitly returned below; conditional returns follow the selected branch | + `side_panel` = | 属性 | 值 | |------|-----| | background | #f5f5f4 | -*`side_panel`* +After these steps, return *side_panel*. ## card_title +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | The value explicitly returned below; conditional returns follow the selected branch | + `card_title` = | 属性 | 值 | @@ -32,10 +47,14 @@ markup: occlusion | font-size | 1.15rem | | margin | 0 0 0.35rem | -*`card_title`* +After these steps, return *card_title*. ## card_body +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | The value explicitly returned below; conditional returns follow the selected branch | + `card_body` = | 属性 | 值 | @@ -43,4 +62,28 @@ markup: occlusion | color | #57534e | | margin | 0 | -*`card_body`* +After these steps, return *card_body*. + +## css + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | CSS compiled from the original four declarative property tables | + +Call with plugin before discovery. This task preserves the original top navigation background/border, side-panel background, card title size/spacing and card body color/spacing. The selector names target the native components and query-card markup directly. The property functions remain independently callable, so changing one region does not require editing a raw CSS string. + +The server writes the returned text through native filesystem IO into its explicit generated resource path. Compilation itself neither writes that file nor mounts static content. These four sections keep their original order; the general View runtime still owns responsive row geometry. A compiler diagnostic stops serving instead of substituting an old stylesheet. + +We **nav = [Read the original navigation declarations](topnav())** and **side = [Read the original side-panel declarations](side_panel())** and **title = [Read the original title declarations](card_title())** and **body = [Read the original summary declarations](card_body())**. +We **nav_css = [Compile the navigation selector](web.make_style(name="topnav", table=`nav`))** and **side_css = [Compile the side selector](web.make_style(name="side", table=`side`))** and **title_css = [Compile the native card title selector](web.make_style(name="content.cards h2", table=`title`))** and **body_css = [Compile the native card body selector](web.make_style(name="content.cards p", table=`body`))**. + +`parts` = + +| css | +|---| +| `nav_css` | +| `side_css` | +| `title_css` | +| `body_css` | + +Return *[Keep the compiled sections in order](text.str_join(xs=`parts`, sep="\n"))*. diff --git a/examples/web-site-zh/README.md b/examples/web-site-zh/README.md index 06b2b3a..480728c 100644 --- a/examples/web-site-zh/README.md +++ b/examples/web-site-zh/README.md @@ -1,9 +1,32 @@ -# examples/web-site-zh +# web-site-zh -与 [`examples/web-site`](../web-site/) 对等(`ext/web/网页.mq.md`)。 +中文作者通过网页、表单与鉴权资源组织站点。首页、关于、写文章、后台与短链详情各自声明路由;父组件组合结构,内容叶子只写 Markdown。主题保留原来的墨色、酒红、金色、字体、粒子、断点和表单状态,不写作者业务 JavaScript 或手写 CSS。 -```bash -marqdo run examples/web-site-zh/index.mq.md +从仓库根使用当前源码 CLI,先准备工程与 Web 插件,再调用真实启动流程: + +```sh +target/debug/marqdo call skills/marqdo-dev/index.mq.md prepare_engineering --effects process.exec --fs-root . --require-ok --json +target/debug/marqdo call skills/marqdo-dev/index.mq.md prepare_web --effects plugin --fs-root . --require-ok --json +target/debug/marqdo call examples/web-site-zh/index.mq.md serve --effects plugin,fs.write,network.write --fs-root examples/web-site-zh --require-ok --json ``` -http://127.0.0.1:18082/ — 演示脚本见英文样站 [DEMO.md](../web-site/DEMO.md)。 +打开 http://127.0.0.1:18082/ ;默认数据库位于站点文件根的 data/site-zh.db,重启保留现有文章。admin/demo 仅为本机演示账户。服务阻塞当前进程,停止由调用者负责。 + +按职责阅读: + +- [工程入口](index.mq.md) — 声明首页,组合数据、表单、会话、门禁与监听。 +- [布局入口](components/index.mq.md) — 公共侧栏与独立后台结构,终端叶子在 components/content。 +- [文章请求资源](components/articles.mq.md) — 当前摘要卡片与真实短链完整正文。 +- [共享表单](forms.mq.md) — 实际字段和规则在 forms.tables.md,校验失败保留 CSRF。 +- [主题入口](styles/index.mq.md) — 保留原始数据,只映射结构地址并适配包装几何。 +- [原生核对工具](verify.mq.md) — 实际比较 412 条原始布局/动画声明并返回 CSS 身份。 + +```sh +target/debug/marqdo call examples/web-site-zh/verify.mq.md theme_values --effects plugin,fs.read --fs-root examples/web-site-zh --require-ok --json +``` + +主题生成在 public/generated/theme.css;它是可再生产物,源码为相邻声明表,不应手改生成文件。字体链接保留 Google Fonts 地址,离线使用原声明中的后备字体;本地浏览器验收不声称验证远端字体服务送达。 + +公共创建表单继续公开,后台页面则有实际角色门禁。共享表单出现在后台不意味着提交端点自动私有。实际 HTTP 回归在 Tree、Bytecode 中使用独占副本站点;真实浏览器验证样式、发布、详情、会话导航、退出与窄屏顺序,避免操作示例已有数据库。 + +动手流程见英文对应工程的 [DEMO.md](../web-site/DEMO.md)。 diff --git a/examples/web-site-zh/components/articles.mq.md b/examples/web-site-zh/components/articles.mq.md new file mode 100644 index 0000000..0540861 --- /dev/null +++ b/examples/web-site-zh/components/articles.mq.md @@ -0,0 +1,34 @@ +--- +markup: occlusion +title: 当前文章卡片与短链详情 +import: + 组件: ext/web/网页/组件/索引.mq.md + 视图: ext/data/视图.mq.md + 表: lib/表.mq.md +--- + +两种视图随请求查询应用持有的同一 articles 表。卡片使用摘要和短链,详情使用完整 Markdown 正文。构造描述不另开数据库,也不缓存启动时的旧记录;原生卡片与文章类名供原主题继续使用。 + +## cards + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 通过 /post/短链 打开详情的当前文章卡片 | + +构造不需要副作用。监听应用拥有数据库与实际执行上下文,卡片保留原来的稳定 id 顺序,字段仍为 title、summary 与 slug。标题、摘要按文本转义,完整正文只留给详情。公共发布或后台共享表单新增文章后,下次请求即能看见,不必重启站点。 + +我们 **资源 = [描述实际当前文章列表](视图.查询(源="articles", 排序="id", 链接前缀="/post/"))**。 +最后返回 *[安放一个请求期间的卡片职责](组件.请求资源(值=`资源`, 槽="articles"))*。 + +## detail + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 实际路径捕获选中的首篇完整 Markdown 文章 | + +声明的 /post/{slug} 页面在请求解析资源时提供路径参数,同名查询字符串不能替换它。原生详情即使有摘要也使用完整正文,并且每次复制条件再替换参数,不污染启动时保留的定义。缺少数据库仍是错误;没有匹配记录沿用现有查询资源的空结果约定。 + +条件保留为明确记录,不能把单列表误当字典。父层继续拥有文章区域的位置,本函数不自己拼接标题或渲染 Markdown,以免与卡片规则和当前请求上下文分离。 + +我们 **条件 = [保留实际短链条件记录](表.设(map=None, key="slug", value="{slug}"))** 和 **资源 = [描述匹配短链的完整正文](视图.查询(源="articles", 条件=`条件`, 详情=True, 上限=1))**。 +最后返回 *[安放实际请求的文章](组件.请求资源(值=`资源`, 槽="article"))*。 diff --git a/examples/web-site-zh/components/content/about.md b/examples/web-site-zh/components/content/about.md new file mode 100644 index 0000000..d469ec5 --- /dev/null +++ b/examples/web-site-zh/components/content/about.md @@ -0,0 +1,5 @@ +> 关于 + +# 关于 + +文档与站点同一 .mq.md 制品。版式与主题是 styles/shell.mq.md 里的 GFM 样式表——无需手写 CSS 或业务 JavaScript。 diff --git a/examples/web-site-zh/components/content/desk-footer.md b/examples/web-site-zh/components/content/desk-footer.md new file mode 100644 index 0000000..157a171 --- /dev/null +++ b/examples/web-site-zh/components/content/desk-footer.md @@ -0,0 +1 @@ +[站点](/) · [后台](/admin) · [退出](/admin/logout) diff --git a/examples/web-site-zh/components/content/desk.md b/examples/web-site-zh/components/content/desk.md new file mode 100644 index 0000000..67997e7 --- /dev/null +++ b/examples/web-site-zh/components/content/desk.md @@ -0,0 +1,9 @@ +> 管理台 · 已进入后台 + +# 后台 + +这就是管理台(需登录):与前台共用 articles schema,装配成列表 + 创建表单——不是另写一套 SPA。顶栏「站点」回前台,「退出」结束会话。 + +- 登录门禁 +- 表声明 +- 创建 + 列表 diff --git a/examples/web-site-zh/components/content/footer.md b/examples/web-site-zh/components/content/footer.md new file mode 100644 index 0000000..eae8fb2 --- /dev/null +++ b/examples/web-site-zh/components/content/footer.md @@ -0,0 +1 @@ +[Marqdo](https://www.marqdo.com/) · [Source](https://github.com/cflmy/marqdo) diff --git a/examples/web-site-zh/components/content/home.md b/examples/web-site-zh/components/content/home.md new file mode 100644 index 0000000..bc4e7f2 --- /dev/null +++ b/examples/web-site-zh/components/content/home.md @@ -0,0 +1,13 @@ +> WWW Demo · 表即全栈 + +# Marqdo + +一份可执行 Markdown 声明路由、表单、后台与样式——作者零业务 JavaScript、零手写 .css。点击卡片打开全文,再按下列三步动手试。 + +- 0 作者 JS +- 0 作者 .css +- GFM 表 + +1. 点击任意卡片 — /post/{slug} 用同一张 articles 表打开详情。 +2. 打开[写文章](/new),空标题提交(规则表校验)。 +3. 点顶栏**登录**(admin / demo),再进**后台** — 门禁管理台:创建表单 + 列表。 diff --git a/examples/web-site-zh/components/content/new.md b/examples/web-site-zh/components/content/new.md new file mode 100644 index 0000000..c93791f --- /dev/null +++ b/examples/web-site-zh/components/content/new.md @@ -0,0 +1,5 @@ +> 表单 · 试校验 + +# 写文章 + +空标题提交应失败(规则表,非客户端 JS);填写标题、slug 与摘要后与后台、卡片网格共享一行。 diff --git a/examples/web-site-zh/components/content/post.md b/examples/web-site-zh/components/content/post.md new file mode 100644 index 0000000..3eea0ff --- /dev/null +++ b/examples/web-site-zh/components/content/post.md @@ -0,0 +1 @@ +> 文章 · 表绑定详情 diff --git a/examples/web-site-zh/components/desk.mq.md b/examples/web-site-zh/components/desk.mq.md index 5b220ef..b154266 100644 --- a/examples/web-site-zh/components/desk.mq.md +++ b/examples/web-site-zh/components/desk.mq.md @@ -1,30 +1,42 @@ --- markup: occlusion -title: components/desk -description: 管理台壳 — 顶栏品牌为「后台」,无前台侧栏。 +title: 后台独立导航与页脚 +import: + 组件: ext/web/网页/组件/索引.mq.md + 文件: lib/文件.mq.md --- +自定义后台保留自己的品牌与结束链接,不带公共侧栏。实际鉴权仍归服务入口;构造这些节点或隐藏某个链接都不会授权访客进入管理页面。 + ## nav -`nav` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 按当前会话解析的后台导航 | -| 属性 | 值 | 样式 | 媒体 | 当 | -|------|-----|------|------|-----| -| 后台 | /admin | | | | -| 站点 | / | | | | -| 写文章 | /new | | | | -| 退出 | /admin/logout | | | auth | +构造无需副作用。首项保持后台上下文,随后提供站点、写文章及退出;与原站一样,只有退出行依赖登录条件。整个页面已由服务入口另行保护,退出目的地仍是原生会话地址。本块返回结构化资源,父层负责位置和外观,不能把可见性判断当成服务器门禁。 -*`nav`* +后台与公共导航分开,避免管理中的品牌仍跳向首页。修改路径应同步检查真实处理器清单,防止链接看似存在却没有声明对应行为。 + +`项目` = + +| @ | label | href | when | +|---|---|---|---| +| 1 | 后台 | /admin | | +| 2 | 站点 | / | | +| 3 | 写文章 | /new | | +| 4 | 退出 | /admin/logout | auth | + +我们 **资源 = [描述后台实际会话导航](组件.导航资源(项=`项目`))**。 +最后返回 *[保持相同导航片段身份](组件.请求资源(值=`资源`, 槽="nav"))*。 ## foot -`foot` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 后台终端 Markdown 返回与退出链接 | -| 属性 | 值 | 样式 | -|------|-----|------| -| 站点 | / | | -| 后台 | /admin | | -| 退出 | /admin/logout | | +授予站点文件根的 fs.read。实际路由门禁在渲染本组件之前已决定访问,站点和后台保留返回目标;退出只有被访问时才结束会话,读叶子不产生退出操作。页脚只有一个链接职责,内部无独立几何,不为凑目录再拆一层。父层放置它,主题提供原来的页脚外观。 -*`foot`* +我们 **文本 = [读取后台终端结束链接](文件.读文本(路径="components/content/desk-footer.md"))** 和 **叶子 = [保留普通 Markdown 内容](组件.正文(文本=`文本`, 槽="footer-content"))**。 +最后返回 *[放入后台语义页脚](组件.包裹(子节点=`叶子`, 种类="footer", 槽="footer", 样式="foot"))*。 diff --git a/examples/web-site-zh/components/foot.mq.md b/examples/web-site-zh/components/foot.mq.md index db15bd8..c244f51 100644 --- a/examples/web-site-zh/components/foot.mq.md +++ b/examples/web-site-zh/components/foot.mq.md @@ -1,15 +1,21 @@ --- markup: occlusion +title: 公共页脚的终端 Markdown +import: + 组件: ext/web/网页/组件/索引.mq.md + 文件: lib/文件.mq.md --- +公共页脚只有项目与源码链接,内部没有独立双栏,因此简单 Markdown 就是拆分终点。父层决定它出现在何处,主题沿用原来页脚的颜色、间距和字号。 + ## foot -`foot` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 保留原始链接的语义页脚 | -| 属性 | 值 | 样式 | -|------|-----|------| -| Marqdo | https://www.marqdo.com/ | | -| Source | https://github.com/cflmy/marqdo | | +以站点为文件根授予 fs.read。内容叶子保留原项目与源码目的地,不查询业务记录,也不读取凭据。改文案只修改 content/footer.md;改几何回到父布局。组件输出仍是嵌套节点,不先把叶子渲染成不透明 HTML 再拼回页面。 -*`foot`* +我们 **文本 = [读取终端项目链接](文件.读文本(路径="components/content/footer.md"))** 和 **叶子 = [保留普通 Markdown 链接](组件.正文(文本=`文本`, 槽="footer-content"))**。 +最后返回 *[保留页脚语义与主题类](组件.包裹(子节点=`叶子`, 种类="footer", 槽="footer", 样式="foot"))*。 diff --git a/examples/web-site-zh/components/head.mq.md b/examples/web-site-zh/components/head.mq.md new file mode 100644 index 0000000..3374a2c --- /dev/null +++ b/examples/web-site-zh/components/head.mq.md @@ -0,0 +1,48 @@ +--- +markup: occlusion +title: 首页 SEO、共享字体与主题声明 +import: + 组件: ext/web/网页/组件/索引.mq.md + 页头: ext/web/页头.mq.md +--- + +本叶子保留原站的首页元数据与 Google Fonts 资源地址。装配只声明链接,不下载字体;主题由服务入口从表编译并写到明确静态目录。 + +## nodes + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| homepage | bool | False | 仅首页显式保留原来的首页 SEO | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 进入真正 head 的纯 SEO、字体与主题资源 | + +使用`homepage`=False,在装配阶段纯构造。元数据为 key/value 行记录,字体与样式继续使用 rel/href/crossorigin 原生字段。只有首页显式选择原来的 SEO,其余页面只共享字体与主题,避免把首页描述错误地复制到每篇文章。原生渲染将它们收集到真正 head,去重相同链接,不在正文或片段中输出占位。 + +字体是否成功送达取决于浏览器能否访问外部服务;不可用时仍使用主题声明的后备字体。地址声明不等于生成文件,服务入口须在监听之前编译并写出确切路径。资源构造不加载插件、不验证远端状态、不运行脚本,也不把网络错误当作已经加载成功。 + +字体表中的第一项预连接样式服务,第二项保留字体源的 anonymous 跨域设置,第三项保留原始字体集合与字重。最后的站内样式链接只对应本次生成产物,源头仍是可读属性表。标题与文案保留在各自 Document,页头不承担整页配置或应用变异。离线预览使用同一个元数据收集过程,片段只更新已打开页面,不重复注入字体与 SEO。 + +`元数据` = + +| @ | key | value | +|---|---|---| +| 1 | description | 表即全栈 — Marqdo 网页示例;作者零业务 JavaScript。 | +| 2 | og:type | website | +| 3 | og:title | Marqdo 中文站 | + +`链接` = + +| @ | rel | href | crossorigin | +|---|---|---|---| +| 1 | preconnect | https://fonts.googleapis.com | | +| 2 | preconnect | https://fonts.gstatic.com | anonymous | +| 3 | stylesheet | https://fonts.googleapis.com/css2?family=Great+Vibes&family=Noto+Sans+SC:wght@300;400;500;700&family=Noto+Serif+SC:wght@400;600&display=swap | | +| 4 | stylesheet | /static/generated/theme.css | | + +我们 **选定元数据 = None**,其他页面只保留共享链接。 +1. `homepage` + 我们 **选定元数据 = 元数据**,只给首页保留原 SEO。 +我们 **资源 = [保留实际元数据与原生资源链接](页头.声明(元数据=`选定元数据`, 链接=`链接`))**。 +最后返回 *[把纯页头声明与结构一起保留](组件.请求资源(值=`资源`, 槽="document-head"))*。 diff --git a/examples/web-site-zh/components/index.mq.md b/examples/web-site-zh/components/index.mq.md new file mode 100644 index 0000000..94b2ab9 --- /dev/null +++ b/examples/web-site-zh/components/index.mq.md @@ -0,0 +1,37 @@ +--- +markup: occlusion +title: 公共与后台递归布局入口 +import: + 组件: ext/web/网页/组件/索引.mq.md + 导航: nav.mq.md + 侧栏: side.mq.md + 页脚: foot.mq.md + 后台: desk.mq.md + 页头: head.mq.md + 表: lib/表.mq.md +--- + +本父模块只决定站点结构。公共页面保留导航、侧栏和主体、页脚;后台采用自己的导航与页脚,不带公共侧栏。各子模块拥有 Markdown 或具型请求资源,父层不渲染子块后再拼 HTML。 + +## frame + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| body | list | 必填 | 页面自己提供并保留资源值的主体节点 | +| management | bool | False | 选择已被实际门禁保护的后台框架 | +| homepage | bool | False | 只有首页保留原来的首页 SEO | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 递归站点结构及真正收集到 head 的纯资源 | + +使用`body`、`management`=False、`homepage`=False。导航按当前请求会话解析,本函数不认证用户;后台路径由服务入口另行保护,选择后台框架不会授予权限。页脚只有一组普通链接,内部已可用简单 Markdown 表示,因此无需人为继续拆分。 + +稳定槽名 nav、sidebar、main 与 footer 保留片段身份。原生资源外层继续留在结构树中,主题让其语义子块参与原来的命名网格。is-desk 类属于这个明确框架,代替旧的整页 body 变异;颜色、动画与属性值仍来自原始声明。纯页头资源不会成为用户正文。 + +我们 **顶部 = [组合公共导航](导航.nav())**、**旁栏 = [组合公共侧栏](侧栏.side())**、**底部 = [读取公共 Markdown 页脚](页脚.foot())** 和 **样式 = "site-layout has-sidebar"**。 +1. `management` + 我们 **顶部 = [使用后台自己的导航](后台.nav())**、**旁栏 = [后台不带公共侧栏](表.空表())**、**底部 = [读取后台返回链接](后台.foot())** 和 **样式 = "site-layout no-sidebar is-desk"**。 +我们 **主体 = [保留页面自身的正文责任](组件.包裹(子节点=`body`, 种类="section", 槽="main", 样式="main"))**、**子块 = [导航位于公共侧栏之前](表.拼接(a=`顶部`, b=`旁栏`))**、**子块 = [放入实际主体](表.拼接(a=`子块`, b=`主体`))** 和 **子块 = [以选定页脚结束](表.拼接(a=`子块`, b=`底部`))**。 +接着 **框架 = [声明稳定的站点区域](组件.包裹(子节点=`子块`, 种类="section", 槽="site", 样式=`样式`))** 和 **资源 = [保留字体、主题与选定 SEO](页头.nodes(homepage=`homepage`))**。 +最后返回 *[让声明与递归框架一并保留](表.拼接(a=`资源`, b=`框架`))*。 diff --git a/examples/web-site-zh/components/intro.mq.md b/examples/web-site-zh/components/intro.mq.md new file mode 100644 index 0000000..e431ba3 --- /dev/null +++ b/examples/web-site-zh/components/intro.mq.md @@ -0,0 +1,26 @@ +--- +markup: occlusion +title: 终端 Markdown 引言组件 +import: + 组件: ext/web/网页/组件/索引.mq.md + 文件: lib/文件.mq.md +--- + +引言终止于普通 Markdown:分类、标题、解释、特性列表与阅读步骤。它们已经能直接用文档层次表达,主题选择这些真实语义元素。页面几何仍归父框架,不恢复旧的引言绑定方言。 + +## nodes + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | text | 必填 | 作者选择的 home、about、new、desk 或 post 叶子 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 包裹实际终端 Markdown 的语义引言区域 | + +输入`name`,在站点文件根授权 fs.read。路径由作者的 Document 选择,不是请求参数。缺失叶子保留原生文件诊断,不回退到抄写的固定正文。读取内容不会把其中的强调或链接执行成 Marqdo 语句,而是交给既有 Markdown 渲染器解释。 + +叶子内部没有独立的排列职责,只有引用分类、标题、段落、项目符号和编号步骤。若将来出现需要独立几何的子区域,应继续拆分。样式保留原来的字体、徽章与步骤面板,内容仍直接可读。 + +我们 **路径 = "components/content/" + name + ".md"**、**文本 = [读取这段引言的实际内容](文件.读文本(路径=`路径`))** 和 **叶子 = [保留简单的 Markdown 层次](组件.正文(文本=`文本`, 槽="intro-content"))**。 +完成后返回 *[将引言放入明确语义区域](组件.包裹(子节点=`叶子`, 种类="section", 槽="intro", 样式="main-intro"))*。 diff --git a/examples/web-site-zh/components/nav.mq.md b/examples/web-site-zh/components/nav.mq.md index 6bd8ecc..ffc76c7 100644 --- a/examples/web-site-zh/components/nav.mq.md +++ b/examples/web-site-zh/components/nav.mq.md @@ -1,20 +1,32 @@ --- markup: occlusion +title: 实际会话中的导航组件 +import: + 组件: ext/web/网页/组件/索引.mq.md --- +本模块只拥有这一组导航。文字、目标及顺序保留原站约定,会话相关行必须在每次请求中决定,因此使用具型导航资源,不能把启动时的身份快照当成当前用户。 + ## nav -顶栏:**登录**(访客)/ **后台** + **退出**(已登录)。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 保留稳定片段槽名的单个导航请求资源 | -`nav` = +构造是纯计算,不登录、退出或注册路由。空 when 始终显示,guest 与 auth 按服务器当前会话筛选;原生导航类名继续服务于已有主题。隐藏后台链接不能阻止直接访问,服务入口另行对实际 /admin 地址绑定角色门禁。 -| 属性 | 值 | 样式 | 媒体 | 当 | -|------|-----|------|------|-----| -| Marqdo | / | | | | -| 关于 | /about | | | | -| 写文章 | /new | | | | -| 登录 | /login | | | guest | -| 后台 | /admin | | | auth | -| 退出 | /admin/logout | | | auth | +父模块负责网格位置,本块只解释目标。改文字在这里完成,改路径同时核对声明的 Document。资源值保留结构,不拼 HTML,也不返回已被移除的 front/back 页面绑定表。 -*`nav`* +`项目` = + +| @ | label | href | when | +|---|---|---|---| +| 1 | Marqdo | / | | +| 2 | 关于 | /about | | +| 3 | 写文章 | /new | | +| 4 | 登录 | /login | guest | +| 5 | 后台 | /admin | auth | +| 6 | 退出 | /admin/logout | auth | + +我们 **资源 = [描述当前会话的可见链接](组件.导航资源(项=`项目`, 区域="nav"))**。 +最后返回 *[保留一个具型导航区域](组件.请求资源(值=`资源`, 槽="nav"))*。 diff --git a/examples/web-site-zh/components/side.mq.md b/examples/web-site-zh/components/side.mq.md index b6bdf78..f664be1 100644 --- a/examples/web-site-zh/components/side.mq.md +++ b/examples/web-site-zh/components/side.mq.md @@ -1,17 +1,31 @@ --- markup: occlusion +title: 实际会话中的侧栏组件 +import: + 组件: ext/web/网页/组件/索引.mq.md --- +本模块只拥有这一组导航。文字、目标及顺序保留原站约定,会话相关行必须在每次请求中决定,因此使用具型导航资源,不能把启动时的身份快照当成当前用户。 + ## side -`side` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 保留稳定片段槽名的单个导航请求资源 | -| 属性 | 值 | 样式 | 媒体 | 当 | -|------|-----|------|------|-----| -| 1. 首页 | / | | | | -| 2. 写文章 | /new | | | | -| 3. 登录 | /login | | | guest | -| 3. 后台 | /admin | | | auth | -| 关于 | /about | | | | +构造是纯计算,不登录、退出或注册路由。空 when 始终显示,guest 与 auth 按服务器当前会话筛选;原生导航类名继续服务于已有主题。隐藏后台链接不能阻止直接访问,服务入口另行对实际 /admin 地址绑定角色门禁。 -*`side`* +父模块负责网格位置,本块只解释目标。改文字在这里完成,改路径同时核对声明的 Document。资源值保留结构,不拼 HTML,也不返回已被移除的 front/back 页面绑定表。 + +`项目` = + +| @ | label | href | when | +|---|---|---|---| +| 1 | 1. 首页 | / | | +| 2 | 2. 写文章 | /new | | +| 3 | 3. 登录 | /login | guest | +| 4 | 3. 后台 | /admin | auth | +| 5 | 关于 | /about | | + +我们 **资源 = [描述当前会话的可见链接](组件.导航资源(项=`项目`, 区域="sidebar"))**。 +最后返回 *[保留一个具型导航区域](组件.请求资源(值=`资源`, 槽="sidebar"))*。 diff --git a/examples/web-site-zh/db/articles.mq.md b/examples/web-site-zh/db/articles.mq.md index 6c063b3..b442585 100644 --- a/examples/web-site-zh/db/articles.mq.md +++ b/examples/web-site-zh/db/articles.mq.md @@ -1,36 +1,32 @@ --- markup: occlusion +title: 文章结构与种子调用手册 +import: + document: lib/document.mq.md --- +本文件解释各个调用的用途;相邻的 [articles.tables.md](articles.tables.md) 保存可直接阅读的字面表。把 --fs-root 指向站点目录,读取需要 fs.read。字段、样式与正文是数据,读取不会执行文件中的说明。 + ## schema -`fields` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 原生字面表的原始类型与列式数据形态 | -| 字段 | 类型 | 可空 | -|------|------|------| -| id | integer | false | -| title | text | false | -| slug | text | false | -| summary | text | true | -| body | text | true | +声明文章的字段、原生类型与可空约束;id 的数值类型和必填字段保持不变。数据库初始化器使用此表保证结构,不负责猜测用户数据的迁移。 -*`fields`* +授予站点文件根的 fs.read 后可独立调用。章节名精确匹配且必须唯一;表头、行列不齐或动态表达式会保留原生文档诊断。需要实际样式时再调用 css;需要数据库记录时交给数据库资源。返回值不是 HTML,也不是已应用的浏览器效果。 + +完成后返回*[读取 schema 的实际字面表](document.read_table(path="db/articles.tables.md", title="schema"))*. ## seed -卡片显示 summary;/post/{slug} 显示完整 body(Markdown)。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 原生字面表的原始类型与列式数据形态 | -`rows` = +提供起始演示文章,保留原来的 id、短链、摘要与正文。只有数据库初始化器确认空表后才应插入;读取本函数不会写入或重置现有文章。 -| id | title | slug | summary | body | -|----|-------|------|---------|------| -| 1 | 你好 Marqdo | hello-marqdo | 一份可执行 Markdown 既是站点说明,也是上线制品——路由、表单与样式都用表声明。 | "Marqdo 把 .mq.md 当作可执行文档。编辑器里读到的叙述,就是服务器跑起来的同一份制品:GFM 表变成 schema、表单、导航与 CSS。本 Demo 走完这条契约——打开「写文章」、触发规则表校验,再发布一行,首页与后台同时出现,全程无需作者业务 JavaScript。" | -| 2 | 表即全栈 | tables-full-stack | Schema、表单、路由、后台与主题令牌共用一套表方言,而不是 JS/CSS 分家。 | "常见技术栈把关切拆进多种语言:数据用 SQL/ORM,输入用表单库,URL 用路由,外观用手写样式。Marqdo 把这些表面收成作者本来就会写的 GFM 表。字段表、规则表、绑定表、样式表不是比喻,而是运行时。结果是一份既能当散文扫读、又能当程序执行的站点。" | -| 3 | 零作者 JS 与 CSS | zero-author-js-css | 业务留在 Markdown;外观是样式表加宿主壳——无作者业务 JS、无作者 .css。 | "作者业务 JavaScript 从构造上为零:校验来自服务端规则表,列表/详情由绑定表交给宿主渲染。主题令牌写在属性/值表里,经样式装配变成 CSS,作者也不必维护 .css 文件。本 Demo 关闭壳样式,只让声明过的样式上色——方便会议观众当场核对主张。" | -| 4 | 一表打通卡片与详情 | card-to-detail | 列表把 href 绑到 slug;/post/{slug} 加详情=真即可打开全文。 | "点击首页任意卡片。列表绑定用 articles.slug 作为 href,链接前缀补上 /post/。详情页复用同一张表,查询条件 slug = {slug},再页面.详情,首行就渲染成完整文章(标题 + Markdown 正文),而不是卡片网格。这与求道量子等更大的 Marqdo 站同一套路。" | -| 5 | 样式表不是样式文件 | style-tables | 具名样式表(kicker、intro_title、card_title)通过绑定表第三列挂上。 | "引言、卡片与壳层都用属性/值/样式绑定。样式列指向 styles/shell.mq.md 里的具名属性表。引言装配或主体装配时,这些表变成页面上的 CSS 类。改 Demo 外观不必打开 .css——改可读的 Markdown 表,文案与样式仍挨在一起。" | -| 6 | 表单来自字段表与规则表 | forms-from-tables | 「写文章」空标题会因规则表失败;合法提交写入与后台共享的一行。 | "写文章与后台挂载同一表单对象:字段表声明标签与类型,规则表声明 required、max 与提示文案。空标题提交时错误来自服务端,不是客户端脚本。填好标题与 slug 再提交,卡片网格与后台列表都会出现——一张 schema、两个表面、零作者 JS。" | -| 7 | 种子数据就是文档 | seed-is-docs | 这些段落写在 GFM 种子表里——Demo 正文也是程序的一部分。 | "种子行与 schema 同在 db/articles.mq.md。首次启动若表为空,宿主会插入它们。于是 Demo 叙述与代码同版本:卡片用稍长摘要,详情用更长正文,slug 保证深链稳定。审稿人打开种子表,就能看到会场站点将展示的内容。" | -| 8 | 为什么要做这个 Demo | why-demo-matters | WWW Demo 需要审稿人几分钟内能跑、能点、能对照源码的制品。 | "Demo 轨道要的是可运行系统,不是只靠幻灯片。本样站刻意很小:一张 SQLite 表、几条路由、一套文学风壳层——却覆盖论文主张(表即全栈),并配三步操作脚本。克隆仓库,运行样站,点开卡片,弄坏一次表单,再把 index.mq.md 与浏览器对照。这个闭环就是投稿本身。" | +授予站点文件根的 fs.read 后可独立调用。章节名精确匹配且必须唯一;表头、行列不齐或动态表达式会保留原生文档诊断。需要实际样式时再调用 css;需要数据库记录时交给数据库资源。返回值不是 HTML,也不是已应用的浏览器效果。 -*`rows`* +完成后返回*[读取 seed 的实际字面表](document.read_table(path="db/articles.tables.md", title="seed"))*. diff --git a/examples/web-site-zh/db/articles.tables.md b/examples/web-site-zh/db/articles.tables.md new file mode 100644 index 0000000..99e4512 --- /dev/null +++ b/examples/web-site-zh/db/articles.tables.md @@ -0,0 +1,30 @@ +# Article data + +Literal article schema and demonstration content. Reading these tables does not open a database or insert rows. Follow articles.mq.md for callable use; the database initializer decides whether seeding is appropriate. + +## schema + +Field definitions for the native database initializer; nullable values remain booleans. + +| 字段 | 类型 | 可空 | +|------|------|------| +| id | integer | false | +| title | text | false | +| slug | text | false | +| summary | text | true | +| body | text | true | + +## seed + +Initial demonstration records in their original column-oriented shape; ids and stable slugs retain their meaning. + +| id | title | slug | summary | body | +|----|-------|------|---------|------| +| 1 | 你好 Marqdo | hello-marqdo | 一份可执行 Markdown 既是站点说明,也是上线制品——路由、表单与样式都用表声明。 | "Marqdo 把 .mq.md 当作可执行文档。编辑器里读到的叙述,就是服务器跑起来的同一份制品:GFM 表变成 schema、表单、导航与 CSS。本 Demo 走完这条契约——打开「写文章」、触发规则表校验,再发布一行,首页与后台同时出现,全程无需作者业务 JavaScript。" | +| 2 | 表即全栈 | tables-full-stack | Schema、表单、路由、后台与主题令牌共用一套表方言,而不是 JS/CSS 分家。 | "常见技术栈把关切拆进多种语言:数据用 SQL/ORM,输入用表单库,URL 用路由,外观用手写样式。Marqdo 把这些表面收成作者本来就会写的 GFM 表。字段表、规则表、绑定表、样式表不是比喻,而是运行时。结果是一份既能当散文扫读、又能当程序执行的站点。" | +| 3 | 零作者 JS 与 CSS | zero-author-js-css | 业务留在 Markdown;外观是样式表加宿主壳——无作者业务 JS、无作者 .css。 | "作者业务 JavaScript 从构造上为零:校验来自服务端规则表,列表/详情由绑定表交给宿主渲染。主题令牌写在属性/值表里,经样式装配变成 CSS,作者也不必维护 .css 文件。本 Demo 关闭壳样式,只让声明过的样式上色——方便会议观众当场核对主张。" | +| 4 | 一表打通卡片与详情 | card-to-detail | 列表把 href 绑到 slug;/post/{slug} 加详情=真即可打开全文。 | "点击首页任意卡片。列表绑定用 articles.slug 作为 href,链接前缀补上 /post/。详情页复用同一张表,查询条件 slug = {slug},再页面.详情,首行就渲染成完整文章(标题 + Markdown 正文),而不是卡片网格。这与求道量子等更大的 Marqdo 站同一套路。" | +| 5 | 样式表不是样式文件 | style-tables | 具名样式表(kicker、intro_title、card_title)通过绑定表第三列挂上。 | "引言、卡片与壳层都用属性/值/样式绑定。样式列指向 styles/shell.mq.md 里的具名属性表。引言装配或主体装配时,这些表变成页面上的 CSS 类。改 Demo 外观不必打开 .css——改可读的 Markdown 表,文案与样式仍挨在一起。" | +| 6 | 表单来自字段表与规则表 | forms-from-tables | 「写文章」空标题会因规则表失败;合法提交写入与后台共享的一行。 | "写文章与后台挂载同一表单对象:字段表声明标签与类型,规则表声明 required、max 与提示文案。空标题提交时错误来自服务端,不是客户端脚本。填好标题与 slug 再提交,卡片网格与后台列表都会出现——一张 schema、两个表面、零作者 JS。" | +| 7 | 种子数据就是文档 | seed-is-docs | 这些段落写在 GFM 种子表里——Demo 正文也是程序的一部分。 | "种子行与 schema 同在 db/articles.mq.md。首次启动若表为空,宿主会插入它们。于是 Demo 叙述与代码同版本:卡片用稍长摘要,详情用更长正文,slug 保证深链稳定。审稿人打开种子表,就能看到会场站点将展示的内容。" | +| 8 | 为什么要做这个 Demo | why-demo-matters | WWW Demo 需要审稿人几分钟内能跑、能点、能对照源码的制品。 | "Demo 轨道要的是可运行系统,不是只靠幻灯片。本样站刻意很小:一张 SQLite 表、几条路由、一套文学风壳层——却覆盖论文主张(表即全栈),并配三步操作脚本。克隆仓库,运行样站,点开卡片,弄坏一次表单,再把 index.mq.md 与浏览器对照。这个闭环就是投稿本身。" | diff --git a/examples/web-site-zh/db/index.mq.md b/examples/web-site-zh/db/index.mq.md index 60f7971..8d038b3 100644 --- a/examples/web-site-zh/db/index.mq.md +++ b/examples/web-site-zh/db/index.mq.md @@ -1,21 +1,37 @@ --- markup: occlusion -title: db/index -description: 打开 sqlite、建表、幂等种子。 -导入: - 网页: ext/web/网页.mq.md +title: web-site-zh database lifecycle +import: + data: ext/data/db.mq.md articles: articles.mq.md + fs: lib/fs.mq.md + text: lib/text.mq.md --- +The database entry connects schema and literal seed leaves to the actual data resource. It no longer uses the removed web database constructor. Grant fs.write and plugin with the site directory as --fs-root; the SQLite path is resolved through that native root rather than the process working directory. + ## open -**store = > 网页.数据库 地址="sqlite:data/site-zh.db"** -**fields = > articles.schema** -> `store`.初始化 名=articles 字段=`fields` -**rows = > store.查询 表="articles" 上限=1** -1. `rows` - *store* -2. * - **seed = > articles.seed** - > `store`.插入 表=articles 行=`seed` - *store* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | any | None | None selects data/site-zh.db under the site root; tests provide a disposable explicit URI | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Initialized articles database resource with existing rows preserved | + +Use `url`=None to open the site's local database. Create the default data directory through native file operations, then resolve the actual SQLite filename within the granted root. An explicit SQLite path goes through the same root and symlink checks before the native database resource receives it. Other supported database URIs retain their resource-specific backend contract; they are not sandboxed by filesystem permissions. + +The schema reader preserves native field types and nullability. Initialization ensures the table exists, queries one row to distinguish an empty table, and inserts the original demonstration content only into an empty table. An existing or partly populated table is kept unchanged. This is not a column migrator, data repair tool or reason to delete a user's articles. A native connection, schema or insert diagnostic stops the caller before it starts serving. + +For isolated verification choose a caller-owned temporary SQLite file and copy the article data leaf under that granted site root. Keep the returned resource in the same program for subsequent queries. Close the process before cleaning its owned directory; do not run tests against the example's existing data directory. + +1. `url` == None + We **[Create only the site's default data directory](fs.make_dirs(path="data"))** and **file = [Resolve its database filename](fs.resolve(path="data/site-zh.db"))** and **url = "sqlite:" + file**. +1. [The explicit or default URI selects SQLite](text.starts_with(text=`url`, prefix="sqlite:")) + We **file = [Read the selected SQLite path](text.replace(text=`url`, old="sqlite:", new="", count=1))** and **file = [Apply the native file-root policy](fs.resolve(path=`file`))** and **url = "sqlite:" + file**. +We **store = [Open the selected actual database resource](data.db(url=`url`))** and **fields = [Read the documented article schema](articles.schema())**. +We **[Ensure the table without clearing it](> `store`.init name="articles" fields=`fields`)** and **existing = [Check whether business records already exist](> `store`.select table="articles" limit=1)**. +1. not `existing` + We **seed = [Read the original demonstration data](articles.seed())** and **[Seed only the empty article table](> `store`.insert table="articles" rows=`seed`)**. +Once the selected database is ready, return *store* for the site's resource bindings. diff --git a/examples/web-site-zh/forms.mq.md b/examples/web-site-zh/forms.mq.md new file mode 100644 index 0000000..5df6ffe --- /dev/null +++ b/examples/web-site-zh/forms.mq.md @@ -0,0 +1,26 @@ +--- +markup: occlusion +title: 共享文章表单与服务器校验 +import: + 表单: ext/data/表单.mq.md + document: lib/document.mq.md +--- + +写文章与后台引用同一个 article 表单,服务入口只挂载一次。字段、规则、展示和数据库提交因此使用同一资源。原示例的公共发布仍为公开入口,自定义后台路径另有真实角色门禁。 + +## article + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 包含标题、短链、摘要、正文与原始校验上限的插入表单 | + +构造与挂载需要 plugin,并在站点根授予 fs.read 读取相邻的字面字段和规则。标题和短链必填,上限分别是 120 与 80 字符;摘要与正文可空,上限分别是 500 与 8000 字符。浏览器必填提示不能取代这些服务器规则,绕过浏览器校验仍得到实际拒绝消息。构造不会写行或认证用户。 + +输入类型继续为 text 与 textarea,保留原字段行为。拒绝提交后保留字段错误与当前 CSRF,成功返回首页的实时卡片列表。每次更新都保留新资源,否则挂载旧值会丢掉字段或规则。字段表里的 name 是数据库列名,label 只是用户文案;摘要和完整正文分别展示,不相互替代。 + +这个表单并不因为出现在后台就变成私有接口。真正私有的业务应保护它自己的系统提交地址,示例明确保留公共创建能力,避免只保护展示页却错误宣称数据写入已受限。 + +我们 **字段 = [读取实际字面字段契约](document.read_table(path="forms.tables.md", title="fields"))** 和 **规则 = [读取实际字面校验规则](document.read_table(path="forms.tables.md", title="rules"))**。 + +我们 **资源 = [创建实际文章插入资源](表单.构造(表="articles"))**、**资源 = [绑定可读字段记录](表单.字段(资源=`资源`, 定义=`字段`))** 和 **资源 = [绑定实际服务器规则](表单.规则(资源=`资源`, 定义=`规则`))**。 +最后返回 *[保留提交文案与成功返回目标](表单.文案(资源=`资源`, 提交="发布", 取消="取消", 返回地址="/"))*。 diff --git a/examples/web-site-zh/forms.tables.md b/examples/web-site-zh/forms.tables.md new file mode 100644 index 0000000..6121dc5 --- /dev/null +++ b/examples/web-site-zh/forms.tables.md @@ -0,0 +1,27 @@ +# 文章表单数据 + +可调用契约在 forms.mq.md。这里保存原始字面行,不是另一份提交实现。字段对应既有 articles schema,原生展示和服务器校验使用同一记录。 + +## fields + +标题与短链必填,摘要和正文可选,输入类型保持原样。 + +| @ | name | label | type | required | +|---|---|---|---|---| +| 1 | title | 标题 | text | True | +| 2 | slug | slug | text | True | +| 3 | summary | 摘要 | textarea | False | +| 4 | body | 正文 | textarea | False | + +## rules + +服务器使用这些原始规则与错误文案,浏览器提示不能替代它们。 + +| @ | field | rule | message | +|---|---|---|---| +| 1 | title | required | 标题不能为空 | +| 2 | title | max:120 | 标题太长 | +| 3 | slug | required | slug 不能为空 | +| 4 | slug | max:80 | slug 太长 | +| 5 | summary | max:500 | 摘要太长 | +| 6 | body | max:8000 | 正文太长 | diff --git a/examples/web-site-zh/index.mq.md b/examples/web-site-zh/index.mq.md index f52884e..9da7cba 100644 --- a/examples/web-site-zh/index.mq.md +++ b/examples/web-site-zh/index.mq.md @@ -1,205 +1,60 @@ --- markup: occlusion -title: 中文站点示例 -description: >- - 与 examples/web-site 对等的 WWW Demo 样站:表驱动全站;作者业务 JS=0;作者 .css=0。 -导入: +type: web +view: main +route: / +title: Marqdo 中文站 +import: + 布局: components/index.mq.md + 引言: components/intro.mq.md + 文章: components/articles.mq.md + 数据库: db/index.mq.md + 表单定义: forms.mq.md + 主题: styles/index.mq.md 网页: ext/web/网页.mq.md - shell: styles/shell.mq.md - nav: components/nav.mq.md - side: components/side.mq.md - foot: components/foot.mq.md - desk: components/desk.mq.md - articles: db/articles.mq.md - db: db/index.mq.md + 表单: ext/data/表单.mq.md + 鉴权: ext/security/鉴权.mq.md + 文件: lib/文件.mq.md + 表: lib/表.mq.md --- -# main +本入口是可执行建站手册。先读组件入口的公共与后台结构,再读终端 Markdown、请求期间文章、表单和数据库。首页、关于、写文章、后台与短链详情各自声明路由。当前会话决定导航,实际访问策略由安全资源执行;自定义后台不启用另一套原生后台首页。 -本文件既是站点说明,也是可运行应用。 +## main -`home` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 公共框架内的 Markdown 介绍与当前文章卡片 | -| 组件 | 样式 | -|------|------| -| nav.`nav` | shell.`topnav` | -| side.`side` | shell.`side_panel` | -| foot.`foot` | shell.`footer` | +启动装配只读取内容叶子并构造查询描述,不初始化或清空数据库。监听应用保留的实际资源在请求期间查询文章;发布后下次访问直接看到新记录。共享布局保留导航、侧栏、页脚、首页 SEO、字体与原始文学主题。改一块内容沿导入找到自己的叶子,不能把完整页面壳复制到每个路由。 -后台壳:去掉前台侧栏,顶栏品牌改为「后台」。 +我们 **说明 = [读取首页终端介绍](引言.nodes(name="home"))**、**卡片 = [描述当前文章卡片](文章.cards())** 和 **正文 = [让说明先于业务记录](表.拼接(a=`说明`, b=`卡片`))**。 +最后返回 *[放入共享公共框架并保留首页 SEO](布局.frame(body=`正文`, homepage=True))*。 -`desk_shell` = +## serve -| 组件 | 样式 | -|------|------| -| desk.`nav` | shell.`topnav` | -| desk.`foot` | shell.`footer` | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| root | text | "examples/web-site-zh" | 相对仓库的明确站点发现目录 | +| port | number | 18082 | 本机回环监听端口 | +| url | any | None | None 保留站点根 SQLite;验收指定独占临时 URI | -`index` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 数据、表单、鉴权及自定义后台门禁齐备后的阻塞监听结果 | -| 属性 | 值 | 样式 | -|------|-----|------| -| title | articles.`articles`.title | shell.`card_title` | -| body | articles.`articles`.summary | shell.`card_body` | -| href | articles.`articles`.slug | | +从仓库根使用`root`="examples/web-site-zh"、`port`=18082、`url`=None,授予 plugin,fs.write,network.write 并设置 --fs-root examples/web-site-zh。初始化只为空表播种,已有文章全部保留。原始主题数据叶子不变,样式入口只把旧壳选择器映射到明确的 View 结构,并恢复原来由装配操作附着的命名属性表。 -`detail` = +主题在发现页面之前编译并原生写入 public/generated。准备站点不监听;同一文章表单同时供公共发布页与后台引用。随后绑定本地演示会话,并对实际 /admin 路径施加角色门禁,每次更新都保留新应用,最后才监听。admin/demo 只是回环演示账户,部署应替换用户来源与网络策略。服务阻塞当前进程,由调用者负责停止;不要为验收删除示例已有 data 目录。 -| 属性 | 值 | 样式 | -|------|-----|------| -| title | articles.`articles`.title | shell.`card_title` | -| body | articles.`articles`.body | | +我们 **存储 = [初始化并保留原有文章](数据库.open(url=`url`))**、**样式 = [编译真实 View 主题映射](主题.css())**,并 **[建立明确的生成目录](文件.建目录(路径="public/generated"))**、**[原生写入本次编译的主题](文件.原子写文本(路径="public/generated/theme.css", 内容=`样式`))**。 +接着 **应用 = [发现五个明确声明的页面](网页.准备站点(根=`root`, 主机="127.0.0.1", 端口=`port`, 数据库=`存储`, 静态目录="public"))**、**资源 = [构造共享服务器校验规则](表单定义.article())** 和 **应用 = [明确挂载公开文章表单](表单.挂载(应用=`应用`, 标识="article", 资源=`资源`))**。 -`by_slug` = +`用户` = -| 字段 | 操作 | 值 | -|------|------|-----| -| slug | = | {slug} | +| @ | username | password | role | +|---|---|---|---| +| 1 | admin | demo | admin | -`首页引言` = - -| 属性 | 值 | 样式 | -|------|-----|------| -| 眉题 | WWW Demo · 表即全栈 | shell.`kicker` | -| 标题 | Marqdo | shell.`intro_title` | -| 导语 | "一份可执行 Markdown 声明路由、表单、后台与样式——作者零业务 JavaScript、零手写 .css。点击卡片打开全文,再按下列三步动手试。" | shell.`lede` | -| 标签 | 0 作者 JS | shell.`claim` | -| 标签 | 0 作者 .css | shell.`claim` | -| 标签 | GFM 表 | shell.`claim` | -| 步骤 | "点击任意卡片 — /post/{slug} 用同一张 articles 表打开详情。" | shell.`step` | -| 步骤 | "打开 [写文章](/new),空标题提交(规则表校验)。" | shell.`step` | -| 步骤 | "点顶栏 **登录**(admin / demo),再进 **后台** — 门禁管理台:创建表单 + 列表。" | shell.`step` | - -`关于引言` = - -| 属性 | 值 | 样式 | -|------|-----|------| -| 眉题 | 关于 | shell.`kicker` | -| 标题 | 关于 | shell.`intro_title` | -| 导语 | "文档与站点同一 .mq.md 制品。版式与主题是 styles/shell.mq.md 里的 GFM 样式表——无需手写 CSS 或业务 JavaScript。" | shell.`lede` | - -`写文章引言` = - -| 属性 | 值 | 样式 | -|------|-----|------| -| 眉题 | 表单 · 试校验 | shell.`kicker` | -| 标题 | 写文章 | shell.`intro_title` | -| 导语 | 空标题提交应失败(规则表,非客户端 JS);填写标题、slug 与摘要后与后台、卡片网格共享一行。 | shell.`lede` | - -`后台引言` = - -| 属性 | 值 | 样式 | -|------|-----|------| -| 眉题 | 管理台 · 已进入后台 | shell.`kicker` | -| 标题 | 后台 | shell.`intro_title` | -| 导语 | "这就是管理台(需登录):与前台共用 articles schema,装配成列表 + 创建表单——不是另写一套 SPA。顶栏「站点」回前台,「退出」结束会话。" | shell.`lede` | -| 标签 | 登录门禁 | shell.`claim` | -| 标签 | 表声明 | shell.`claim` | -| 标签 | "创建 + 列表" | shell.`claim` | - -`文章引言` = - -| 属性 | 值 | 样式 | -|------|-----|------| -| 眉题 | 文章 · 表绑定详情 | shell.`kicker` | - -`article_fields` = - -| 字段 | 标签 | 类型 | 必填 | 默认 | -|------|------|------|------|------| -| title | 标题 | text | true | | -| slug | slug | text | true | | -| summary | 摘要 | textarea | false | | -| body | 正文 | textarea | false | | - -`article_rules` = - -| 字段 | 规则 | 消息 | -|------|------|------| -| title | required | 标题不能为空 | -| title | max:120 | 标题太长 | -| slug | required | slug 不能为空 | -| slug | max:80 | slug 太长 | -| summary | max:500 | 摘要太长 | -| body | max:8000 | 正文太长 | - -`home_meta` = - -| key | value | -|-----|-------| -| description | 表即全栈 — Marqdo 网页示例;作者零业务 JavaScript。 | -| og:type | website | -| og:title | Marqdo 中文站 | - -`fonts` = - -| 关系 | 地址 | 跨域 | -|------|------|------| -| preconnect | https://fonts.googleapis.com | | -| preconnect | https://fonts.gstatic.com | anonymous | -| stylesheet | https://fonts.googleapis.com/css2?family=Great+Vibes&family=Noto+Sans+SC:wght@300;400;500;700&family=Noto+Serif+SC:wght@400;600&display=swap | | - -**store = > db.open** -**site_css = > shell.css** - -**page = > 网页.页面 标题="Marqdo 中文站" 壳样式="off"** -**page = > page.引言装配 引言=`首页引言`** -**page = > page.元数据 元数据=home_meta** -**page = > page.头装配 表=fonts** -**page = > page.样式 样式=site_css** -**page = > page.组件装配 组件=home** -**page = > page.主体装配 主体=index** -**page = > page.链接前缀 前缀="/post/"** - -**about = > 网页.页面 标题="关于 · Marqdo 中文站" 壳样式="off"** -**about = > about.引言装配 引言=`关于引言`** -**about = > about.头装配 表=fonts** -**about = > about.样式 样式=site_css** -**about = > about.组件装配 组件=home** - -**article_form = > 网页.表单 表="articles" 动作="插入"** -**article_form = > article_form.字段 字段=article_fields** -**article_form = > article_form.规则 规则=article_rules** - -**new = > 网页.页面 标题="写文章 · Marqdo 中文站" 壳样式="off"** -**new = > new.引言装配 引言=`写文章引言`** -**new = > new.头装配 表=fonts** -**new = > new.样式 样式=site_css** -**new = > new.组件装配 组件=home** -**new = > new.表单装配 id="article" 表单=article_form** - -**desk = > 网页.页面 标题="后台 · Marqdo 中文站" 壳样式="off"** -**desk = > desk.壳HTML 体类="is-desk"** -**desk = > desk.引言装配 引言=`后台引言`** -**desk = > desk.头装配 表=fonts** -**desk = > desk.样式 样式=site_css** -**desk = > desk.组件装配 组件=desk_shell** -**desk = > desk.表单装配 id="article" 表单=article_form** -**desk = > desk.主体装配 主体=index** -**desk = > desk.链接前缀 前缀="/post/"** - -**post = > 网页.页面 标题="文章 · Marqdo 中文站" 壳样式="off"** -**post = > post.引言装配 引言=`文章引言`** -**post = > post.头装配 表=fonts** -**post = > post.样式 样式=site_css** -**post = > post.组件装配 组件=home** -**post = > post.主体装配 主体=detail** -**post = > post.查询条件 条件=by_slug** -**post = > post.详情 详情=True** - -演示账号(用户表声明;宿主会话鉴权,无作者 JS)。 - -`管理员` = - -| 用户名 | 密码 | 角色 | -|--------|------|------| -| admin | demo | admin | - -**app = > 网页.应用 页面=page 数据库=store 后台=False 主机="127.0.0.1" 端口=18082 壳样式="off" 登录回跳="/admin" 登出回跳="/"** -**app = > app.路由 路径="/about" 页面=about** -**app = > app.路由 路径="/new" 页面=new** -**app = > app.路由 路径="/admin" 页面=desk** -**app = > app.路由 路径="/post/{slug}" 页面=post** -**app = > app.鉴权 用户表=`管理员` 会话时长=3600 登录路径="/login" 登录回跳="/admin" 登出回跳="/"** -**app = > app.门禁 路径="/admin" 角色="admin" 匹配="prefix" 拒绝="redirect" 排除="/login"** -> `app`.监听 +我们 **应用 = [绑定实际登录会话](鉴权.绑定(应用=`应用`, 用户=`用户`, 登录路径="/login", 登录返回="/admin", 退出返回="/"))** 和 **应用 = [保护直接访问自定义后台的请求](鉴权.门禁(应用=`应用`, 路径="/admin", 角色="admin", 匹配="prefix", 拒绝="redirect", 排除="/login"))**。 +资源与策略就绪后返回 *[开始实际监听](网页.监听(应用=`应用`))*。 diff --git a/examples/web-site-zh/pages/about.mq.md b/examples/web-site-zh/pages/about.mq.md new file mode 100644 index 0000000..c563761 --- /dev/null +++ b/examples/web-site-zh/pages/about.mq.md @@ -0,0 +1,29 @@ +--- +markup: occlusion +type: web +view: main +route: /about +title: 关于 · Marqdo 中文站 +import: + 布局: ../components/index.mq.md + 引言: ../components/intro.mq.md + 文章: ../components/articles.mq.md + 组件: ext/web/网页/组件/索引.mq.md + 表单: ext/data/表单.mq.md + 表: lib/表.mq.md +--- + +本 Document 显式声明 /about,介绍留在终端 Markdown,框架按职责共享。请求资源继续拥有自己的数据和提交责任。 页面启动函数不初始化数据库或开启另一个监听进程。 + +## main + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 共享框架内的本页内容与请求资源 | + +装配授予 fs.read 以读取终端说明,构造描述仍是纯计算。这份解释页不需要查询或表单,修改一个布局区域应沿导入找到对应子模块,不在本文件重新拼页面壳。 + +结构保持稳定,请求资源观察当前数据与身份。父层决定位置,终端叶子解释内容,职责不因为文件较短就合并回完整原生 HTML。首次阅读本页就应能判断实际路径、内容来源和运行边界。 + +我们 **正文 = [读取本页终端说明](引言.nodes(name="about"))**。 +最后返回 *[选择本页的递归框架](布局.frame(body=`正文`, management=False))*。 diff --git a/examples/web-site-zh/pages/desk.mq.md b/examples/web-site-zh/pages/desk.mq.md new file mode 100644 index 0000000..78326fb --- /dev/null +++ b/examples/web-site-zh/pages/desk.mq.md @@ -0,0 +1,31 @@ +--- +markup: occlusion +type: web +view: main +route: /admin +title: 后台 · Marqdo 中文站 +import: + 布局: ../components/index.mq.md + 引言: ../components/intro.mq.md + 文章: ../components/articles.mq.md + 组件: ext/web/网页/组件/索引.mq.md + 表单: ext/data/表单.mq.md + 表: lib/表.mq.md +--- + +本 Document 显式声明 /admin,介绍留在终端 Markdown,框架按职责共享。服务入口在渲染后台前执行真实 admin 角色门禁。 页面启动函数不初始化数据库或开启另一个监听进程。 + +## main + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 共享框架内的本页内容与请求资源 | + +装配授予 fs.read 以读取终端说明,构造描述仍是纯计算。服务器在请求期间为真实会话准备表单 CSRF 与返回路径,不把启动时令牌写死到页面。缺少挂载资源应保留诊断,不能显示固定成功的空表单。 + +后台保留自己的导航和页脚,不带公共侧栏。它有意共享公共文章提交端点,页面门禁不会让该端点自动私有;公开创建是示例保留的行为。首次阅读本页就应能判断实际路径、内容来源和运行边界。 + +我们 **正文 = [读取本页终端说明](引言.nodes(name="desk"))**。 +我们 **引用 = [引用同一个实际挂载的表单](表单.引用(标识="article"))**、**操作 = [保留当前请求 CSRF 与提交上下文](组件.请求资源(值=`引用`, 槽="article-form"))** 和 **正文 = [说明位于实际操作之前](表.拼接(a=`正文`, b=`操作`))**。 +我们 **记录 = [描述同一份当前文章列表](文章.cards())** 和 **正文 = [保留真实业务记录资源](表.拼接(a=`正文`, b=`记录`))**。 +最后返回 *[选择本页的递归框架](布局.frame(body=`正文`, management=True))*。 diff --git a/examples/web-site-zh/pages/new.mq.md b/examples/web-site-zh/pages/new.mq.md new file mode 100644 index 0000000..e5b9358 --- /dev/null +++ b/examples/web-site-zh/pages/new.mq.md @@ -0,0 +1,30 @@ +--- +markup: occlusion +type: web +view: main +route: /new +title: 写文章 · Marqdo 中文站 +import: + 布局: ../components/index.mq.md + 引言: ../components/intro.mq.md + 文章: ../components/articles.mq.md + 组件: ext/web/网页/组件/索引.mq.md + 表单: ext/data/表单.mq.md + 表: lib/表.mq.md +--- + +本 Document 显式声明 /new,介绍留在终端 Markdown,框架按职责共享。请求资源继续拥有自己的数据和提交责任。 页面启动函数不初始化数据库或开启另一个监听进程。 + +## main + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 共享框架内的本页内容与请求资源 | + +装配授予 fs.read 以读取终端说明,构造描述仍是纯计算。服务器在请求期间为真实会话准备表单 CSRF 与返回路径,不把启动时令牌写死到页面。缺少挂载资源应保留诊断,不能显示固定成功的空表单。 + +结构保持稳定,请求资源观察当前数据与身份。父层决定位置,终端叶子解释内容,职责不因为文件较短就合并回完整原生 HTML。首次阅读本页就应能判断实际路径、内容来源和运行边界。 + +我们 **正文 = [读取本页终端说明](引言.nodes(name="new"))**。 +我们 **引用 = [引用同一个实际挂载的表单](表单.引用(标识="article"))**、**操作 = [保留当前请求 CSRF 与提交上下文](组件.请求资源(值=`引用`, 槽="article-form"))** 和 **正文 = [说明位于实际操作之前](表.拼接(a=`正文`, b=`操作`))**。 +最后返回 *[选择本页的递归框架](布局.frame(body=`正文`, management=False))*。 diff --git a/examples/web-site-zh/pages/post.mq.md b/examples/web-site-zh/pages/post.mq.md new file mode 100644 index 0000000..9724049 --- /dev/null +++ b/examples/web-site-zh/pages/post.mq.md @@ -0,0 +1,30 @@ +--- +markup: occlusion +type: web +view: main +route: /post/{slug} +title: 文章 · Marqdo 中文站 +import: + 布局: ../components/index.mq.md + 引言: ../components/intro.mq.md + 文章: ../components/articles.mq.md + 组件: ext/web/网页/组件/索引.mq.md + 表单: ext/data/表单.mq.md + 表: lib/表.mq.md +--- + +本 Document 显式声明 /post/{slug},介绍留在终端 Markdown,框架按职责共享。请求资源继续拥有自己的数据和提交责任。 页面启动函数不初始化数据库或开启另一个监听进程。 + +## main + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 共享框架内的本页内容与请求资源 | + +装配授予 fs.read 以读取终端说明,构造描述仍是纯计算。路径捕获在请求期间选择当前数据库记录,查询字符串不能替换短链。详情使用完整 Markdown 正文,摘要只属于列表,空正文也不应被摘要冒充。 + +结构保持稳定,请求资源观察当前数据与身份。父层决定位置,终端叶子解释内容,职责不因为文件较短就合并回完整原生 HTML。首次阅读本页就应能判断实际路径、内容来源和运行边界。 + +我们 **正文 = [读取本页终端说明](引言.nodes(name="post"))**。 +我们 **记录 = [描述当前短链的完整正文](文章.detail())** 和 **正文 = [保留真实业务记录资源](表.拼接(a=`正文`, b=`记录`))**。 +最后返回 *[选择本页的递归框架](布局.frame(body=`正文`, management=False))*。 diff --git a/examples/web-site-zh/styles/index.mq.md b/examples/web-site-zh/styles/index.mq.md new file mode 100644 index 0000000..4cd16a0 --- /dev/null +++ b/examples/web-site-zh/styles/index.mq.md @@ -0,0 +1,97 @@ +--- +markup: occlusion +title: 递归 View 的文学主题入口 +import: + document: lib/document.mq.md + 网页: ext/web/网页.mq.md + table: lib/table.mq.md + text: lib/text.mq.md +--- + +先读本入口再修改呈现。shell.tables.md 保留每条原始声明,shell.mq.md 仍能编译原来的 CSS。本入口只把选择器投影到明确的 View 树,恢复旧装配附着的命名属性,再加入 view.tables.md 中有界的包装层几何。颜色、属性值、媒体条件、粒子与关键帧正文都来自原始数据,不用简化主题掩盖结构迁移。 + +## _selector + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| selector | text | 必填 | 原主题中由作者控制的单个选择器 | +| mappings | list | 必填 | 从 view.tables.md 读取的明确 old/new 地址行 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 映射到当前递归框架的等效选择器 | + +使用`selector`和`mappings`。旧 body 的侧栏与后台状态已移入 site-layout,主体改为 section,避免在既有文档 main 中再嵌套 main。原来的分类、主标题、徽章容器和阅读步骤分别对应终端 Markdown 的引用、标题、无序与有序列表。 + +文档背景、根令牌、选中文字、重置与关键帧保持全局,局部选择器增加本站作用域,避免基础 View 默认值覆盖明确主题。这是已知组件树的固定迁移,不是通用 CSS 解析器,也不接收访客的重写规则。调用者每个区域只读取一次映射,再显式传给本纯函数,避免逐条声明重复文件读取。 + +- [按本工程明确的结构地址映射处理](for mappings as mapping) + 我们 **selector = [只替换已知的选择器地址](text.replace(text=`selector`, old=access(mapping, "old"), new=access(mapping, "new")))**. +1. `selector` == "*" or `selector` == "::selection" or text.starts_with(text=`selector`, prefix="body") or text.starts_with(text=`selector`, prefix="html") or text.starts_with(text=`selector`, prefix=":root") or text.starts_with(text=`selector`, prefix="@") + 最后返回 *selector* ,使文档规则与关键帧保持原有作用域。 +1. text.starts_with(text=`selector`, prefix=".site-layout") + 最后返回 *[只为布局状态增加一次作用域](".mq-document " + selector)*. +最后返回 *[将区域选择器限定在本站框架内](".mq-document .site-layout " + selector)*. + +## _table + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | text | 必填 | 原始 vars、motion、layout、responsive、chrome 或 widgets 章节 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 仅选择器字段变化的原始声明行 | + +使用`name`,从站点根授权 fs.read。原生 Markdown 读取保留声明和字面类型,列转行后保持顺序。每条记录的属性、值、可选媒体与原位置都不变,只有选择器经过上面的固定映射;不可变更新不会污染原来的主题表。 + +本函数不编译或写 CSS。保留可调用的投影行,让验收能逐项核对属性、值和媒体条件,再观察浏览器结果。缺失章节、列长不齐或不支持的字面量都应保留真实诊断,不得静默丢弃样式。令牌和关键帧地址自身也保持不变,不能只比较颜色却删掉动画。 + +我们 **mappings = [读取明确的结构迁移表](document.read_table(path="styles/view.tables.md", title="selectors"))**. +我们 **columns = [读取未改变的原始声明叶子](document.read_table(path="styles/shell.tables.md", title=`name`))** 和 **rows = [逐行保留原有声明](table.from_columns(columns=`columns`))** 和 **projected = [开始有序的选择器投影](table.empty_list())**. +- [在原位置保留每条原始声明](for rows as row) + 我们 **selector = [只映射这一行的结构地址](_selector(selector=access(row, "选择器"), mappings=`mappings`))** 和 **record = [保持其余声明字段不变](table.put(in=`row`, at="选择器", value=`selector`))** 和 **projected = [保留原始属性与值](table.append(list=`projected`, item=`record`))**. +最后返回 *projected* ,供实际编译或独立比较。 + +## _property + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | text | 必填 | 原来的命名属性/值章节 | +| selector | text | 必填 | 新树中明确语义目标;名称不含开头的点 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 原始属性在明确新目标上的实际编译结果 | + +使用`name`与`selector`,授予 fs.read 与 plugin。旧装配曾把这些属性附到生成的字段,现在同一声明直接选择导航、侧栏/页脚、原生卡片和终端 Markdown 元素,值不改变,也不由用户内容推断。 + +目标由主题入口控制,以 mq-document 开头,原生编译器补上类选择器的点。明确目标让旧属性表仍有用,同时不恢复已移除的页面绑定方言。返回只是文本,保存路径和原子写入由服务入口负责;编译不等于文件已经挂载或浏览器已经加载。 + +我们 **properties = [读取原来的命名属性声明](document.read_table(path="styles/shell.tables.md", title=`name`))**. +最后返回 *[编译明确的语义目标](网页.编译样式(名称=`selector`, 属性=`properties`))*. + +## css + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 保留原始值、明确映射与包装层几何的完整 View 主题 | + +从站点文件根授予 fs.read 与 plugin。令牌和关键帧保持原顺序,随后编译布局、响应断点、引言与控件;命名属性恢复旧装配单独附着的字体和区域外观。不会以替代色板或删减主题提高通过率。 + +最后的几何表只处理运行时包装:移除基础预览的固定宽度和字体默认,让导航资源的原生语义子块参与已有命名网格,并保留公共侧栏与后台状态。Markdown 项目符号成为原来的徽章组,首个解释段落使用原有导语属性,正文无需隐藏的 HTML 模板。 + +编译不会写样式表,也不发放浏览器验收结果。服务入口在发现页面之前原生保存确切文件,再测试实际计算颜色、字体尺寸、宽屏侧栏、窄屏堆叠、表单与后台。选择器失效时修正映射,不能删除视觉能力。各区域顺序和命名属性目标都在相邻数据叶子中可直接阅读;缺少任何章节应停止,而不是退回旧生成文件。生成产物可以重建,原声明与迁移表才是编辑入口;不要手改生成 CSS 后误认为源码已经修复。样式变化仍需宽屏和窄屏两个方向的实际观察。 + +我们 **areas = [读取保留的主题区域顺序](document.read_table(path="styles/view.tables.md", title="areas"))**. + +我们 **parts = [开始实际有序的主题编译](table.empty_list())**. +- [编译每个原始主题区域](for areas as name) + 我们 **rows = [保留全部原始值与媒体条件](_table(name=`name`))** 和 **compiled = [编译实际投影后的声明](网页.编译样式(名称=`name`, 属性=`rows`))** 和 **parts = [保留原来的级联顺序](table.append(list=`parts`, item=`compiled`))**. + +我们 **properties = [读取实际命名属性目标](document.read_table(path="styles/view.tables.md", title="properties"))**. + +- [恢复每组原来附着的命名属性](for properties as property) + 我们 **compiled = [编译明确的语义选择器](_property(name=access(property, "name"), selector=access(property, "selector")))** 和 **parts = [保留真实的命名属性组](table.append(list=`parts`, item=`compiled`))**. +我们 **geometry = [读取有界的 View 包装层适配](document.read_table(path="styles/view.tables.md", title="geometry"))** 和 **compiled = [编译原生几何适配](网页.编译样式(名称="view", 属性=`geometry`))** 和 **parts = [以明确的包装规则结束](table.append(list=`parts`, item=`compiled`))**. +最后返回 *[按顺序保留实际编译的各段](text.str_join(xs=`parts`, sep=""))*. diff --git a/examples/web-site-zh/styles/shell.mq.md b/examples/web-site-zh/styles/shell.mq.md index 0342f1a..559364b 100644 --- a/examples/web-site-zh/styles/shell.mq.md +++ b/examples/web-site-zh/styles/shell.mq.md @@ -1,677 +1,277 @@ --- markup: occlusion -title: styles/shell -description: >- - Literary dark theme for examples/web-site — ink / wine / gold after the - anlian.cyou Zhang Ailing topic. GFM tables only; no author .css. +title: 原始文学主题声明的读取与比较 import: + document: lib/document.mq.md web: ext/web/web.mq.md + table: lib/table.mq.md text: lib/text.mq.md --- -Authors style the site with **GFM tables** only. App pages use `shell_css=off` -so host defaults do not fight this theme. Palette mirrors -[海上花开](https://www.anlian.cyou/topics/author-zhangailing/): night ink, -wine, cold gold, serif display. +本文件保留原始数据读取与 CSS 编译,用于比较迁移前的声明。当前站点从 styles/index.mq.md 编译 View 映射;不要把本文件输出误当成新树已经适配。数据叶子中每条原始声明保持可阅读、可独立调用。 ## vars -`vars` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | -| 选择器 | 属性 | 值 | -|--------|------|-----| -| :root | --ink | #0a0809 | -| :root | --ink-lift | #141012 | -| :root | --wine | #6b1e3a | -| :root | --wine-soft | rgba(107,30,58,0.35) | -| :root | --gold | #d4af37 | -| :root | --gold-dim | rgba(212,175,55,0.45) | -| :root | --gold-soft | rgba(212,175,55,0.12) | -| :root | --paper | rgba(255,248,240,0.92) | -| :root | --paper-dim | rgba(255,248,240,0.72) | -| :root | --paper-faint | rgba(255,248,240,0.48) | -| :root | --glass | rgba(20,12,18,0.72) | -| :root | --glass-strong | rgba(20,12,18,0.88) | -| :root | --border | rgba(212,175,55,0.22) | -| :root | --border-soft | rgba(212,175,55,0.12) | -| :root | --danger | #e8a0a8 | -| :root | --radius | 4px | -| :root | --radius-sm | 2px | -| :root | --space-2 | 8px | -| :root | --space-3 | 12px | -| :root | --space-4 | 16px | -| :root | --space-5 | 20px | -| :root | --space-6 | 24px | -| :root | --space-8 | 32px | -| :root | --text | 16px | -| :root | --leading | "1.75" | -| :root | --shadow | "0 24px 80px rgba(0,0,0,.55), inset 0 1px 0 rgba(255,255,255,.06)" | -| :root | --shadow-card | "0 12px 40px rgba(107,30,58,.35)" | -| :root | --ring | "0 0 0 2px rgba(212,175,55,.35)" | -| :root | --serif | "'Noto Serif SC', 'Source Serif 4', Georgia, serif" | -| :root | --sans | "'Noto Sans SC', 'IBM Plex Sans', system-ui, sans-serif" | -| :root | --display | "'Great Vibes', 'Allura', cursive" | -| :root | --mono | "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace" | -| ::selection | background | rgba(212,175,55,0.35) | -| ::selection | color | var(--paper) | +整站色板、字体、间距与阴影令牌。 -*`vars`* +使用这些自定义属性的规则应在令牌之后编译。选中文字颜色与 :root 一样保持全局,不应被框架映射限制在某张卡片中。修改值会影响整站,需核对实际 CSS 与浏览器颜色,不能只在局部重命名引用。 + +从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 + +读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="vars"))*. ## motion -`motion` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | -| 选择器 | 属性 | 值 | -|--------|------|-----| -| @keyframes rise 0% | opacity | "0" | -| @keyframes rise 0% | transform | translateY(14px) | -| @keyframes rise 100% | opacity | "1" | -| @keyframes rise 100% | transform | translateY(0) | -| @keyframes float 0% | transform | translateY(0) | -| @keyframes float 0% | opacity | "0.7" | -| @keyframes float 50% | transform | translateY(6px) | -| @keyframes float 50% | opacity | "1" | -| @keyframes float 100% | transform | translateY(0) | -| @keyframes float 100% | opacity | "0.7" | -| @keyframes goldPulse 0% | text-shadow | "0 0 24px rgba(212,175,55,.2)" | -| @keyframes goldPulse 50% | text-shadow | "0 0 48px rgba(212,175,55,.45)" | -| @keyframes goldPulse 100% | text-shadow | "0 0 24px rgba(212,175,55,.2)" | -| @keyframes particleDrift 0% | transform | translate3d(0,0,0) | -| @keyframes particleDrift 50% | transform | translate3d(-2.5vw, 1.5vh, 0) | -| @keyframes particleDrift 100% | transform | translate3d(0,0,0) | -| @keyframes particleDrift2 0% | transform | translate3d(0,0,0) | -| @keyframes particleDrift2 50% | transform | translate3d(2vw, -2vh, 0) | -| @keyframes particleDrift2 100% | transform | translate3d(0,0,0) | -| @keyframes nebulaPulse 0% | opacity | "0.55" | -| @keyframes nebulaPulse 50% | opacity | "0.9" | -| @keyframes nebulaPulse 100% | opacity | "0.55" | +原有入场、漂浮、粒子与辉光关键帧。 -*`motion`* +关键帧地址、属性和值保持全局及原顺序,时长仍归使用它的规则。读到数据不会启动动画,浏览器加载编译主题后才应用。View 投影不能给这些地址加组件前缀,也不能为了静态截图删除运动能力。 + +从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 + +读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="motion"))*. ## layout -`layout` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | -| 选择器 | 属性 | 值 | -|--------|------|-----| -| * | box-sizing | border-box | -| html | scroll-behavior | smooth | -| html | -webkit-text-size-adjust | 100% | -| body | margin | "0" | -| body | min-height | 100vh | -| body | font-family | var(--sans) | -| body | font-weight | "400" | -| body | font-size | var(--text) | -| body | line-height | var(--leading) | -| body | color | var(--paper) | -| body | background | var(--ink) | -| body | background-image | "radial-gradient(ellipse 90% 55% at 50% -15%, rgba(107,30,58,.5), transparent 58%), radial-gradient(ellipse 55% 45% at 92% 75%, rgba(212,175,55,.14), transparent 55%), radial-gradient(ellipse 40% 35% at 8% 70%, rgba(107,30,58,.22), transparent 60%), linear-gradient(180deg, #0a0809 0%, #120c10 45%, #0a0809 100%)" | -| body | background-attachment | fixed | -| body | display | grid | -| body | grid-template-rows | "auto 1fr auto" | -| body | -webkit-font-smoothing | antialiased | -| body | position | relative | -| body | overflow-x | hidden | -| body::before | content | '""' | -| body::before | position | fixed | -| body::before | inset | "0" | -| body::before | z-index | "1" | -| body::before | pointer-events | none | -| body::before | opacity | "0.1" | -| body::before | background-image | "url(\"data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E\")" | -| html::before | content | '""' | -| html::before | position | fixed | -| html::before | inset | "0" | -| html::before | z-index | "0" | -| html::before | pointer-events | none | -| html::before | background-image | "radial-gradient(ellipse 50% 40% at 15% 30%, rgba(107,30,58,.35), transparent 70%), radial-gradient(ellipse 45% 35% at 85% 60%, rgba(212,175,55,.12), transparent 65%), radial-gradient(ellipse 40% 30% at 50% 90%, rgba(107,30,58,.25), transparent 70%)" | -| html::before | animation | "nebulaPulse 12s ease-in-out infinite" | -| body::after | content | '""' | -| body::after | position | fixed | -| body::after | top | "0" | -| body::after | left | "0" | -| body::after | width | "2px" | -| body::after | height | "2px" | -| body::after | z-index | "2" | -| body::after | pointer-events | none | -| body::after | border-radius | 50% | -| body::after | background | transparent | -| body::after | box-shadow | "82vw 15vh 0px 0px rgba(212,175,55,0.55),29vw 18vh 0px 1px rgba(212,175,55,0.25),95vw 70vh 1px 0px rgba(212,175,55,0.55),4vw 12vh 0px 1px rgba(212,175,55,0.35),78vw 4vh 0px 1px rgba(245,230,200,0.5),84vw 90vh 1px 0px rgba(245,230,200,0.5),58vw 76vh 0px 0px rgba(255,248,240,0.4),90vw 55vh 0px 0px rgba(255,248,240,0.4),28vw 98vh 0px 0px rgba(255,248,240,0.4),49vw 13vh 0px 1px rgba(255,248,240,0.4),34vw 6vh 1px 1px rgba(212,175,55,0.25),16vw 49vh 0px 1px rgba(212,175,55,0.55),80vw 47vh 0px 1px rgba(245,230,200,0.5),9vw 6vh 0px 0px rgba(212,175,55,0.25),11vw 30vh 1px 0px rgba(212,175,55,0.55),59vw 82vh 0px 0px rgba(255,248,240,0.4),46vw 27vh 0px 1px rgba(212,175,55,0.25),88vw 83vh 0px 1px rgba(212,175,55,0.55),94vw 32vh 1px 0px rgba(212,175,55,0.35),35vw 82vh 0px 1px rgba(212,175,55,0.25),42vw 99vh 0px 0px rgba(212,175,55,0.55),41vw 52vh 0px 0px rgba(255,248,240,0.4),73vw 92vh 0px 1px rgba(255,248,240,0.4),64vw 51vh 1px 0px rgba(212,175,55,0.25),34vw 18vh 0px 1px rgba(212,175,55,0.35),75vw 55vh 1px 0px rgba(245,230,200,0.5),29vw 18vh 1px 0px rgba(245,230,200,0.5),97vw 7vh 0px 1px rgba(212,175,55,0.55),21vw 88vh 0px 0px rgba(107,30,58,0.45),49vw 77vh 0px 1px rgba(107,30,58,0.45),2vw 88vh 0px 1px rgba(212,175,55,0.25),69vw 97vh 0px 0px rgba(255,248,240,0.4),38vw 56vh 1px 0px rgba(212,175,55,0.35),93vw 93vh 0px 1px rgba(255,248,240,0.4),14vw 81vh 0px 0px rgba(255,248,240,0.4),48vw 98vh 0px 1px rgba(212,175,55,0.35),42vw 63vh 0px 0px rgba(212,175,55,0.55),40vw 31vh 0px 1px rgba(212,175,55,0.55),11vw 11vh 1px 0px rgba(212,175,55,0.25),98vw 69vh 0px 1px rgba(212,175,55,0.35),61vw 71vh 0px 1px rgba(212,175,55,0.35),78vw 55vh 0px 1px rgba(212,175,55,0.35),40vw 52vh 0px 0px rgba(212,175,55,0.25),67vw 58vh 0px 0px rgba(212,175,55,0.55),9vw 44vh 0px 1px rgba(212,175,55,0.55),29vw 1vh 0px 0px rgba(212,175,55,0.55),9vw 5vh 0px 1px rgba(255,248,240,0.4),31vw 36vh 1px 0px rgba(212,175,55,0.25),70vw 17vh 1px 0px rgba(212,175,55,0.25),61vw 53vh 0px 0px rgba(212,175,55,0.35),85vw 56vh 1px 0px rgba(255,248,240,0.4),60vw 94vh 0px 0px rgba(212,175,55,0.55),52vw 94vh 0px 0px rgba(255,248,240,0.4),25vw 25vh 1px 0px rgba(245,230,200,0.5),55vw 24vh 1px 0px rgba(255,248,240,0.4),10vw 57vh 0px 0px rgba(245,230,200,0.5),84vw 70vh 0px 0px rgba(212,175,55,0.55),22vw 53vh 1px 0px rgba(107,30,58,0.45),52vw 8vh 1px 0px rgba(212,175,55,0.35),50vw 34vh 0px 0px rgba(107,30,58,0.45),90vw 94vh 1px 0px rgba(245,230,200,0.5),25vw 38vh 0px 1px rgba(212,175,55,0.35),95vw 70vh 0px 0px rgba(212,175,55,0.55),7vw 75vh 0px 0px rgba(107,30,58,0.45),66vw 11vh 0px 1px rgba(212,175,55,0.35),9vw 87vh 1px 0px rgba(212,175,55,0.35),73vw 32vh 0px 1px rgba(245,230,200,0.5),11vw 54vh 0px 0px rgba(212,175,55,0.25),27vw 86vh 0px 0px rgba(212,175,55,0.25),34vw 51vh 0px 0px rgba(212,175,55,0.35),41vw 97vh 0px 0px rgba(212,175,55,0.55),80vw 73vh 0px 1px rgba(212,175,55,0.55)" | -| body::after | animation | "particleDrift 48s ease-in-out infinite" | -| html::after | content | '""' | -| html::after | position | fixed | -| html::after | top | "0" | -| html::after | left | "0" | -| html::after | width | "1px" | -| html::after | height | "1px" | -| html::after | z-index | "2" | -| html::after | pointer-events | none | -| html::after | border-radius | 50% | -| html::after | background | transparent | -| html::after | box-shadow | "28vw 65vh 0 0 rgba(255,248,240,0.25),17vw 45vh 0 0 rgba(212,175,55,0.3),32vw 48vh 0 0 rgba(255,248,240,0.25),21vw 57vh 0 0 rgba(107,30,58,0.3),91vw 39vh 0 0 rgba(107,30,58,0.3),84vw 68vh 0 0 rgba(212,175,55,0.3),86vw 71vh 0 0 rgba(255,248,240,0.25),85vw 14vh 0 0 rgba(212,175,55,0.3),34vw 15vh 0 0 rgba(212,175,55,0.3),96vw 71vh 0 0 rgba(212,175,55,0.3),35vw 37vh 0 0 rgba(107,30,58,0.3),27vw 92vh 0 0 rgba(255,248,240,0.25),27vw 88vh 0 0 rgba(107,30,58,0.3),34vw 65vh 0 0 rgba(255,248,240,0.25),33vw 7vh 0 0 rgba(212,175,55,0.3),82vw 55vh 0 0 rgba(255,248,240,0.25),6vw 1vh 0 0 rgba(255,248,240,0.25),99vw 17vh 0 0 rgba(107,30,58,0.3),34vw 21vh 0 0 rgba(107,30,58,0.3),57vw 71vh 0 0 rgba(107,30,58,0.3),55vw 72vh 0 0 rgba(212,175,55,0.3),15vw 10vh 0 0 rgba(107,30,58,0.3),20vw 70vh 0 0 rgba(212,175,55,0.3),48vw 75vh 0 0 rgba(107,30,58,0.3),19vw 56vh 0 0 rgba(212,175,55,0.3),6vw 40vh 0 0 rgba(255,248,240,0.25),6vw 46vh 0 0 rgba(212,175,55,0.3),88vw 32vh 0 0 rgba(107,30,58,0.3),14vw 46vh 0 0 rgba(107,30,58,0.3),53vw 80vh 0 0 rgba(107,30,58,0.3),20vw 31vh 0 0 rgba(212,175,55,0.3),23vw 53vh 0 0 rgba(212,175,55,0.3),23vw 95vh 0 0 rgba(255,248,240,0.25),53vw 86vh 0 0 rgba(107,30,58,0.3),32vw 35vh 0 0 rgba(212,175,55,0.3),90vw 14vh 0 0 rgba(255,248,240,0.25),5vw 61vh 0 0 rgba(212,175,55,0.3),26vw 59vh 0 0 rgba(255,248,240,0.25),40vw 30vh 0 0 rgba(212,175,55,0.3),4vw 85vh 0 0 rgba(212,175,55,0.3),52vw 43vh 0 0 rgba(255,248,240,0.25),9vw 99vh 0 0 rgba(255,248,240,0.25),45vw 83vh 0 0 rgba(107,30,58,0.3),52vw 87vh 0 0 rgba(107,30,58,0.3),43vw 4vh 0 0 rgba(212,175,55,0.3),34vw 23vh 0 0 rgba(107,30,58,0.3),34vw 5vh 0 0 rgba(212,175,55,0.3),77vw 56vh 0 0 rgba(255,248,240,0.25)" | -| html::after | animation | "particleDrift2 64s ease-in-out infinite" | -| body.has-sidebar | grid-template-columns | "14rem minmax(0, 1fr)" | -| body.has-sidebar | grid-template-areas | '"top top" "side main" "foot foot"' | -| body.no-sidebar | grid-template-areas | '"top" "main" "foot"' | -| body.layout-stacked | grid-template-areas | '"top" "main" "foot"' | -| body.is-desk | grid-template-areas | '"top" "main" "foot"' | -| header.topnav | grid-area | top | -| aside.side | grid-area | side | -| main.main | grid-area | main | -| footer.foot | grid-area | foot | -| header.topnav | position | relative | -| header.topnav | z-index | "20" | -| aside.side | position | relative | -| aside.side | z-index | "10" | -| main.main | position | relative | -| main.main | z-index | "10" | -| footer.foot | position | relative | -| footer.foot | z-index | "10" | -| main.main | width | "100%" | -| main.main | max-width | "min(78rem, 100%)" | -| main.main | padding | "var(--space-8) var(--space-6) 4rem" | -| main.main | animation | "rise .8s cubic-bezier(.22,1,.36,1) both" | -| a | color | var(--gold) | -| a | text-decoration | none | -| a | transition | color 0.25s ease | -| a:hover | color | #f5e6c8 | -| code | font-family | var(--mono) | -| code | font-size | "0.82em" | -| code | font-weight | "400" | -| code | background | rgba(0,0,0,0.35) | -| code | border | 1px solid var(--border-soft) | -| code | padding | "0.12em 0.45em" | -| code | border-radius | var(--radius-sm) | -| code | color | var(--gold) | +文档背景、排版与原有区域网格声明。 -*`layout`* +旧 body 状态描述过去的页面壳,当前样式入口只把已知地址映射到明确 site-layout 区域,属性值不变。背景和粒子层继续属于文档全局,任何修改都应对照真实宽窄屏几何,而不是只比较声明数量。 + +从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 + +读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="layout"))*. ## responsive -`responsive` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | -| 媒体 | 选择器 | 属性 | 值 | -|------|--------|------|-----| -| (max-width: 860px) | body.has-sidebar | grid-template-columns | 1fr | -| (max-width: 860px) | body.has-sidebar | grid-template-areas | '"top" "main" "side" "foot"' | -| (max-width: 860px) | aside.side | border-right | "0" | -| (max-width: 860px) | aside.side | border-top | 1px solid var(--border-soft) | -| (max-width: 860px) | main.main | padding | "var(--space-6) var(--space-4) var(--space-8)" | -| (max-width: 860px) | .content.cards | grid-template-columns | 1fr | -| (max-width: 860px) | .site-form form | grid-template-columns | 1fr | -| (max-width: 860px) | .site-form label:nth-child(1) | grid-column | "1 / -1" | -| (max-width: 860px) | .site-form label:nth-child(2) | grid-column | "1 / -1" | -| (max-width: 860px) | header.topnav | padding | "0.85rem var(--space-4)" | -| (max-width: 860px) | .intro_title | font-size | "2.4rem" | -| (prefers-reduced-motion: reduce) | main.main | animation | none | -| (prefers-reduced-motion: reduce) | .kicker | animation | none | -| (prefers-reduced-motion: reduce) | article.card | transition | none | -| (prefers-reduced-motion: reduce) | body::after | animation | none | -| (prefers-reduced-motion: reduce) | html::after | animation | none | -| (prefers-reduced-motion: reduce) | html::before | animation | none | +原始媒体条件及减少动画偏好的规则。 -*`responsive`* +媒体文本保留为独立列。宽度条件收拢公共网格并调整留白,减少动画偏好关闭指定动画而非删除关键帧。核对时保留行顺序、媒体和值,不能仅因为 CSS 中仍出现选择器名就认定断点有效。 + +从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 + +读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="responsive"))*. ## topnav -`topnav` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | -| 属性 | 值 | -|------|-----| -| position | sticky | -| top | "0" | -| z-index | "40" | -| display | flex | -| align-items | center | -| justify-content | flex-start | -| gap | var(--space-4) | -| padding | "1rem var(--space-6)" | -| background | "linear-gradient(180deg, rgba(10,8,9,.92) 0%, rgba(10,8,9,.55) 70%, transparent 100%)" | -| backdrop-filter | blur(10px) | -| -webkit-backdrop-filter | blur(10px) | -| border-bottom | 1px solid var(--border-soft) | +顶部导航外观的命名属性和值。 -*`topnav`* +原有吸顶、渐变、模糊、间距与分隔线继续作用于原生 topnav 类。目标链接与实际会话条件归导航资源,属性表不能认证用户或注册路由。编译也不意味着样式文件已保存或挂载,服务入口负责这些后续步骤。 + +从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 + +读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="topnav"))*. ## side_panel -`side_panel` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | -| 属性 | 值 | -|------|-----| -| background | "rgba(10,8,9,.55)" | -| padding | "var(--space-6) var(--space-4)" | -| border-right | 1px solid var(--border-soft) | +公共侧栏外观的命名属性和值。 -*`side_panel`* +侧栏背景、留白与分隔线区分任务入口和正文,外部网格位置仍归父框架,后台有意不带该区域。这里不维护另一份链接或会话判断。修改外观后应确认窄屏仍在正文之后显示,不能用隐藏侧栏掩盖布局错误。 + +从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 + +读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="side_panel"))*. ## footer -`footer` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | -| 属性 | 值 | -|------|-----| -| color | var(--paper-faint) | -| font-size | "0.8rem" | -| letter-spacing | "0.08em" | -| padding | "var(--space-5) var(--space-6)" | -| border-top | 1px solid var(--border-soft) | -| background | "rgba(10,8,9,.75)" | +结束区域外观的命名属性和值。 -*`footer`* +颜色、字号、间距、边框与背景保留原站定义。Markdown 叶子拥有真实链接,本表既不创建目的地也不执行退出。公共与后台页脚可共享相同外观,内容仍分别维护,父层继续决定位置。 + +从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 + +读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="footer"))*. ## card_title -`card_title` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | -| 属性 | 值 | -|------|-----| -| font-family | var(--serif) | -| font-size | "1.15rem" | -| font-weight | "600" | -| margin | "0 0 var(--space-2)" | -| color | var(--gold) | -| letter-spacing | "0.02em" | -| line-height | "1.35" | +文章卡片标题的命名排版属性。 -*`card_title`* +当前查询渲染器转义文章标题并保留原生 h2,View 主题直接选择该结构,不恢复旧 front/back 绑定。读取不查询文章、不截断标题或修改持久数据;应结合真实卡片确认属性到达实际标题。 + +从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 + +读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="card_title"))*. ## card_body -`card_body` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | -| 属性 | 值 | -|------|-----| -| color | var(--paper-dim) | -| margin | "0" | -| line-height | "1.65" | -| font-size | "0.9rem" | -| font-weight | "400" | -| display | "-webkit-box" | -| -webkit-box-orient | vertical | -| -webkit-line-clamp | "3" | -| overflow | hidden | +卡片摘要的命名排版属性。 -*`card_body`* +摘要来自当前查询,完整 Markdown 正文仍留给详情。本表只改变外观,不选择或替换内容。选择器调整后要同时验证转义摘要和完整正文的独立行为,不能用摘要冒充缺失的正文。 + +从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 + +读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="card_body"))*. ## chrome -Panel + claim/steps group layout (field look comes from named bind styles). +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | -`chrome` = +原始引言面板、徽章容器、阅读步骤和全文规则。 -| 选择器 | 属性 | 值 | -|--------|------|-----| -| .main-intro | background | var(--glass) | -| .main-intro | border | 1px solid var(--border) | -| .main-intro | border-radius | var(--radius) | -| .main-intro | padding | "2.25rem 1.75rem 1.85rem" | -| .main-intro | box-shadow | var(--shadow) | -| .main-intro | backdrop-filter | blur(16px) | -| .main-intro | -webkit-backdrop-filter | blur(16px) | -| .main-intro | margin-bottom | var(--space-8) | -| .main-intro > .claim | display | flex | -| .main-intro > .claim | flex-wrap | wrap | -| .main-intro > .claim | gap | var(--space-2) | -| .main-intro > .claim | margin | "0 0 var(--space-6)" | -| .main-intro > .steps | margin | "0" | -| .main-intro > .steps | padding | "var(--space-5) var(--space-5) var(--space-5) 1.5rem" | -| .main-intro > .steps | color | var(--paper-dim) | -| .main-intro > .steps | background | "rgba(0,0,0,.35)" | -| .main-intro > .steps | border | 1px solid var(--border-soft) | -| .main-intro > .steps | border-left | 2px solid var(--gold-dim) | -| .main-intro > .steps | border-radius | var(--radius) | -| .main-intro > .steps | font-size | "0.95rem" | -| .main-intro > .steps | letter-spacing | "0.02em" | -| .main-intro > .steps a | color | var(--gold) | -| .main-intro > .steps a | font-weight | "500" | -| .main-intro > .steps a:hover | color | #f5e6c8 | -| .article | background | var(--glass) | -| .article | border | 1px solid var(--border) | -| .article | border-radius | var(--radius) | -| .article | padding | "2rem 1.75rem" | -| .article | box-shadow | var(--shadow) | -| .article | backdrop-filter | blur(16px) | -| .article | -webkit-backdrop-filter | blur(16px) | -| .article-title | font-family | var(--serif) | -| .article-title | font-size | "clamp(1.75rem, 4vw, 2.35rem)" | -| .article-title | font-weight | "600" | -| .article-title | color | var(--gold) | -| .article-title | letter-spacing | "0.04em" | -| .article-title | margin | "0 0 var(--space-5)" | -| .article-title | line-height | "1.25" | -| .article-body | color | var(--paper-dim) | -| .article-body | font-family | var(--sans) | -| .article-body | font-size | "1.02rem" | -| .article-body | line-height | "1.85" | -| .article-body.md p | margin | "0 0 1.1rem" | -| .article-body.md a | color | var(--gold) | -| article.card | cursor | pointer | -| a.card-link | color | inherit | -| a.card-link | text-decoration | none | -| a.card-link:hover | color | inherit | +当前引言是终端 Markdown,因此映射选择真实标题、项目符号与编号列表;文章规则继续选择原生详情结构。保留明确映射与原值,不应为恢复旧选择器而把整段内容藏回作者 HTML。 -*`chrome`* +从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 + +读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="chrome"))*. ## kicker -`kicker` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | -| 属性 | 值 | -|------|-----| -| letter-spacing | "0.32em" | -| text-transform | uppercase | -| font-size | "0.72rem" | -| color | var(--gold-dim) | -| margin | "0 0 var(--space-4)" | -| font-weight | "400" | -| font-family | var(--sans) | -| animation | "float 2.8s ease-in-out infinite" | +引言分类标签的命名排版属性。 -*`kicker`* +字距、颜色、小字号和漂浮动画选择分类所用的 Markdown 引用块,分类文字仍是内容叶子中直接可读的一行。编译这些属性不会创建文字或下载字体,加载与实际呈现需另外观察。 + +从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 + +读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="kicker"))*. ## intro_title -`intro_title` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | -| 属性 | 值 | -|------|-----| -| font-family | var(--display) | -| font-size | "clamp(3rem, 10vw, 4.8rem)" | -| font-weight | "400" | -| line-height | "1.15" | -| letter-spacing | "0.04em" | -| margin | "0 0 var(--space-4)" | -| color | transparent | -| background | "linear-gradient(135deg, #f5e6c8 0%, var(--gold) 42%, var(--wine) 100%)" | -| -webkit-background-clip | text | -| background-clip | text | -| animation | "goldPulse 4.5s ease-in-out infinite" | +引言主标题的命名字体与响应式属性。 -*`intro_title`* +保留展示字体、响应字号、渐变文字与辉光动画,View 主题选择真实 Markdown h1,避免把字号施加到包装层后又被浏览器标题倍乘。验收检查计算字体和尺寸,读到属性不能证明渲染已正确。 + +从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 + +读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="intro_title"))*. ## lede -`lede` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | -| 属性 | 值 | -|------|-----| -| color | var(--paper-dim) | -| max-width | "34rem" | -| line-height | "1.85" | -| margin | "0 0 var(--space-5)" | -| font-size | "1.05rem" | -| letter-spacing | "0.02em" | -| font-weight | "400" | -| font-family | var(--sans) | +引言解释段落的命名排版属性。 -*`lede`* +宽度、行高、颜色、间距和字体选择叶子中的解释段落,与特性徽章和编号步骤保持独立。目标应是实际段落,而非依赖包装层与浏览器默认外边距凑出近似效果;内容仍由终端 Markdown 维护。 + +从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 + +读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="lede"))*. ## claim -`claim` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | -| 属性 | 值 | -|------|-----| -| display | inline-flex | -| align-items | center | -| padding | "0.2rem 0.65rem" | -| border-radius | var(--radius-sm) | -| background | var(--wine-soft) | -| color | #f0c9d4 | -| font-size | "0.68rem" | -| font-weight | "500" | -| letter-spacing | "0.14em" | -| border | 1px solid rgba(107,30,58,0.5) | +单条简短特性徽章的命名属性。 -*`claim`* +Markdown 无序列表对应原来的 flex 徽章容器,列表项使用这里的 inline 徽章属性。容器的间距与换行归 chrome 章节。分别保留两层责任,才能同时得到直接可读的列表内容和原来的视觉分组。 + +从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 + +读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="claim"))*. ## step -`step` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | -| 属性 | 值 | -|------|-----| -| margin | "0.55rem 0" | +单条阅读步骤原有的外边距。 -*`step`* +这里只有一条属性行,原生结果含标量单元格,而不是列式列表,样式编译器支持这个形态。Markdown 编号列表拥有序号和链接,本值只提供条目留白,不改变阅读顺序或在后台替用户执行步骤。 + +从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 + +读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="step"))*. ## widgets -`widgets` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | -| 选择器 | 属性 | 值 | -|--------|------|-----| -| ul.nav | display | flex | -| ul.nav | flex-wrap | wrap | -| ul.nav | align-items | center | -| ul.nav | gap | "0.35rem 1rem" | -| ul.nav | list-style | none | -| ul.nav | margin | "0" | -| ul.nav | padding | "0" | -| ul.nav a | display | inline-flex | -| ul.nav a | align-items | center | -| ul.nav a | text-decoration | none | -| ul.nav a | color | var(--paper-dim) | -| ul.nav a | padding | "0.35rem 0" | -| ul.nav a | border-radius | "0" | -| ul.nav a | font-weight | "400" | -| ul.nav a | font-size | "0.8rem" | -| ul.nav a | letter-spacing | "0.14em" | -| ul.nav a | transition | color 0.25s ease | -| ul.nav a:hover | background | transparent | -| ul.nav a:hover | color | var(--gold) | -| ul.nav a:hover | text-decoration | none | -| ul.nav a[href="/admin"] | color | var(--gold) | -| ul.nav a[href="/admin"] | letter-spacing | "0.18em" | -| ul.nav a[href="/admin"] | border-bottom | 1px solid var(--gold-dim) | -| ul.side-nav a[href="/admin"] | color | var(--gold) | -| body.is-desk header.topnav | border-bottom | 1px solid rgba(107,30,58,0.55) | -| body.is-desk header.topnav | box-shadow | "0 12px 40px rgba(107,30,58,.18)" | -| body.is-desk .main-intro | border-left | 3px solid var(--wine) | -| body.is-desk .site-form | border-color | rgba(107,30,58,0.45) | -| body.is-desk .site-form | box-shadow | "0 0 0 1px rgba(212,175,55,.12), 0 18px 48px rgba(0,0,0,.35)" | -| body.is-desk .content.cards | margin-top | var(--space-6) | -| ul.nav li:first-child a | font-family | var(--display) | -| ul.nav li:first-child a | font-weight | "400" | -| ul.nav li:first-child a | color | var(--gold) | -| ul.nav li:first-child a | font-size | "1.85rem" | -| ul.nav li:first-child a | letter-spacing | "0.06em" | -| ul.nav li:first-child a | padding | "0.1rem 0.2rem 0.1rem 0" | -| ul.nav li:first-child a:hover | background | transparent | -| ul.nav li:first-child a:hover | color | #f5e6c8 | -| .side-label | display | block | -| .side-label | font-size | "0" | -| .side-label | margin | "0 0 var(--space-4)" | -| .side-label::before | content | '"Path"' | -| .side-label::before | display | block | -| .side-label::before | font-size | "0.68rem" | -| .side-label::before | letter-spacing | "0.28em" | -| .side-label::before | text-transform | uppercase | -| .side-label::before | color | var(--gold-dim) | -| .side-label::before | font-weight | "400" | -| ul.side-nav | list-style | none | -| ul.side-nav | margin | "0" | -| ul.side-nav | padding | "0" | -| ul.side-nav | display | grid | -| ul.side-nav | gap | "2px" | -| ul.side-nav | border-left | 1px solid var(--border) | -| ul.side-nav | padding-left | "0.85rem" | -| ul.side-nav | margin-left | "0.25rem" | -| ul.side-nav a | display | block | -| ul.side-nav a | text-decoration | none | -| ul.side-nav a | color | var(--paper-dim) | -| ul.side-nav a | padding | "0.45rem 0.35rem" | -| ul.side-nav a | border-radius | "0" | -| ul.side-nav a | font-weight | "400" | -| ul.side-nav a | font-size | "0.88rem" | -| ul.side-nav a | letter-spacing | "0.06em" | -| ul.side-nav a | border | "0" | -| ul.side-nav a | position | relative | -| ul.side-nav a:hover | background | transparent | -| ul.side-nav a:hover | border-color | transparent | -| ul.side-nav a:hover | color | var(--gold) | -| ul.side-nav a:hover | text-decoration | none | -| ul.side-nav a:hover | box-shadow | none | -| ul.foot-nav | display | flex | -| ul.foot-nav | gap | var(--space-4) | -| ul.foot-nav | list-style | none | -| ul.foot-nav | margin | "0" | -| ul.foot-nav | padding | "0" | -| ul.foot-nav a | color | var(--paper-faint) | -| ul.foot-nav a | font-weight | "400" | -| ul.foot-nav a | letter-spacing | "0.1em" | -| ul.foot-nav a | font-size | "0.78rem" | -| ul.foot-nav a:hover | color | var(--gold) | -| .content.cards | display | grid | -| .content.cards | gap | var(--space-4) | -| .content.cards | margin-top | "0" | -| .content.cards | grid-template-columns | "repeat(auto-fill, minmax(16rem, 1fr))" | -| article.card | background | "rgba(0,0,0,.35)" | -| article.card | border | 1px solid var(--border-soft) | -| article.card | border-radius | var(--radius-sm) | -| article.card | padding | "1.35rem 1.15rem" | -| article.card | box-shadow | none | -| article.card | transition | "border-color .35s ease, box-shadow .35s ease, transform .35s ease" | -| article.card:hover | transform | "translateY(-3px)" | -| article.card:hover | box-shadow | var(--shadow-card) | -| article.card:hover | border-color | var(--gold-dim) | -| .site-form | background | var(--glass) | -| .site-form | border | 1px solid var(--border) | -| .site-form | border-radius | var(--radius) | -| .site-form | padding | "var(--space-6) var(--space-6) var(--space-7, 1.75rem)" | -| .site-form | margin | "0 0 var(--space-6)" | -| .site-form | max-width | "100%" | -| .site-form | width | "100%" | -| .site-form | box-shadow | var(--shadow) | -| .site-form | backdrop-filter | blur(16px) | -| .site-form | -webkit-backdrop-filter | blur(16px) | -| .site-form .meta | display | none | -| .site-form form | display | grid | -| .site-form form | grid-template-columns | "minmax(0, 1fr) minmax(0, 1fr)" | -| .site-form form | column-gap | var(--space-5) | -| .site-form form | row-gap | var(--space-5) | -| .site-form form | gap | var(--space-5) | -| .site-form form | margin | "0" | -| .site-form form | width | "100%" | -| .site-form form | max-width | "100%" | -| .site-form label | display | grid | -| .site-form label | gap | var(--space-2) | -| .site-form label | margin | "0" | -| .site-form label | min-width | "0" | -| .site-form label | font-weight | "400" | -| .site-form label | color | var(--gold) | -| .site-form label | font-size | "0.78rem" | -| .site-form label | letter-spacing | "0.16em" | -| .site-form label | text-transform | uppercase | -| .site-form label:nth-child(1) | grid-column | "1" | -| .site-form label:nth-child(2) | grid-column | "2" | -| .site-form label:nth-child(n+3) | grid-column | "1 / -1" | -| .site-form .actions | grid-column | "1 / -1" | -| .site-form input | -webkit-appearance | none | -| .site-form textarea | -webkit-appearance | none | -| .site-form input | appearance | none | -| .site-form textarea | appearance | none | -| .site-form input | box-sizing | border-box | -| .site-form textarea | box-sizing | border-box | -| .site-form input | display | block | -| .site-form textarea | display | block | -| .site-form input | width | "100%" | -| .site-form textarea | width | "100%" | -| .site-form input | height | "2.75rem" | -| .site-form textarea | min-height | "10rem" | -| .site-form label:nth-child(4) textarea | min-height | "14rem" | -| .site-form textarea | resize | vertical | -| .site-form input | padding | "0 0.9rem" | -| .site-form textarea | padding | "0.75rem 0.9rem" | -| .site-form input | border | 1px solid var(--border) | -| .site-form textarea | border | 1px solid var(--border) | -| .site-form input | border-radius | var(--radius-sm) | -| .site-form textarea | border-radius | var(--radius-sm) | -| .site-form input | background | "rgba(0,0,0,.4)" | -| .site-form textarea | background | "rgba(0,0,0,.4)" | -| .site-form input | color | var(--paper) | -| .site-form textarea | color | var(--paper) | -| .site-form input | font | inherit | -| .site-form textarea | font | inherit | -| .site-form input | font-size | "0.95rem" | -| .site-form textarea | font-size | "0.95rem" | -| .site-form input | line-height | "1.4" | -| .site-form textarea | line-height | "1.65" | -| .site-form input | transition | "border-color .2s ease, box-shadow .2s ease" | -| .site-form textarea | transition | "border-color .2s ease, box-shadow .2s ease" | -| .site-form input:hover | border-color | var(--gold-dim) | -| .site-form textarea:hover | border-color | var(--gold-dim) | -| .site-form input:focus | outline | none | -| .site-form textarea:focus | outline | none | -| .site-form input:focus | border-color | var(--gold) | -| .site-form textarea:focus | border-color | var(--gold) | -| .site-form input:focus | box-shadow | var(--ring) | -| .site-form textarea:focus | box-shadow | var(--ring) | -| .site-form input[readonly] | background | "rgba(0,0,0,.25)" | -| .site-form input[readonly] | color | var(--paper-faint) | -| .site-form .err | color | var(--danger) | -| .site-form .err | font-size | "0.8rem" | -| .site-form .err | font-weight | "500" | -| .site-form .err | letter-spacing | "0.04em" | -| .site-form .actions | display | flex | -| .site-form .actions | align-items | center | -| .site-form .actions | gap | var(--space-4) | -| .site-form .actions | margin-top | var(--space-2) | -| .site-form .actions | flex-wrap | wrap | -| .site-form button | -webkit-appearance | none | -| .site-form button | appearance | none | -| .site-form button | height | "2.75rem" | -| .site-form button | padding | "0 1.35rem" | -| .site-form button | background | "linear-gradient(135deg, #f5e6c8, var(--gold))" | -| .site-form button | color | var(--ink) | -| .site-form button | border | "0" | -| .site-form button | border-radius | 999px | -| .site-form button | font-weight | "600" | -| .site-form button | font-size | "0.85rem" | -| .site-form button | letter-spacing | "0.12em" | -| .site-form button | cursor | pointer | -| .site-form button | box-shadow | "0 8px 28px rgba(212,175,55,.28)" | -| .site-form button | transition | "transform .2s ease, box-shadow .2s ease, filter .2s ease" | -| .site-form button:hover | filter | brightness(1.06) | -| .site-form button:hover | transform | "translateY(-1px)" | -| .site-form button:hover | box-shadow | "0 12px 36px rgba(212,175,55,.4)" | -| .site-form .actions a | color | var(--paper-faint) | -| .site-form .actions a | font-weight | "400" | -| .site-form .actions a | text-decoration | none | -| .site-form .actions a | font-size | "0.85rem" | -| .site-form .actions a | letter-spacing | "0.08em" | -| .site-form .actions a:hover | color | var(--gold) | -| .flash.err | color | var(--danger) | -| .flash.err | font-weight | "500" | +原始卡片、表单、提示和管理状态声明。 -*`widgets`* +悬停与焦点、字段宽度、操作行和后台选择器保持原顺序。原生表单资源拥有校验与提交,主题只映射结构地址。可见错误外观不能证明服务器已经拒绝输入,仍需实际失败和成功提交验收。 + +从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 + +读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="widgets"))*. + + +## _compile + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | text | 必填 | shell.tables.md 中精确原始章节 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 按原始选择器编译的单个主题区段 | + +使用`name`,从站点根授予 fs.read 与 plugin。原生读取保留原始值与形态,编译器处理选择器、媒体和关键帧。这个内部工具特意保留旧壳的地址,用于比较迁移前 CSS;当前服务使用 styles/index 的明确 View 映射。缺失章节保留诊断,返回文本既不写文件,也不证明新结构已经适配。 + +我们 **declarations = [读取原始区段的实际声明](document.read_table(path="styles/shell.tables.md", title=`name`))**. +最后返回 *[编译原地址用于保留比较](web.make_style(name=`name`, table=`declarations`))*. ## css -**v = > vars** -**m = > motion** -**l = > layout** -**r = > responsive** -**c = > chrome** -**w = > widgets** -**css_v = > web.make_style name="vars" table=v** -**css_m = > web.make_style name="motion" table=m** -**css_l = > web.make_style name="layout" table=l** -**css_r = > web.make_style name="responsive" table=r** -**css_c = > web.make_style name="chrome" table=c** -**css_w = > web.make_style name="widgets" table=w** +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 保持原六区段地址与级联的基准 CSS | -`parts` = +从站点根授权 fs.read 和 plugin,依次编译令牌、关键帧、布局、断点、引言与控件。这六段地址、顺序和连接方式保持原实现,用于原始数据与散列比较。命名属性仍可分别读取,但不额外加入本基准,以免改变原级联;它们由新的 View 入口恢复到实际目标。 -| css | -|-----| -| `css_v` | -| `css_m` | -| `css_l` | -| `css_r` | -| `css_c` | -| `css_w` | +当前站点不直接加载这个旧壳基准,实际样式见 styles/index。散列相同只能证明原始主题编译保留,不能证明新的选择器匹配、字体送达或移动布局正确。用 verify 的逐行比较加上真实浏览器验证,并由服务入口显式保存实际新主题。 -**out = > text.str_join xs=`parts` sep=""** -*out* +`names` = + +| name | +|---| +| vars | +| motion | +| layout | +| responsive | +| chrome | +| widgets | + +We **parts = [Start the ordered compiled sections](table.empty_list())**. +- [Compile each area in the declared cascade order](for names as name) + We **css = [Compile the selected theme area](_compile(name=`name`))** and **parts = [Preserve its original position](table.append(list=`parts`, item=`css`))**. +Return *[Join the compiled sections without changing separators](text.str_join(xs=`parts`, sep=""))*. diff --git a/examples/web-site-zh/styles/shell.tables.md b/examples/web-site-zh/styles/shell.tables.md new file mode 100644 index 0000000..c3a64db --- /dev/null +++ b/examples/web-site-zh/styles/shell.tables.md @@ -0,0 +1,602 @@ +# Theme declarations + +Literal theme declarations. Callable use and CSS assembly are documented next to this file in shell.mq.md. Each section preserves one native table, including its column names and literal types. + +## vars + +Palette, typefaces, spacing and elevation tokens used by every region. + +| 选择器 | 属性 | 值 | +|--------|------|-----| +| :root | --ink | #0a0809 | +| :root | --ink-lift | #141012 | +| :root | --wine | #6b1e3a | +| :root | --wine-soft | rgba(107,30,58,0.35) | +| :root | --gold | #d4af37 | +| :root | --gold-dim | rgba(212,175,55,0.45) | +| :root | --gold-soft | rgba(212,175,55,0.12) | +| :root | --paper | rgba(255,248,240,0.92) | +| :root | --paper-dim | rgba(255,248,240,0.72) | +| :root | --paper-faint | rgba(255,248,240,0.48) | +| :root | --glass | rgba(20,12,18,0.72) | +| :root | --glass-strong | rgba(20,12,18,0.88) | +| :root | --border | rgba(212,175,55,0.22) | +| :root | --border-soft | rgba(212,175,55,0.12) | +| :root | --danger | #e8a0a8 | +| :root | --radius | 4px | +| :root | --radius-sm | 2px | +| :root | --space-2 | 8px | +| :root | --space-3 | 12px | +| :root | --space-4 | 16px | +| :root | --space-5 | 20px | +| :root | --space-6 | 24px | +| :root | --space-8 | 32px | +| :root | --text | 16px | +| :root | --leading | "1.75" | +| :root | --shadow | "0 24px 80px rgba(0,0,0,.55), inset 0 1px 0 rgba(255,255,255,.06)" | +| :root | --shadow-card | "0 12px 40px rgba(107,30,58,.35)" | +| :root | --ring | "0 0 0 2px rgba(212,175,55,.35)" | +| :root | --serif | "'Noto Serif SC', 'Source Serif 4', Georgia, serif" | +| :root | --sans | "'Noto Sans SC', 'IBM Plex Sans', system-ui, sans-serif" | +| :root | --display | "'Great Vibes', 'Allura', cursive" | +| :root | --mono | "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace" | +| ::selection | background | rgba(212,175,55,0.35) | +| ::selection | color | var(--paper) | + +## motion + +Entrance, floating, particle and glow keyframes; animation timings remain in consuming selectors. + +| 选择器 | 属性 | 值 | +|--------|------|-----| +| @keyframes rise 0% | opacity | "0" | +| @keyframes rise 0% | transform | translateY(14px) | +| @keyframes rise 100% | opacity | "1" | +| @keyframes rise 100% | transform | translateY(0) | +| @keyframes float 0% | transform | translateY(0) | +| @keyframes float 0% | opacity | "0.7" | +| @keyframes float 50% | transform | translateY(6px) | +| @keyframes float 50% | opacity | "1" | +| @keyframes float 100% | transform | translateY(0) | +| @keyframes float 100% | opacity | "0.7" | +| @keyframes goldPulse 0% | text-shadow | "0 0 24px rgba(212,175,55,.2)" | +| @keyframes goldPulse 50% | text-shadow | "0 0 48px rgba(212,175,55,.45)" | +| @keyframes goldPulse 100% | text-shadow | "0 0 24px rgba(212,175,55,.2)" | +| @keyframes particleDrift 0% | transform | translate3d(0,0,0) | +| @keyframes particleDrift 50% | transform | translate3d(-2.5vw, 1.5vh, 0) | +| @keyframes particleDrift 100% | transform | translate3d(0,0,0) | +| @keyframes particleDrift2 0% | transform | translate3d(0,0,0) | +| @keyframes particleDrift2 50% | transform | translate3d(2vw, -2vh, 0) | +| @keyframes particleDrift2 100% | transform | translate3d(0,0,0) | +| @keyframes nebulaPulse 0% | opacity | "0.55" | +| @keyframes nebulaPulse 50% | opacity | "0.9" | +| @keyframes nebulaPulse 100% | opacity | "0.55" | + +## layout + +Page grid, background, typography, navigation and main content rules. + +| 选择器 | 属性 | 值 | +|--------|------|-----| +| * | box-sizing | border-box | +| html | scroll-behavior | smooth | +| html | -webkit-text-size-adjust | 100% | +| body | margin | "0" | +| body | min-height | 100vh | +| body | font-family | var(--sans) | +| body | font-weight | "400" | +| body | font-size | var(--text) | +| body | line-height | var(--leading) | +| body | color | var(--paper) | +| body | background | var(--ink) | +| body | background-image | "radial-gradient(ellipse 90% 55% at 50% -15%, rgba(107,30,58,.5), transparent 58%), radial-gradient(ellipse 55% 45% at 92% 75%, rgba(212,175,55,.14), transparent 55%), radial-gradient(ellipse 40% 35% at 8% 70%, rgba(107,30,58,.22), transparent 60%), linear-gradient(180deg, #0a0809 0%, #120c10 45%, #0a0809 100%)" | +| body | background-attachment | fixed | +| body | display | grid | +| body | grid-template-rows | "auto 1fr auto" | +| body | -webkit-font-smoothing | antialiased | +| body | position | relative | +| body | overflow-x | hidden | +| body::before | content | '""' | +| body::before | position | fixed | +| body::before | inset | "0" | +| body::before | z-index | "1" | +| body::before | pointer-events | none | +| body::before | opacity | "0.1" | +| body::before | background-image | "url(\"data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E\")" | +| html::before | content | '""' | +| html::before | position | fixed | +| html::before | inset | "0" | +| html::before | z-index | "0" | +| html::before | pointer-events | none | +| html::before | background-image | "radial-gradient(ellipse 50% 40% at 15% 30%, rgba(107,30,58,.35), transparent 70%), radial-gradient(ellipse 45% 35% at 85% 60%, rgba(212,175,55,.12), transparent 65%), radial-gradient(ellipse 40% 30% at 50% 90%, rgba(107,30,58,.25), transparent 70%)" | +| html::before | animation | "nebulaPulse 12s ease-in-out infinite" | +| body::after | content | '""' | +| body::after | position | fixed | +| body::after | top | "0" | +| body::after | left | "0" | +| body::after | width | "2px" | +| body::after | height | "2px" | +| body::after | z-index | "2" | +| body::after | pointer-events | none | +| body::after | border-radius | 50% | +| body::after | background | transparent | +| body::after | box-shadow | "82vw 15vh 0px 0px rgba(212,175,55,0.55),29vw 18vh 0px 1px rgba(212,175,55,0.25),95vw 70vh 1px 0px rgba(212,175,55,0.55),4vw 12vh 0px 1px rgba(212,175,55,0.35),78vw 4vh 0px 1px rgba(245,230,200,0.5),84vw 90vh 1px 0px rgba(245,230,200,0.5),58vw 76vh 0px 0px rgba(255,248,240,0.4),90vw 55vh 0px 0px rgba(255,248,240,0.4),28vw 98vh 0px 0px rgba(255,248,240,0.4),49vw 13vh 0px 1px rgba(255,248,240,0.4),34vw 6vh 1px 1px rgba(212,175,55,0.25),16vw 49vh 0px 1px rgba(212,175,55,0.55),80vw 47vh 0px 1px rgba(245,230,200,0.5),9vw 6vh 0px 0px rgba(212,175,55,0.25),11vw 30vh 1px 0px rgba(212,175,55,0.55),59vw 82vh 0px 0px rgba(255,248,240,0.4),46vw 27vh 0px 1px rgba(212,175,55,0.25),88vw 83vh 0px 1px rgba(212,175,55,0.55),94vw 32vh 1px 0px rgba(212,175,55,0.35),35vw 82vh 0px 1px rgba(212,175,55,0.25),42vw 99vh 0px 0px rgba(212,175,55,0.55),41vw 52vh 0px 0px rgba(255,248,240,0.4),73vw 92vh 0px 1px rgba(255,248,240,0.4),64vw 51vh 1px 0px rgba(212,175,55,0.25),34vw 18vh 0px 1px rgba(212,175,55,0.35),75vw 55vh 1px 0px rgba(245,230,200,0.5),29vw 18vh 1px 0px rgba(245,230,200,0.5),97vw 7vh 0px 1px rgba(212,175,55,0.55),21vw 88vh 0px 0px rgba(107,30,58,0.45),49vw 77vh 0px 1px rgba(107,30,58,0.45),2vw 88vh 0px 1px rgba(212,175,55,0.25),69vw 97vh 0px 0px rgba(255,248,240,0.4),38vw 56vh 1px 0px rgba(212,175,55,0.35),93vw 93vh 0px 1px rgba(255,248,240,0.4),14vw 81vh 0px 0px rgba(255,248,240,0.4),48vw 98vh 0px 1px rgba(212,175,55,0.35),42vw 63vh 0px 0px rgba(212,175,55,0.55),40vw 31vh 0px 1px rgba(212,175,55,0.55),11vw 11vh 1px 0px rgba(212,175,55,0.25),98vw 69vh 0px 1px rgba(212,175,55,0.35),61vw 71vh 0px 1px rgba(212,175,55,0.35),78vw 55vh 0px 1px rgba(212,175,55,0.35),40vw 52vh 0px 0px rgba(212,175,55,0.25),67vw 58vh 0px 0px rgba(212,175,55,0.55),9vw 44vh 0px 1px rgba(212,175,55,0.55),29vw 1vh 0px 0px rgba(212,175,55,0.55),9vw 5vh 0px 1px rgba(255,248,240,0.4),31vw 36vh 1px 0px rgba(212,175,55,0.25),70vw 17vh 1px 0px rgba(212,175,55,0.25),61vw 53vh 0px 0px rgba(212,175,55,0.35),85vw 56vh 1px 0px rgba(255,248,240,0.4),60vw 94vh 0px 0px rgba(212,175,55,0.55),52vw 94vh 0px 0px rgba(255,248,240,0.4),25vw 25vh 1px 0px rgba(245,230,200,0.5),55vw 24vh 1px 0px rgba(255,248,240,0.4),10vw 57vh 0px 0px rgba(245,230,200,0.5),84vw 70vh 0px 0px rgba(212,175,55,0.55),22vw 53vh 1px 0px rgba(107,30,58,0.45),52vw 8vh 1px 0px rgba(212,175,55,0.35),50vw 34vh 0px 0px rgba(107,30,58,0.45),90vw 94vh 1px 0px rgba(245,230,200,0.5),25vw 38vh 0px 1px rgba(212,175,55,0.35),95vw 70vh 0px 0px rgba(212,175,55,0.55),7vw 75vh 0px 0px rgba(107,30,58,0.45),66vw 11vh 0px 1px rgba(212,175,55,0.35),9vw 87vh 1px 0px rgba(212,175,55,0.35),73vw 32vh 0px 1px rgba(245,230,200,0.5),11vw 54vh 0px 0px rgba(212,175,55,0.25),27vw 86vh 0px 0px rgba(212,175,55,0.25),34vw 51vh 0px 0px rgba(212,175,55,0.35),41vw 97vh 0px 0px rgba(212,175,55,0.55),80vw 73vh 0px 1px rgba(212,175,55,0.55)" | +| body::after | animation | "particleDrift 48s ease-in-out infinite" | +| html::after | content | '""' | +| html::after | position | fixed | +| html::after | top | "0" | +| html::after | left | "0" | +| html::after | width | "1px" | +| html::after | height | "1px" | +| html::after | z-index | "2" | +| html::after | pointer-events | none | +| html::after | border-radius | 50% | +| html::after | background | transparent | +| html::after | box-shadow | "28vw 65vh 0 0 rgba(255,248,240,0.25),17vw 45vh 0 0 rgba(212,175,55,0.3),32vw 48vh 0 0 rgba(255,248,240,0.25),21vw 57vh 0 0 rgba(107,30,58,0.3),91vw 39vh 0 0 rgba(107,30,58,0.3),84vw 68vh 0 0 rgba(212,175,55,0.3),86vw 71vh 0 0 rgba(255,248,240,0.25),85vw 14vh 0 0 rgba(212,175,55,0.3),34vw 15vh 0 0 rgba(212,175,55,0.3),96vw 71vh 0 0 rgba(212,175,55,0.3),35vw 37vh 0 0 rgba(107,30,58,0.3),27vw 92vh 0 0 rgba(255,248,240,0.25),27vw 88vh 0 0 rgba(107,30,58,0.3),34vw 65vh 0 0 rgba(255,248,240,0.25),33vw 7vh 0 0 rgba(212,175,55,0.3),82vw 55vh 0 0 rgba(255,248,240,0.25),6vw 1vh 0 0 rgba(255,248,240,0.25),99vw 17vh 0 0 rgba(107,30,58,0.3),34vw 21vh 0 0 rgba(107,30,58,0.3),57vw 71vh 0 0 rgba(107,30,58,0.3),55vw 72vh 0 0 rgba(212,175,55,0.3),15vw 10vh 0 0 rgba(107,30,58,0.3),20vw 70vh 0 0 rgba(212,175,55,0.3),48vw 75vh 0 0 rgba(107,30,58,0.3),19vw 56vh 0 0 rgba(212,175,55,0.3),6vw 40vh 0 0 rgba(255,248,240,0.25),6vw 46vh 0 0 rgba(212,175,55,0.3),88vw 32vh 0 0 rgba(107,30,58,0.3),14vw 46vh 0 0 rgba(107,30,58,0.3),53vw 80vh 0 0 rgba(107,30,58,0.3),20vw 31vh 0 0 rgba(212,175,55,0.3),23vw 53vh 0 0 rgba(212,175,55,0.3),23vw 95vh 0 0 rgba(255,248,240,0.25),53vw 86vh 0 0 rgba(107,30,58,0.3),32vw 35vh 0 0 rgba(212,175,55,0.3),90vw 14vh 0 0 rgba(255,248,240,0.25),5vw 61vh 0 0 rgba(212,175,55,0.3),26vw 59vh 0 0 rgba(255,248,240,0.25),40vw 30vh 0 0 rgba(212,175,55,0.3),4vw 85vh 0 0 rgba(212,175,55,0.3),52vw 43vh 0 0 rgba(255,248,240,0.25),9vw 99vh 0 0 rgba(255,248,240,0.25),45vw 83vh 0 0 rgba(107,30,58,0.3),52vw 87vh 0 0 rgba(107,30,58,0.3),43vw 4vh 0 0 rgba(212,175,55,0.3),34vw 23vh 0 0 rgba(107,30,58,0.3),34vw 5vh 0 0 rgba(212,175,55,0.3),77vw 56vh 0 0 rgba(255,248,240,0.25)" | +| html::after | animation | "particleDrift2 64s ease-in-out infinite" | +| body.has-sidebar | grid-template-columns | "14rem minmax(0, 1fr)" | +| body.has-sidebar | grid-template-areas | '"top top" "side main" "foot foot"' | +| body.no-sidebar | grid-template-areas | '"top" "main" "foot"' | +| body.layout-stacked | grid-template-areas | '"top" "main" "foot"' | +| body.is-desk | grid-template-areas | '"top" "main" "foot"' | +| header.topnav | grid-area | top | +| aside.side | grid-area | side | +| main.main | grid-area | main | +| footer.foot | grid-area | foot | +| header.topnav | position | relative | +| header.topnav | z-index | "20" | +| aside.side | position | relative | +| aside.side | z-index | "10" | +| main.main | position | relative | +| main.main | z-index | "10" | +| footer.foot | position | relative | +| footer.foot | z-index | "10" | +| main.main | width | "100%" | +| main.main | max-width | "min(78rem, 100%)" | +| main.main | padding | "var(--space-8) var(--space-6) 4rem" | +| main.main | animation | "rise .8s cubic-bezier(.22,1,.36,1) both" | +| a | color | var(--gold) | +| a | text-decoration | none | +| a | transition | color 0.25s ease | +| a:hover | color | #f5e6c8 | +| code | font-family | var(--mono) | +| code | font-size | "0.82em" | +| code | font-weight | "400" | +| code | background | rgba(0,0,0,0.35) | +| code | border | 1px solid var(--border-soft) | +| code | padding | "0.12em 0.45em" | +| code | border-radius | var(--radius-sm) | +| code | color | var(--gold) | + +## responsive + +Media conditions that collapse the side panel and card grid on small screens. + +| 媒体 | 选择器 | 属性 | 值 | +|------|--------|------|-----| +| (max-width: 860px) | body.has-sidebar | grid-template-columns | 1fr | +| (max-width: 860px) | body.has-sidebar | grid-template-areas | '"top" "main" "side" "foot"' | +| (max-width: 860px) | aside.side | border-right | "0" | +| (max-width: 860px) | aside.side | border-top | 1px solid var(--border-soft) | +| (max-width: 860px) | main.main | padding | "var(--space-6) var(--space-4) var(--space-8)" | +| (max-width: 860px) | .content.cards | grid-template-columns | 1fr | +| (max-width: 860px) | .site-form form | grid-template-columns | 1fr | +| (max-width: 860px) | .site-form label:nth-child(1) | grid-column | "1 / -1" | +| (max-width: 860px) | .site-form label:nth-child(2) | grid-column | "1 / -1" | +| (max-width: 860px) | header.topnav | padding | "0.85rem var(--space-4)" | +| (max-width: 860px) | .intro_title | font-size | "2.4rem" | +| (prefers-reduced-motion: reduce) | main.main | animation | none | +| (prefers-reduced-motion: reduce) | .kicker | animation | none | +| (prefers-reduced-motion: reduce) | article.card | transition | none | +| (prefers-reduced-motion: reduce) | body::after | animation | none | +| (prefers-reduced-motion: reduce) | html::after | animation | none | +| (prefers-reduced-motion: reduce) | html::before | animation | none | + +## topnav + +Property/value style attached to the top navigation binding. + +| 属性 | 值 | +|------|-----| +| position | sticky | +| top | "0" | +| z-index | "40" | +| display | flex | +| align-items | center | +| justify-content | flex-start | +| gap | var(--space-4) | +| padding | "1rem var(--space-6)" | +| background | "linear-gradient(180deg, rgba(10,8,9,.92) 0%, rgba(10,8,9,.55) 70%, transparent 100%)" | +| backdrop-filter | blur(10px) | +| -webkit-backdrop-filter | blur(10px) | +| border-bottom | 1px solid var(--border-soft) | + +## side_panel + +Property/value style for the secondary navigation and explanatory panel. + +| 属性 | 值 | +|------|-----| +| background | "rgba(10,8,9,.55)" | +| padding | "var(--space-6) var(--space-4)" | +| border-right | 1px solid var(--border-soft) | + +## footer + +Property/value style for the closing navigation and attribution. + +| 属性 | 值 | +|------|-----| +| color | var(--paper-faint) | +| font-size | "0.8rem" | +| letter-spacing | "0.08em" | +| padding | "var(--space-5) var(--space-6)" | +| border-top | 1px solid var(--border-soft) | +| background | "rgba(10,8,9,.75)" | + +## card_title + +Property/value typography for a linked article title. + +| 属性 | 值 | +|------|-----| +| font-family | var(--serif) | +| font-size | "1.15rem" | +| font-weight | "600" | +| margin | "0 0 var(--space-2)" | +| color | var(--gold) | +| letter-spacing | "0.02em" | +| line-height | "1.35" | + +## card_body + +Property/value typography for an article's summary. + +| 属性 | 值 | +|------|-----| +| color | var(--paper-dim) | +| margin | "0" | +| line-height | "1.65" | +| font-size | "0.9rem" | +| font-weight | "400" | +| display | "-webkit-box" | +| -webkit-box-orient | vertical | +| -webkit-line-clamp | "3" | +| overflow | hidden | + +## chrome + +Grouped selectors for introduction panels, claims, reading steps and full article content. + +| 选择器 | 属性 | 值 | +|--------|------|-----| +| .main-intro | background | var(--glass) | +| .main-intro | border | 1px solid var(--border) | +| .main-intro | border-radius | var(--radius) | +| .main-intro | padding | "2.25rem 1.75rem 1.85rem" | +| .main-intro | box-shadow | var(--shadow) | +| .main-intro | backdrop-filter | blur(16px) | +| .main-intro | -webkit-backdrop-filter | blur(16px) | +| .main-intro | margin-bottom | var(--space-8) | +| .main-intro > .claim | display | flex | +| .main-intro > .claim | flex-wrap | wrap | +| .main-intro > .claim | gap | var(--space-2) | +| .main-intro > .claim | margin | "0 0 var(--space-6)" | +| .main-intro > .steps | margin | "0" | +| .main-intro > .steps | padding | "var(--space-5) var(--space-5) var(--space-5) 1.5rem" | +| .main-intro > .steps | color | var(--paper-dim) | +| .main-intro > .steps | background | "rgba(0,0,0,.35)" | +| .main-intro > .steps | border | 1px solid var(--border-soft) | +| .main-intro > .steps | border-left | 2px solid var(--gold-dim) | +| .main-intro > .steps | border-radius | var(--radius) | +| .main-intro > .steps | font-size | "0.95rem" | +| .main-intro > .steps | letter-spacing | "0.02em" | +| .main-intro > .steps a | color | var(--gold) | +| .main-intro > .steps a | font-weight | "500" | +| .main-intro > .steps a:hover | color | #f5e6c8 | +| .article | background | var(--glass) | +| .article | border | 1px solid var(--border) | +| .article | border-radius | var(--radius) | +| .article | padding | "2rem 1.75rem" | +| .article | box-shadow | var(--shadow) | +| .article | backdrop-filter | blur(16px) | +| .article | -webkit-backdrop-filter | blur(16px) | +| .article-title | font-family | var(--serif) | +| .article-title | font-size | "clamp(1.75rem, 4vw, 2.35rem)" | +| .article-title | font-weight | "600" | +| .article-title | color | var(--gold) | +| .article-title | letter-spacing | "0.04em" | +| .article-title | margin | "0 0 var(--space-5)" | +| .article-title | line-height | "1.25" | +| .article-body | color | var(--paper-dim) | +| .article-body | font-family | var(--sans) | +| .article-body | font-size | "1.02rem" | +| .article-body | line-height | "1.85" | +| .article-body.md p | margin | "0 0 1.1rem" | +| .article-body.md a | color | var(--gold) | +| article.card | cursor | pointer | +| a.card-link | color | inherit | +| a.card-link | text-decoration | none | +| a.card-link:hover | color | inherit | + +## kicker + +Property/value typography for the small introductory category label. + +| 属性 | 值 | +|------|-----| +| letter-spacing | "0.32em" | +| text-transform | uppercase | +| font-size | "0.72rem" | +| color | var(--gold-dim) | +| margin | "0 0 var(--space-4)" | +| font-weight | "400" | +| font-family | var(--sans) | +| animation | "float 2.8s ease-in-out infinite" | + +## intro_title + +Property/value typography and responsive size for the main introduction heading. + +| 属性 | 值 | +|------|-----| +| font-family | var(--display) | +| font-size | "clamp(3rem, 10vw, 4.8rem)" | +| font-weight | "400" | +| line-height | "1.15" | +| letter-spacing | "0.04em" | +| margin | "0 0 var(--space-4)" | +| color | transparent | +| background | "linear-gradient(135deg, #f5e6c8 0%, var(--gold) 42%, var(--wine) 100%)" | +| -webkit-background-clip | text | +| background-clip | text | +| animation | "goldPulse 4.5s ease-in-out infinite" | + +## lede + +Property/value typography for the supporting introduction paragraph. + +| 属性 | 值 | +|------|-----| +| color | var(--paper-dim) | +| max-width | "34rem" | +| line-height | "1.85" | +| margin | "0 0 var(--space-5)" | +| font-size | "1.05rem" | +| letter-spacing | "0.02em" | +| font-weight | "400" | +| font-family | var(--sans) | + +## claim + +Property/value style used by the short feature claims. + +| 属性 | 值 | +|------|-----| +| display | inline-flex | +| align-items | center | +| padding | "0.2rem 0.65rem" | +| border-radius | var(--radius-sm) | +| background | var(--wine-soft) | +| color | #f0c9d4 | +| font-size | "0.68rem" | +| font-weight | "500" | +| letter-spacing | "0.14em" | +| border | 1px solid rgba(107,30,58,0.5) | + +## step + +Initial demonstration records in their original column-oriented shape; ids and stable slugs retain their meaning. + +| 属性 | 值 | +|------|-----| +| margin | "0.55rem 0" | + +## widgets + +Cards, forms, flash messages and administration controls, including hover and focus states. + +| 选择器 | 属性 | 值 | +|--------|------|-----| +| ul.nav | display | flex | +| ul.nav | flex-wrap | wrap | +| ul.nav | align-items | center | +| ul.nav | gap | "0.35rem 1rem" | +| ul.nav | list-style | none | +| ul.nav | margin | "0" | +| ul.nav | padding | "0" | +| ul.nav a | display | inline-flex | +| ul.nav a | align-items | center | +| ul.nav a | text-decoration | none | +| ul.nav a | color | var(--paper-dim) | +| ul.nav a | padding | "0.35rem 0" | +| ul.nav a | border-radius | "0" | +| ul.nav a | font-weight | "400" | +| ul.nav a | font-size | "0.8rem" | +| ul.nav a | letter-spacing | "0.14em" | +| ul.nav a | transition | color 0.25s ease | +| ul.nav a:hover | background | transparent | +| ul.nav a:hover | color | var(--gold) | +| ul.nav a:hover | text-decoration | none | +| ul.nav a[href="/admin"] | color | var(--gold) | +| ul.nav a[href="/admin"] | letter-spacing | "0.18em" | +| ul.nav a[href="/admin"] | border-bottom | 1px solid var(--gold-dim) | +| ul.side-nav a[href="/admin"] | color | var(--gold) | +| body.is-desk header.topnav | border-bottom | 1px solid rgba(107,30,58,0.55) | +| body.is-desk header.topnav | box-shadow | "0 12px 40px rgba(107,30,58,.18)" | +| body.is-desk .main-intro | border-left | 3px solid var(--wine) | +| body.is-desk .site-form | border-color | rgba(107,30,58,0.45) | +| body.is-desk .site-form | box-shadow | "0 0 0 1px rgba(212,175,55,.12), 0 18px 48px rgba(0,0,0,.35)" | +| body.is-desk .content.cards | margin-top | var(--space-6) | +| ul.nav li:first-child a | font-family | var(--display) | +| ul.nav li:first-child a | font-weight | "400" | +| ul.nav li:first-child a | color | var(--gold) | +| ul.nav li:first-child a | font-size | "1.85rem" | +| ul.nav li:first-child a | letter-spacing | "0.06em" | +| ul.nav li:first-child a | padding | "0.1rem 0.2rem 0.1rem 0" | +| ul.nav li:first-child a:hover | background | transparent | +| ul.nav li:first-child a:hover | color | #f5e6c8 | +| .side-label | display | block | +| .side-label | font-size | "0" | +| .side-label | margin | "0 0 var(--space-4)" | +| .side-label::before | content | '"Path"' | +| .side-label::before | display | block | +| .side-label::before | font-size | "0.68rem" | +| .side-label::before | letter-spacing | "0.28em" | +| .side-label::before | text-transform | uppercase | +| .side-label::before | color | var(--gold-dim) | +| .side-label::before | font-weight | "400" | +| ul.side-nav | list-style | none | +| ul.side-nav | margin | "0" | +| ul.side-nav | padding | "0" | +| ul.side-nav | display | grid | +| ul.side-nav | gap | "2px" | +| ul.side-nav | border-left | 1px solid var(--border) | +| ul.side-nav | padding-left | "0.85rem" | +| ul.side-nav | margin-left | "0.25rem" | +| ul.side-nav a | display | block | +| ul.side-nav a | text-decoration | none | +| ul.side-nav a | color | var(--paper-dim) | +| ul.side-nav a | padding | "0.45rem 0.35rem" | +| ul.side-nav a | border-radius | "0" | +| ul.side-nav a | font-weight | "400" | +| ul.side-nav a | font-size | "0.88rem" | +| ul.side-nav a | letter-spacing | "0.06em" | +| ul.side-nav a | border | "0" | +| ul.side-nav a | position | relative | +| ul.side-nav a:hover | background | transparent | +| ul.side-nav a:hover | border-color | transparent | +| ul.side-nav a:hover | color | var(--gold) | +| ul.side-nav a:hover | text-decoration | none | +| ul.side-nav a:hover | box-shadow | none | +| ul.foot-nav | display | flex | +| ul.foot-nav | gap | var(--space-4) | +| ul.foot-nav | list-style | none | +| ul.foot-nav | margin | "0" | +| ul.foot-nav | padding | "0" | +| ul.foot-nav a | color | var(--paper-faint) | +| ul.foot-nav a | font-weight | "400" | +| ul.foot-nav a | letter-spacing | "0.1em" | +| ul.foot-nav a | font-size | "0.78rem" | +| ul.foot-nav a:hover | color | var(--gold) | +| .content.cards | display | grid | +| .content.cards | gap | var(--space-4) | +| .content.cards | margin-top | "0" | +| .content.cards | grid-template-columns | "repeat(auto-fill, minmax(16rem, 1fr))" | +| article.card | background | "rgba(0,0,0,.35)" | +| article.card | border | 1px solid var(--border-soft) | +| article.card | border-radius | var(--radius-sm) | +| article.card | padding | "1.35rem 1.15rem" | +| article.card | box-shadow | none | +| article.card | transition | "border-color .35s ease, box-shadow .35s ease, transform .35s ease" | +| article.card:hover | transform | "translateY(-3px)" | +| article.card:hover | box-shadow | var(--shadow-card) | +| article.card:hover | border-color | var(--gold-dim) | +| .site-form | background | var(--glass) | +| .site-form | border | 1px solid var(--border) | +| .site-form | border-radius | var(--radius) | +| .site-form | padding | "var(--space-6) var(--space-6) var(--space-7, 1.75rem)" | +| .site-form | margin | "0 0 var(--space-6)" | +| .site-form | max-width | "100%" | +| .site-form | width | "100%" | +| .site-form | box-shadow | var(--shadow) | +| .site-form | backdrop-filter | blur(16px) | +| .site-form | -webkit-backdrop-filter | blur(16px) | +| .site-form .meta | display | none | +| .site-form form | display | grid | +| .site-form form | grid-template-columns | "minmax(0, 1fr) minmax(0, 1fr)" | +| .site-form form | column-gap | var(--space-5) | +| .site-form form | row-gap | var(--space-5) | +| .site-form form | gap | var(--space-5) | +| .site-form form | margin | "0" | +| .site-form form | width | "100%" | +| .site-form form | max-width | "100%" | +| .site-form label | display | grid | +| .site-form label | gap | var(--space-2) | +| .site-form label | margin | "0" | +| .site-form label | min-width | "0" | +| .site-form label | font-weight | "400" | +| .site-form label | color | var(--gold) | +| .site-form label | font-size | "0.78rem" | +| .site-form label | letter-spacing | "0.16em" | +| .site-form label | text-transform | uppercase | +| .site-form label:nth-child(1) | grid-column | "1" | +| .site-form label:nth-child(2) | grid-column | "2" | +| .site-form label:nth-child(n+3) | grid-column | "1 / -1" | +| .site-form .actions | grid-column | "1 / -1" | +| .site-form input | -webkit-appearance | none | +| .site-form textarea | -webkit-appearance | none | +| .site-form input | appearance | none | +| .site-form textarea | appearance | none | +| .site-form input | box-sizing | border-box | +| .site-form textarea | box-sizing | border-box | +| .site-form input | display | block | +| .site-form textarea | display | block | +| .site-form input | width | "100%" | +| .site-form textarea | width | "100%" | +| .site-form input | height | "2.75rem" | +| .site-form textarea | min-height | "10rem" | +| .site-form label:nth-child(4) textarea | min-height | "14rem" | +| .site-form textarea | resize | vertical | +| .site-form input | padding | "0 0.9rem" | +| .site-form textarea | padding | "0.75rem 0.9rem" | +| .site-form input | border | 1px solid var(--border) | +| .site-form textarea | border | 1px solid var(--border) | +| .site-form input | border-radius | var(--radius-sm) | +| .site-form textarea | border-radius | var(--radius-sm) | +| .site-form input | background | "rgba(0,0,0,.4)" | +| .site-form textarea | background | "rgba(0,0,0,.4)" | +| .site-form input | color | var(--paper) | +| .site-form textarea | color | var(--paper) | +| .site-form input | font | inherit | +| .site-form textarea | font | inherit | +| .site-form input | font-size | "0.95rem" | +| .site-form textarea | font-size | "0.95rem" | +| .site-form input | line-height | "1.4" | +| .site-form textarea | line-height | "1.65" | +| .site-form input | transition | "border-color .2s ease, box-shadow .2s ease" | +| .site-form textarea | transition | "border-color .2s ease, box-shadow .2s ease" | +| .site-form input:hover | border-color | var(--gold-dim) | +| .site-form textarea:hover | border-color | var(--gold-dim) | +| .site-form input:focus | outline | none | +| .site-form textarea:focus | outline | none | +| .site-form input:focus | border-color | var(--gold) | +| .site-form textarea:focus | border-color | var(--gold) | +| .site-form input:focus | box-shadow | var(--ring) | +| .site-form textarea:focus | box-shadow | var(--ring) | +| .site-form input[readonly] | background | "rgba(0,0,0,.25)" | +| .site-form input[readonly] | color | var(--paper-faint) | +| .site-form .err | color | var(--danger) | +| .site-form .err | font-size | "0.8rem" | +| .site-form .err | font-weight | "500" | +| .site-form .err | letter-spacing | "0.04em" | +| .site-form .actions | display | flex | +| .site-form .actions | align-items | center | +| .site-form .actions | gap | var(--space-4) | +| .site-form .actions | margin-top | var(--space-2) | +| .site-form .actions | flex-wrap | wrap | +| .site-form button | -webkit-appearance | none | +| .site-form button | appearance | none | +| .site-form button | height | "2.75rem" | +| .site-form button | padding | "0 1.35rem" | +| .site-form button | background | "linear-gradient(135deg, #f5e6c8, var(--gold))" | +| .site-form button | color | var(--ink) | +| .site-form button | border | "0" | +| .site-form button | border-radius | 999px | +| .site-form button | font-weight | "600" | +| .site-form button | font-size | "0.85rem" | +| .site-form button | letter-spacing | "0.12em" | +| .site-form button | cursor | pointer | +| .site-form button | box-shadow | "0 8px 28px rgba(212,175,55,.28)" | +| .site-form button | transition | "transform .2s ease, box-shadow .2s ease, filter .2s ease" | +| .site-form button:hover | filter | brightness(1.06) | +| .site-form button:hover | transform | "translateY(-1px)" | +| .site-form button:hover | box-shadow | "0 12px 36px rgba(212,175,55,.4)" | +| .site-form .actions a | color | var(--paper-faint) | +| .site-form .actions a | font-weight | "400" | +| .site-form .actions a | text-decoration | none | +| .site-form .actions a | font-size | "0.85rem" | +| .site-form .actions a | letter-spacing | "0.08em" | +| .site-form .actions a:hover | color | var(--gold) | +| .flash.err | color | var(--danger) | +| .flash.err | font-weight | "500" | diff --git a/examples/web-site-zh/styles/view.tables.md b/examples/web-site-zh/styles/view.tables.md new file mode 100644 index 0000000..f30332e --- /dev/null +++ b/examples/web-site-zh/styles/view.tables.md @@ -0,0 +1,71 @@ +# View 几何适配 + +这些字面声明只适配明确的 View 包装。原始色板、动画、排版和组件属性保留在 shell.tables.md;可调用入口说明如何将递归框架连接到这些数据。 + +## geometry + +基础预览层继承本站字体与全宽。资源仍保留结构值,其语义子块参与原来的命名网格;列表使用 Markdown,不增加私有引言方言。 + +| selector | property | value | +|---|---|---| +| .mq-document .mq-view | max-width | none | +| .mq-document .mq-view | margin | 0 | +| .mq-document .mq-view | padding | 0 | +| .mq-document .mq-view | line-height | inherit | +| .mq-document .mq-view | font-family | inherit | +| .mq-document .site-layout | display | grid | +| .mq-document .site-layout | grid-template-rows | auto 1fr auto | +| .mq-document .site-layout | min-height | 100vh | +| .mq-document .site-layout > .slot-nav | display | contents | +| .mq-document .site-layout > .slot-sidebar | display | contents | +| .mq-document .site-layout .main-intro ul | padding | 0 | +| .mq-document .site-layout .main-intro ul | list-style | none | +| .mq-document .site-layout .main-intro li > p | margin | 0 | +| .mq-document .site-layout .main-intro blockquote > p | margin | 0 | + +## selectors + +只有这些结构地址改变,原属性、值、媒体与顺序保留。这是本站迁移表,不是新的页面语言。 + +| @ | old | new | +|---|---|---| +| 1 | body.has-sidebar | .site-layout.has-sidebar | +| 2 | body.no-sidebar | .site-layout.no-sidebar | +| 3 | body.layout-stacked | .site-layout.layout-stacked | +| 4 | body.is-desk | .site-layout.is-desk | +| 5 | main.main | section.main | +| 6 | .main-intro > .claim | .main-intro ul | +| 7 | .main-intro > .steps | .main-intro ol | +| 8 | .intro_title | .main-intro h1 | +| 9 | .kicker | .main-intro blockquote | + +## areas + +按同一级联顺序编译这些原始章节。 + +| name | +|---| +| vars | +| motion | +| layout | +| responsive | +| chrome | +| widgets | + + +## properties + +在实际语义目标上恢复每组命名属性,原生编译器给名称补上开头的类选择器点。 + +| @ | name | selector | +|---|---|---| +| 1 | topnav | mq-document .site-layout .topnav | +| 2 | side_panel | mq-document .site-layout .side | +| 3 | footer | mq-document .site-layout .foot | +| 4 | card_title | mq-document .site-layout .content.cards h2 | +| 5 | card_body | mq-document .site-layout .content.cards p | +| 6 | kicker | mq-document .site-layout .main-intro blockquote | +| 7 | intro_title | mq-document .site-layout .main-intro h1 | +| 8 | lede | mq-document .site-layout .main-intro .slot-intro-content > p | +| 9 | claim | mq-document .site-layout .main-intro ul > li | +| 10 | step | mq-document .site-layout .main-intro ol > li | diff --git a/examples/web-site-zh/verify.mq.md b/examples/web-site-zh/verify.mq.md new file mode 100644 index 0000000..48e8e42 --- /dev/null +++ b/examples/web-site-zh/verify.mq.md @@ -0,0 +1,106 @@ +--- +markup: occlusion +title: 主题迁移的原生核对证据 +import: + document: lib/document.mq.md + table: lib/table.mq.md + hash: lib/hash.mq.md + result: lib/result.mq.md + theme: styles/index.mq.md + original: styles/shell.mq.md +--- + +本工具读取实际声明并编译原主题和 View 投影,不发放整个站点的通过证书,也不能替代 HTTP 与浏览器验收。它不初始化或写入业务数据库。路径和数据读取都通过固有能力完成,没有另一种语言搬运源码或计算期望值。 + +```sh +marqdo call examples/web-site-zh/verify.mq.md theme_values --effects plugin,fs.read --fs-root examples/web-site-zh --require-ok --json +``` + +## _row + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| before | map | 必填 | 原始字面声明的单条记录 | +| after | map | 必填 | 相同位置的实际投影记录 | +| keep_selector | bool | False | 令牌和关键帧还须保持地址自身 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | 允许的地址变化之外,整条声明是否相同 | + +使用`before`、`after`、`keep_selector`=False。先只排除双方同名的选择器字段,再比较完整记录,因此属性、值、可选媒体和其他已有字段都不能消失。原生字典比较不依赖键的显示顺序;值类型与内容仍必须相同,不用文本格式化掩盖差异。 + +全局令牌与动画关键帧连地址自身也必须保持,这时再比较原始记录中的选择器。本纯函数不读取文件、不编译 CSS,也不宣称相同记录已经呈现在浏览器中。不可变删键返回新记录,输入仍供地址比较和后续诊断使用。 + +我们 **left = [只排除原始结构地址](table.delete(map=`before`, key="选择器"))** 和 **right = [只排除投影结构地址](table.delete(map=`after`, key="选择器"))**。 +1. `left` != `right` + 返回 *False*,因为声明数据本身已经变化。 +1. `keep_selector` + 返回 *[全局声明同时保持地址](access(before, "选择器") == access(after, "选择器"))*。 +返回 *True*,表示只发生允许的局部地址投影。 + +## _area + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | text | 必填 | 精确的原始主题章节名称 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result,成功值为该区段实际逐行核对数 | + +输入`name`,从站点根授予 fs.read。原表继续使用选择器、属性、值和媒体的中文列名,投影保留这些键,不能为复用代码而重写原始数据。先核对实际行数,再按相同位置逐项比较,因此删除、额外添加和交换不同声明都能保留失败。 + +数据来自原生字面表读取,投影来自当前样式入口。缺失章节或非法列形态保留原生诊断;有变化则返回具体区段的失败 Result,不将空输出当作成功。累计值只来自已完成比较的每一行。令牌和关键帧采用更严格的全局地址规则,其余区段仅允许明确的选择器映射。 + +列表下标从零开始,每次只读取相同位置的投影。不能把记录先排序再比较,因为相同选择器重复声明时,原顺序本身决定 CSS 级联结果。只有一行完整通过后才递增位置,失败不会把已经比较的部分数目包装成整个区段的成功值;上层据此决定是否继续统计。 + +我们 **columns = [读取原始声明章节](document.read_table(path="styles/shell.tables.md", title=`name`))**、**rows = [保留原始行序](table.from_columns(columns=`columns`))** 和 **projected = [运行真实选择器投影](theme._table(name=`name`))**。 +1. len(`rows`) != len(`projected`) + 返回 *[保留声明数量变化](result.error(code="site.theme_rows", message=`name`, operation="theme_values"))*。 +我们 **position = 0**。 +- [按相同位置核对完整声明](for rows as row) + 我们 **actual = [读取对应投影行](table.at(xs=`projected`, i=`position`))** 和 **same = [核对允许地址之外的全部字段](_row(before=`row`, after=`actual`, keep_selector=(`name` == "vars" or `name` == "motion")))**。 + 1. not `same` + 返回 *[保留实际声明差异](result.error(code="site.theme_value", message=`name`, operation="theme_values"))*。 + 我们 **position = position + 1**,只累计真正通过的声明。 +返回 *[交出该区段的实际核对数](result.ok(value=`position`))*。 + +## theme_values + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result,包含已核对行数、原主题及实际 View CSS 的摘要 | + +从站点根授予 plugin 与 fs.read。逐区段运行实际原始表和投影的核对工具,失败时原样返回失败,不继续累加其他结果。六个区段必须全部完成,媒体、值、属性和顺序均由各自完整记录核对,令牌和关键帧还要求地址保持不变。 + +成功值含 preserved_rows、original_sha256、view_sha256,摘要来自原生编译器真实输出。新 View 地址和包装层几何会让两份 CSS 不同,不能把摘要相同当成唯一通过条件。它们只是可追踪产物身份,浏览器仍需验证色板、字体、几何、表单和当前记录。 + +命令中的 --require-ok 让失败 Result 影响进程退出,自动化不能只看外层调用完成就读取成功字段。读取与编译不写文件、不初始化数据库,也不清理用户目录。实际站点行为使用独占副本测试,服务退出后再清理。这个工具不发放整个项目的完成证书,也不会用删除失败规则的方式修复差异。 + +`areas` = + +| name | +|---| +| vars | +| motion | +| layout | +| responsive | +| chrome | +| widgets | + +我们 **count = 0**。 +- [核对每个实际原始主题区段](for areas as name) + 我们 **checked = [运行有界区段比较](_area(name=`name`))**。 + 1. not access(`checked`, "ok") + 返回 *checked*,保留真实失败。 + 我们 **count = [累计实际核对数](count + access(checked, "value"))**。 +我们 **old_css = [编译保留的原主题](original.css())**、**view_css = [编译实际 View 主题](theme.css())**、**original_sha256 = [识别真实原始 CSS](hash.sha256(text=`old_css`))** 和 **view_sha256 = [识别真实 View CSS](hash.sha256(text=`view_css`))**。 + +`evidence` = + +| preserved_rows | original_sha256 | view_sha256 | +|---|---|---| +| `count` | `original_sha256` | `view_sha256` | + +返回 *[交出真实核对和编译证据](result.ok(value=`evidence`))*。 diff --git a/examples/web-site/DEMO.md b/examples/web-site/DEMO.md index fc6bbed..0eb1b8f 100644 --- a/examples/web-site/DEMO.md +++ b/examples/web-site/DEMO.md @@ -1,40 +1,27 @@ -# Demo walkthrough (`examples/web-site`) +# Complete-site walkthrough -Aligned with The Web Conference **Demo** expectations: implemented system, -**hands-on** interaction, clear venue script, reproducible from the repo. +Start through the callable workflow in [README](README.md). For a fresh owned database the site seeds eight articles; an existing database retains its actual rows and must not be reset merely to reproduce that count. -## Run +| Step | Actual action | Evidence to inspect | +|---|---|---| +| 1 | Open Home | Original theme, Markdown introduction, badges, reading steps and summary cards | +| 2 | Open a card | Declared /post/{slug} route; full Markdown body rather than its summary | +| 3 | Read index and follow components/index | Actual parent/child tree, terminal Markdown and typed data/form/navigation resources | +| 4 | Submit New with an empty title | Actual server rule message; retry retains current CSRF | +| 5 | Submit title, slug, summary and body | New row appears on Home and in the gated desk without restart | +| 6 | Follow Login, use admin/demo, open Admin | Real route gate; separate desk navigation, no public rail, shared form and current cards | +| 7 | Return Home and log out | Session-specific links switch with the real identity; direct Admin access redirects again | +| 8 | Narrow the browser | The original 860px breakpoint puts main before the side rail without overflow | -```bash -./scripts/build-web-plugin.sh -marqdo run examples/web-site/index.mq.md +Source responsibilities remain separate. Route metadata lives in each Document, form data is [forms.tables.md](forms.tables.md), current data behavior is [components/articles](components/articles.mq.md), SEO/fonts are [components/head](components/head.mq.md), and theme source plus explicit View mapping begins at [styles/index](styles/index.mq.md). No compose mutation chain or author page HTML is required. + +The callable [verification tool](verify.mq.md) compares 412 original declaration rows and returns actual baseline/projected CSS hashes. It does not replace visual or HTTP acceptance. The real-browser suite deliberately aborts external font requests and verifies declared font families and local fallback rendering; it makes no claim about external service delivery. + +Use native file discovery for author-asset checks, excluding the explicitly generated stylesheet directory: + +```sh +target/debug/marqdo call lib/fs.mq.md find 'path="."' 'pattern="**/*.js"' 'exclude=["public/generated/**"]' --effects fs.read --fs-root examples/web-site --json +target/debug/marqdo call lib/fs.mq.md find 'path="."' 'pattern="**/*.css"' 'exclude=["public/generated/**"]' --effects fs.read --fs-root examples/web-site --json ``` -Open http://127.0.0.1:18081/ - -## Venue script (≈3 minutes) - -| Step | Action | What reviewers should notice | -|------|--------|------------------------------| -| 1 | Home | Claim badges + steps; **8 seed cards** with summaries | -| 2 | Click a card | `/post/{slug}` detail from the same table (`detail=True`) | -| 3 | Open `index.mq.md` beside the browser | Narrative = program; field/rule/route/intro tables | -| 4 | `/new` empty title → submit | Server validation from **rule table** (no author JS) | -| 5 | `/new` valid title+slug → submit | Row appears on Home and Admin | -| 6 | Top-nav **Login** (`admin` / `demo`) → **Admin** | Session gate; desk shell + create form | -| 7 | Terminal check | `find examples/web-site \( -name '*.js' -o -name '*.css' \)` → **0** | - -## Authoring contract - -| Surface | Source | -|---------|--------| -| Routes / forms / admin | GFM tables in `index.mq.md` | -| Styles | `styles/shell.mq.md` → `web.make_style` (ink / wine / gold; `shell_css=off`) | -| Intro | `| front | back | style |` → `page.compose_intro` (same bind as main) | -| Fonts | `page.head` table → Google Fonts (Noto Serif SC + Ma Shan Zheng) | -| Author `.js` / `.css` | **None** | - -## Video - -Same beats as above; English captions preferred. See thesis -`www-2027-demo/VIDEO.md` for length / upload tips. +Both author-asset lists are empty. This says nothing about generated runtime resources or native rendering internals, which are separate declared boundaries. diff --git a/examples/web-site/README.md b/examples/web-site/README.md index 719229a..a2b2cfc 100644 --- a/examples/web-site/README.md +++ b/examples/web-site/README.md @@ -1,27 +1,32 @@ -# examples/web-site +# web-site -Canonical **English** sample for `ext/web` — WWW Demo walkthrough site. +This is the complete English document-native site: Home, About, New, the gated custom desk and slug detail each declare their own route. Parents compose structure and leaves contain Markdown. The original ink/wine/gold theme, typography, particles, breakpoints and form states remain declarative, with no author business JavaScript or hand-written CSS. -**Hands-on script:** [DEMO.md](./DEMO.md) +From the checkout root, use the current source CLI and prepare the engineering and Web plugins, then call the actual serving workflow: -## Authoring rules (checkable) - -| Surface | How it is authored | -|---------|-------------------| -| Routes / forms / admin | GFM tables + class methods | -| Look-and-feel | Host shell CSS + **style tables** | -| Author business JavaScript | **none** | -| Author hand-written `.css` | **none** | - -```bash -cargo build -p marqdo_plugin_web -marqdo run examples/web-site/index.mq.md +```sh +target/debug/marqdo call skills/marqdo-dev/index.mq.md prepare_engineering --effects process.exec --fs-root . --require-ok --json +target/debug/marqdo call skills/marqdo-dev/index.mq.md prepare_web --effects plugin --fs-root . --require-ok --json +target/debug/marqdo call examples/web-site/index.mq.md serve --effects plugin,fs.write,network.write --fs-root examples/web-site --require-ok --json ``` -http://127.0.0.1:18081/ — `/about`, `/new` (validation), `/admin` (list + create). +Open http://127.0.0.1:18081/ and use admin/demo only as local fixture credentials. Default SQLite belongs to the granted site root; restart preserves existing rows. The listener blocks in this process and the caller owns shutdown. -```bash -find examples/web-site \( -name '*.js' -o -name '*.css' \) | wc -l # 0 +Read by responsibility: + +- [Site entry](index.mq.md) — declare Home and compose actual data, form, session, gate and listener resources. +- [Layout entry](components/index.mq.md) — public rail and separate desk tree; terminal leaves live in components/content. +- [Article request resources](components/articles.mq.md) — current summary cards and actual captured-slug full Markdown detail. +- [Shared form](forms.mq.md) — actual fields/rules are in forms.tables.md; failed validation retains CSRF. +- [Theme entry](styles/index.mq.md) — retain original data and project only structural addresses plus wrapper geometry. +- [Native verification tool](verify.mq.md) — actually compare 412 original layout/motion declaration rows and return real CSS identities. + +```sh +target/debug/marqdo call examples/web-site/verify.mq.md theme_values --effects plugin,fs.read --fs-root examples/web-site --require-ok --json ``` -Chinese twin: [`examples/web-site-zh/`](../web-site-zh/). +Theme output is generated at public/generated/theme.css; edit the adjacent source tables rather than that rebuildable artifact. Original Google Fonts links remain declared, with the original fallback families offline. Local browser acceptance does not claim external font-service delivery. + +The public creation form remains public, while the custom desk is role-gated. Rendering the same form in Admin does not make its submission endpoint private. HTTP regression uses owned copied sites on Tree and Bytecode; real-browser cases verify styles, publishing, detail, session navigation, logout and narrow-screen order without modifying the example's existing database. + +For the hands-on sequence see [DEMO.md](DEMO.md)。 diff --git a/examples/web-site/components/articles.mq.md b/examples/web-site/components/articles.mq.md new file mode 100644 index 0000000..ae25228 --- /dev/null +++ b/examples/web-site/components/articles.mq.md @@ -0,0 +1,32 @@ +--- +markup: occlusion +title: Current article list and slug detail +import: + component: ext/web/component/index.mq.md + query: ext/data/view.mq.md + table: lib/table.mq.md +--- + +Both views read the same application-owned articles table for each request. Cards use summaries and slug links; detail uses the complete Markdown body. These pure descriptors do not open a second database or cache startup records. Their renderer retains the native card/article classes consumed by the original theme. + +## cards + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Current article cards linked to /post/slug | + +Construct this query without effects. The serving application owns its database resource and actual request execution. Cards keep the original stable id order and use the existing summary/title/slug projection. Titles and summaries are escaped text, while the full body is intentionally reserved for detail. A publish through either mounted form becomes visible on the next request. + +We **resource = [Describe the actual current article list](query.query(source="articles", order="id", link_prefix="/post/"))**. +Return *[Place one request-time card responsibility](component.resource(value=`resource`, slot="articles"))*. + +## detail + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | First article matching the actual captured slug, rendered with full Markdown body | + +The declared /post/{slug} Document supplies the path parameter when the server resolves this query. A same-named query-string value cannot override that capture. The native renderer uses the body even when a summary is present, and it does not mutate the retained condition between requests. Missing database resources remain errors; a missing record remains an empty result under the existing query contract. + +We **condition = [Keep a native record rather than a one-column list](table.put(in=None, at="slug", value="{slug}"))** and **resource = [Describe full-body slug detail](query.query(source="articles", where=`condition`, detail=True, limit=1))**. +Return *[Place the actual requested article](component.resource(value=`resource`, slot="article"))*. diff --git a/examples/web-site/components/content/about.md b/examples/web-site/components/content/about.md new file mode 100644 index 0000000..d1ddb45 --- /dev/null +++ b/examples/web-site/components/content/about.md @@ -0,0 +1,9 @@ +> about + +# About + +Documentation and the deployed site stay one .mq.md artifact. Layout and theme are GFM style tables in styles/shell.mq.md — structure without hand-written CSS or business JavaScript. + +- docs = program +- server-side rules +- hands-on diff --git a/examples/web-site/components/content/desk-footer.md b/examples/web-site/components/content/desk-footer.md new file mode 100644 index 0000000..5c191a2 --- /dev/null +++ b/examples/web-site/components/content/desk-footer.md @@ -0,0 +1 @@ +[Site](/) · [Admin](/admin) · [Logout](/admin/logout) diff --git a/examples/web-site/components/content/desk.md b/examples/web-site/components/content/desk.md new file mode 100644 index 0000000..891f89d --- /dev/null +++ b/examples/web-site/components/content/desk.md @@ -0,0 +1,9 @@ +> desk · you are in admin + +# Admin + +This is the management desk (login required): same articles schema as the public site, assembled as list + create form — not a separate SPA. Use Site in the topnav to return, or Logout to end the session. + +- login-gated +- table-declared +- create + list diff --git a/examples/web-site/components/content/footer.md b/examples/web-site/components/content/footer.md new file mode 100644 index 0000000..eae8fb2 --- /dev/null +++ b/examples/web-site/components/content/footer.md @@ -0,0 +1 @@ +[Marqdo](https://www.marqdo.com/) · [Source](https://github.com/cflmy/marqdo) diff --git a/examples/web-site/components/content/home.md b/examples/web-site/components/content/home.md new file mode 100644 index 0000000..fcba3fa --- /dev/null +++ b/examples/web-site/components/content/home.md @@ -0,0 +1,13 @@ +> WWW demo · tables as the full stack + +# Marqdo + +One executable Markdown artifact declares routes, forms, admin pages, and styles — no hand-written business JavaScript, no author .css. Click a card for the full article, then try the three steps below. + +- 0 author JS +- 0 author .css +- GFM tables + +1. Click any card — /post/{slug} opens the detail page from the same articles table. +2. Open [New](/new) and submit with an empty title (validation from a rule table). +3. Open top-nav **Login** (admin / demo), then **Admin** — gated desk with create form + list. diff --git a/examples/web-site/components/content/new.md b/examples/web-site/components/content/new.md new file mode 100644 index 0000000..8863dd1 --- /dev/null +++ b/examples/web-site/components/content/new.md @@ -0,0 +1,5 @@ +> form · try validation + +# New article + +Leave Title empty and submit — the error comes from the rule table, not client JavaScript. Then fill title, slug, and summary to create a row shared with Admin and the card grid. diff --git a/examples/web-site/components/content/post.md b/examples/web-site/components/content/post.md new file mode 100644 index 0000000..7ca6af1 --- /dev/null +++ b/examples/web-site/components/content/post.md @@ -0,0 +1 @@ +> article · table-bound detail diff --git a/examples/web-site/components/desk.mq.md b/examples/web-site/components/desk.mq.md index ef726b0..3cffe45 100644 --- a/examples/web-site/components/desk.mq.md +++ b/examples/web-site/components/desk.mq.md @@ -1,30 +1,40 @@ --- markup: occlusion -title: components/desk -description: Admin desk chrome — brand reads Admin; no public side rail. +title: Administration navigation and footer +import: + component: ext/web/component/index.mq.md + fs: lib/fs.mq.md --- +The custom desk keeps its own brand and closing links, and omits the public side rail. Authentication remains the serving entry's responsibility. Neither constructing these nodes nor hiding their links can authorize a visitor to the administration route. + ## nav -`nav` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Desk navigation using the real current session | -| front | back | style | media | when | -|-------|------|-------|-------|------| -| Admin | /admin | | | | -| Site | / | | | | -| New | /new | | | | -| Logout | /admin/logout | | | auth | +Construction needs no effects. The first link preserves Admin as the operator's current context, followed by Site, New and Logout. Only the logout link is conditional, matching the original navigation. The entire desk is separately gated, and the actual logout destination remains a native session route. Returned nodes keep their structured resource value so the parent can place them without HTML strings. -*`nav`* +`items` = + +| @ | label | href | when | +|---|---|---|---| +| 1 | Admin | /admin | | +| 2 | Site | / | | +| 3 | New | /new | | +| 4 | Logout | /admin/logout | auth | + +We **resource = [Describe the desk's current navigation](component.navigation(items=`items`))**. +Return *[Keep the same navigation fragment slot](component.resource(value=`resource`, slot="nav"))*. ## foot -`foot` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Desk footer with terminal Markdown return and logout links | -| front | back | style | -|-------|------|-------| -| Site | / | | -| Admin | /admin | | -| Logout | /admin/logout | | +Read this leaf with fs.read under the site root. The route gate has already decided access before the renderer resolves this component. Site and Admin retain their return destinations, while Logout ends the session only when followed. The footer has one content responsibility and no internal layout to split further; the parent owns its placement and the original theme owns its appearance. -*`foot`* +We **text = [Read the desk's terminal closing links](fs.read_text(path="components/content/desk-footer.md"))** and **leaf = [Retain ordinary Markdown content](component.markdown(text=`text`, slot="footer-content"))**. +Return *[Place it in the semantic desk footer](component.wrap(children=`leaf`, kind="footer", slot="footer", style="foot"))*. diff --git a/examples/web-site/components/foot.mq.md b/examples/web-site/components/foot.mq.md index 442c67e..d8c4fd3 100644 --- a/examples/web-site/components/foot.mq.md +++ b/examples/web-site/components/foot.mq.md @@ -1,15 +1,21 @@ --- markup: occlusion +title: Public footer Markdown leaf +import: + component: ext/web/component/index.mq.md + fs: lib/fs.mq.md --- +The public footer is one simple set of project and source links. It has no independent internal columns, so its terminal Markdown is the stopping point for decomposition. The parent controls where it appears; the theme supplies its existing footer appearance. + ## foot -`foot` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Semantic footer containing its terminal Markdown links | -| front | back | style | -|-------|------|-------| -| Marqdo | https://www.marqdo.com/ | | -| Source | https://github.com/cflmy/marqdo | | +Read with fs.read relative to the granted site root. The leaf retains the original project and source destinations; it does not query business rows or expose session credentials. Changing wording belongs in content/footer.md, while changing layout belongs in the parent. This module never renders a child to HTML before composition. -*`foot`* +We **text = [Read the terminal project links](fs.read_text(path="components/content/footer.md"))** and **leaf = [Keep the links in Markdown](component.markdown(text=`text`, slot="footer-content"))**. +Return *[Preserve the footer's semantic region](component.wrap(children=`leaf`, kind="footer", slot="footer", style="foot"))*. diff --git a/examples/web-site/components/head.mq.md b/examples/web-site/components/head.mq.md new file mode 100644 index 0000000..ce4c1b4 --- /dev/null +++ b/examples/web-site/components/head.mq.md @@ -0,0 +1,46 @@ +--- +markup: occlusion +title: SEO, font and theme resource declarations +import: + component: ext/web/component/index.mq.md + head: ext/web/head.mq.md +--- + +This leaf preserves the original site metadata and Google Fonts resource addresses. It declares links, never fetches them during assembly. Theme CSS is explicitly generated from style tables by serve and mounted at the declared static path. + +## nodes + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| homepage | bool | False | Include the original home-only SEO rows | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Pure head resource for real SEO, fonts and the generated theme | + +Use `homepage`=False without effects during page assembly. Only the home Document opts into its original SEO rows; fonts and the theme remain shared. Metadata remains key/value records and the links retain native rel/href/crossorigin fields. The renderer collects them into the actual head in both preview and HTTP output, deduplicating equal declarations. They do not become body placeholders or fragment markup. + +Font delivery still depends on browser access to the external font service; the page uses its declared fallbacks when unavailable. Declaring the theme path does not build it or prove it exists. The serving workflow compiles and writes that exact file before opening a listener, while a static preview caller owns asset preparation. + +`meta` = + +| @ | key | value | +|---|---|---| +| 1 | description | Tables as the full stack — Marqdo Web demo with zero author business JavaScript. | +| 2 | og:type | website | +| 3 | og:title | Marqdo Web Site | + +`links` = + +| @ | rel | href | crossorigin | +|---|---|---|---| +| 1 | preconnect | https://fonts.googleapis.com | | +| 2 | preconnect | https://fonts.gstatic.com | anonymous | +| 3 | stylesheet | https://fonts.googleapis.com/css2?family=Great+Vibes&family=Noto+Sans+SC:wght@300;400;500;700&family=Noto+Serif+SC:wght@400;600&display=swap | | +| 4 | stylesheet | /static/generated/theme.css | | + +We **selected_meta = None** because non-home pages retain only their originally shared head links. +1. `homepage` + We **selected_meta = meta** to retain the original home-specific SEO. +We **resource = [Retain actual metadata and native head links](head.resource(meta=`selected_meta`, links=`links`))**. +Return *[Place one pure head resource alongside the layout](component.resource(value=`resource`, slot="document-head"))*. diff --git a/examples/web-site/components/index.mq.md b/examples/web-site/components/index.mq.md new file mode 100644 index 0000000..528080c --- /dev/null +++ b/examples/web-site/components/index.mq.md @@ -0,0 +1,37 @@ +--- +markup: occlusion +title: Public and desk layout entry +import: + component: ext/web/component/index.mq.md + nav: nav.mq.md + side: side.mq.md + foot: foot.mq.md + desk: desk.mq.md + head: head.mq.md + table: lib/table.mq.md +--- + +This parent declares one site frame. The public tree has navigation, side/main and footer; the desk has its own navigation and footer with no public rail. Children own Markdown or typed request resources. Geometry is declared here and compiled from the original theme tables, never hidden inside a rendered HTML string. + +## frame + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| body | list | required | Page-owned main nodes, retaining nested resources | +| management | bool | False | Select the gated custom desk frame without a public side rail | +| homepage | bool | False | Keep original home SEO scoped to Home | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Recursive site structure and pure head resources | + +Use `body`, `management`=False and `homepage`=False. Child navigation keeps its actual session conditions; this function does not authenticate or authorize a visitor. The desk route is separately gated in serve, so choosing its frame cannot grant access. Footer content is already a simple Markdown responsibility and needs no further internal layout. + +The stable slots nav, sidebar, main and footer retain fragment identities. Native resource wrappers remain in the View tree; the theme transparently places their semantic children in the original grid. The class is-desk is local to this frame, replacing the old whole-body mutation. The theme projection keeps its original rules and values under that explicit scope. Pure head resources are collected into the real document head. + +We **top = [Assemble public navigation](nav.nav())** and **rail = [Assemble the public side rail](side.side())** and **bottom = [Read the public Markdown footer](foot.foot())** and **classes = "site-layout has-sidebar"**. +1. `management` + We **top = [Use the desk's own navigation](desk.nav())** and **rail = [Keep the desk free of the public rail](table.empty_list())** and **bottom = [Read the desk return links](desk.foot())** and **classes = "site-layout no-sidebar is-desk"**. +We **main = [Retain the supplied main responsibility](component.wrap(children=`body`, kind="section", slot="main", style="main"))** and **children = [Keep navigation before the public rail](table.concat(a=`top`, b=`rail`))** and **children = [Keep main content after navigation](table.concat(a=`children`, b=`main`))** and **children = [Finish with the selected footer](table.concat(a=`children`, b=`bottom`))**. +We **frame = [Declare the shared named layout region](component.wrap(children=`children`, kind="section", slot="site", style=`classes`))** and **resources = [Retain actual SEO, fonts and compiled theme](head.nodes(homepage=`homepage`))**. +Return *[Keep head declarations alongside the recursive frame](table.concat(a=`resources`, b=`frame`))*. diff --git a/examples/web-site/components/intro.mq.md b/examples/web-site/components/intro.mq.md new file mode 100644 index 0000000..7356999 --- /dev/null +++ b/examples/web-site/components/intro.mq.md @@ -0,0 +1,26 @@ +--- +markup: occlusion +title: Terminal introduction component +import: + component: ext/web/component/index.mq.md + fs: lib/fs.mq.md +--- + +The introduction ends in one ordinary Markdown responsibility: category, title, explanation, feature bullets and reading steps. Markdown provides that hierarchy directly; the theme selects those semantic elements. Page geometry stays in the parent frame, and no content row uses an HTML shell or the removed intro-binding dialect. + +## nodes + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | text | required | Author-selected home, about, new, desk or post Markdown leaf | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | One semantic introduction region around the actual Markdown leaf | + +Use `name` under the granted site root with fs.read. The relative leaf path is selected by the authored Document, never a request parameter. Missing leaves retain the native file diagnostic rather than displaying a copied fallback. Reading the leaf does not execute its emphasis or links as Marqdo statements; its content is data for the native Markdown renderer. + +Each leaf is already simple enough for Markdown: blockquote category, heading, paragraphs, bullets and ordered steps. A change that adds independent internal geometry should split again. Style selectors preserve the original typography, badges and step panel while the page still reads as a document. + +We **path = "components/content/" + name + ".md"** and **text = [Read this introduction's actual content](fs.read_text(path=`path`))** and **leaf = [Retain its simple Markdown hierarchy](component.markdown(text=`text`, slot="intro-content"))**. +Return *[Keep the introduction as a semantic region](component.wrap(children=`leaf`, kind="section", slot="intro", style="main-intro"))*. diff --git a/examples/web-site/components/nav.mq.md b/examples/web-site/components/nav.mq.md index 39c199d..8cdc28c 100644 --- a/examples/web-site/components/nav.mq.md +++ b/examples/web-site/components/nav.mq.md @@ -1,20 +1,32 @@ --- markup: occlusion +title: Session-aware nav component +import: + component: ext/web/component/index.mq.md --- +This module owns only the selected navigation responsibility. Its labels and destinations retain the original site order. The session-dependent rows are a typed navigation resource because their visibility must follow each request rather than a startup snapshot. + ## nav -Brand first, then demo routes. Guest sees **Login**; signed-in sees **Admin** + **Logout**. +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | One typed navigation resource with stable fragment identity | -`nav` = +Construction is pure and does not log in, log out or register a route. Empty when values keep links visible; guest and auth use the actual session supplied by the server. The resource renderer retains native navigation classes for the existing theme. Hiding Admin never protects its URL: the serving entry separately binds a real /admin role gate. -| front | back | style | media | when | -|-------|------|-------|-------|------| -| Marqdo | / | | | | -| About | /about | | | | -| New | /new | | | | -| Login | /login | | | guest | -| Admin | /admin | | | auth | -| Logout | /admin/logout | | | auth | +The parent places this region and owns its grid relationship. Edit labels here and update declared routes when changing a destination; do not concatenate an HTML navigation string or return an obsolete front/back binding table. -*`nav`* +`items` = + +| @ | label | href | when | +|---|---|---|---| +| 1 | Marqdo | / | | +| 2 | About | /about | | +| 3 | New | /new | | +| 4 | Login | /login | guest | +| 5 | Admin | /admin | auth | +| 6 | Logout | /admin/logout | auth | + +We **resource = [Describe current-session navigation](component.navigation(items=`items`, region="nav"))**. +Return *[Keep this region as a typed View resource](component.resource(value=`resource`, slot="nav"))*. diff --git a/examples/web-site/components/side.mq.md b/examples/web-site/components/side.mq.md index fdbcf78..a4e1cca 100644 --- a/examples/web-site/components/side.mq.md +++ b/examples/web-site/components/side.mq.md @@ -1,19 +1,31 @@ --- markup: occlusion +title: Session-aware sidebar component +import: + component: ext/web/component/index.mq.md --- +This module owns only the selected navigation responsibility. Its labels and destinations retain the original site order. The session-dependent rows are a typed navigation resource because their visibility must follow each request rather than a startup snapshot. + ## side -Hands-on demo checklist (links only — no JS). +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | One typed navigation resource with stable fragment identity | -`side` = +Construction is pure and does not log in, log out or register a route. Empty when values keep links visible; guest and auth use the actual session supplied by the server. The resource renderer retains native navigation classes for the existing theme. Hiding Admin never protects its URL: the serving entry separately binds a real /admin role gate. -| front | back | style | media | when | -|-------|------|-------|-------|------| -| 1. Home | / | | | | -| 2. New form | /new | | | | -| 3. Login | /login | | | guest | -| 3. Admin | /admin | | | auth | -| About | /about | | | | +The parent places this region and owns its grid relationship. Edit labels here and update declared routes when changing a destination; do not concatenate an HTML navigation string or return an obsolete front/back binding table. -*`side`* +`items` = + +| @ | label | href | when | +|---|---|---|---| +| 1 | 1. Home | / | | +| 2 | 2. New form | /new | | +| 3 | 3. Login | /login | guest | +| 4 | 3. Admin | /admin | auth | +| 5 | About | /about | | + +We **resource = [Describe current-session navigation](component.navigation(items=`items`, region="sidebar"))**. +Return *[Keep this region as a typed View resource](component.resource(value=`resource`, slot="sidebar"))*. diff --git a/examples/web-site/db/articles.mq.md b/examples/web-site/db/articles.mq.md index 89788b8..7ba5bb6 100644 --- a/examples/web-site/db/articles.mq.md +++ b/examples/web-site/db/articles.mq.md @@ -1,36 +1,32 @@ --- markup: occlusion +title: Article schema and seed handbook +import: + document: lib/document.mq.md --- +This file explains callable use; [articles.tables.md](articles.tables.md) holds the readable literal tables. Set --fs-root to the site directory and grant fs.read. Reading returns data without running prose, opening a database or changing a page. + ## schema -`fields` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Native table value, preserving literal types and column geometry | -| name | type | nullable | -|------|------|----------| -| id | integer | false | -| title | text | false | -| slug | text | false | -| summary | text | true | -| body | text | true | +Declare article fields, native types and nullability. The initializer consumes this table to ensure structure; it must not guess a migration or erase existing rows. -*`fields`* +Call independently with fs.read on the site root. The section must match exactly and uniquely. Malformed tables or dynamic expressions retain native document diagnostics. A returned style declaration still needs compilation; returned database data still needs an explicit initializer. This value is neither HTML nor an applied browser effect. + +Return *[读取 schema 的实际字面表](document.read_table(path="db/articles.tables.md", title="schema"))*. ## seed -Longer demo rows — cards show summary; /post/{slug} shows full body (Markdown). +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Native table value, preserving literal types and column geometry | -`rows` = +Provide initial demonstration articles with their original ids, stable slugs and content. Insert only after the database initializer confirms an empty table; this reader never changes existing articles. -| id | title | slug | summary | body | -|----|-------|------|---------|------| -| 1 | Hello Marqdo | hello-marqdo | A runnable Markdown file is both the site docs and the deployed app — tables declare routes, forms, and styles. | "Marqdo treats an .mq.md file as an executable document. The narrative you read in the editor is the same artifact the server runs: GFM tables become schema, forms, navigation, and CSS. This demo shows that contract end-to-end — open New, trigger a rule-table validation error, then publish a row that appears on Home and Admin without any author JavaScript." | -| 2 | Tables as the full stack | tables-full-stack | Schema, forms, routes, admin pages, and theme tokens share one tabular dialect instead of a JS/CSS split. | "Most stacks split concerns across languages: SQL or an ORM for data, a form library for input, a router for URLs, and a stylesheet for look. Marqdo collapses those surfaces into GFM tables with the same geometry authors already use for documentation. Field tables, rule tables, bind tables, and style tables are not metaphors — they are the runtime. The result is a site you can skim as prose and execute as a program." | -| 3 | Zero author JS and CSS | zero-author-js-css | Business logic stays in Markdown; appearance is style tables plus the host shell — no hand-written business JS or author .css. | "Author business JavaScript is zero by construction: validation runs from rule tables on the server, and list/detail pages are bind tables rendered by the host. Author .css files are also unnecessary when theme tokens live in property/value tables assembled by make_style. The demo turns shell_css=off so only those declared styles paint the page — proving the claim for a conference audience." | -| 4 | Card to detail in one bind | card-to-detail | List cards bind href to slug; a /post/{slug} route plus detail=True opens the full article. | "Click any card on the home page. The list bind exposes href from articles.slug, and link_prefix prefixes /post/. The detail page reuses the same table with a query slug = {slug} and page.detail so the first row renders as a full article — title and Markdown body — instead of a card grid. That is the same pattern used by larger Marqdo sites such as 求道量子." | -| 5 | Style tables not stylesheets | style-tables | Named style tables (kicker, intro_title, card_title) bind through the third column of every layout table. | "Intro, cards, and chrome all use the bind shape front/back/style. The style column points at a named property table in styles/shell.mq.md. When compose_intro or compose_main runs, those tables become CSS classes on the page. Authors never open a .css file to tweak the demo look — they edit readable Markdown tables that stay next to the copy they style." | -| 6 | Forms from field and rule tables | forms-from-tables | Empty title on New fails from the rule table; a valid submit inserts a row shared with Admin. | "The New and Admin pages mount the same form object: a field table declares labels and types, a rule table declares required and max constraints with messages. Submit with an empty title and the error is server-side, not a client script. Fill a title and slug, submit again, and the row shows up in the card grid and under Admin — one schema, two surfaces, zero author JS." | -| 7 | Seed data is documentation | seed-is-docs | These paragraphs were written as a GFM seed table — the demo content is part of the program. | "Seed rows live beside the schema in db/articles.mq.md. On first boot the host inserts them when the articles table is empty. That means the demo narrative is versioned with the code: longer summaries for cards, fuller bodies for detail pages, and slugs that make deep links stable. Reviewers can open the seed table and see exactly what the venue site will show." | -| 8 | Why this Demo matters | why-demo-matters | WWW Demo needs a hands-on artifact reviewers can run, click, and compare to source in minutes. | "A Demo track asks for an implemented system, not a slide-only pitch. This sample is intentionally small: one SQLite table, a handful of routes, and a literary shell — yet it covers the paper claim (tables as the full stack) with a three-step script. Clone the repo, run the web-site sample, click a card, break a form, then open index.mq.md beside the browser. That loop is the publication." | +Call independently with fs.read on the site root. The section must match exactly and uniquely. Malformed tables or dynamic expressions retain native document diagnostics. A returned style declaration still needs compilation; returned database data still needs an explicit initializer. This value is neither HTML nor an applied browser effect. -*`rows`* +Return *[读取 seed 的实际字面表](document.read_table(path="db/articles.tables.md", title="seed"))*. diff --git a/examples/web-site/db/articles.tables.md b/examples/web-site/db/articles.tables.md new file mode 100644 index 0000000..7b62d3f --- /dev/null +++ b/examples/web-site/db/articles.tables.md @@ -0,0 +1,30 @@ +# Article data + +Literal article schema and demonstration content. Reading these tables does not open a database or insert rows. Follow articles.mq.md for callable use; the database initializer decides whether seeding is appropriate. + +## schema + +Field definitions for the native database initializer; nullable values remain booleans. + +| name | type | nullable | +|------|------|----------| +| id | integer | false | +| title | text | false | +| slug | text | false | +| summary | text | true | +| body | text | true | + +## seed + +Initial demonstration records in their original column-oriented shape; ids and stable slugs retain their meaning. + +| id | title | slug | summary | body | +|----|-------|------|---------|------| +| 1 | Hello Marqdo | hello-marqdo | A runnable Markdown file is both the site docs and the deployed app — tables declare routes, forms, and styles. | "Marqdo treats an .mq.md file as an executable document. The narrative you read in the editor is the same artifact the server runs: GFM tables become schema, forms, navigation, and CSS. This demo shows that contract end-to-end — open New, trigger a rule-table validation error, then publish a row that appears on Home and Admin without any author JavaScript." | +| 2 | Tables as the full stack | tables-full-stack | Schema, forms, routes, admin pages, and theme tokens share one tabular dialect instead of a JS/CSS split. | "Most stacks split concerns across languages: SQL or an ORM for data, a form library for input, a router for URLs, and a stylesheet for look. Marqdo collapses those surfaces into GFM tables with the same geometry authors already use for documentation. Field tables, rule tables, bind tables, and style tables are not metaphors — they are the runtime. The result is a site you can skim as prose and execute as a program." | +| 3 | Zero author JS and CSS | zero-author-js-css | Business logic stays in Markdown; appearance is style tables plus the host shell — no hand-written business JS or author .css. | "Author business JavaScript is zero by construction: validation runs from rule tables on the server, and list/detail pages are bind tables rendered by the host. Author .css files are also unnecessary when theme tokens live in property/value tables assembled by make_style. The demo turns shell_css=off so only those declared styles paint the page — proving the claim for a conference audience." | +| 4 | Card to detail in one bind | card-to-detail | List cards bind href to slug; a /post/{slug} route plus detail=True opens the full article. | "Click any card on the home page. The list bind exposes href from articles.slug, and link_prefix prefixes /post/. The detail page reuses the same table with a query slug = {slug} and page.detail so the first row renders as a full article — title and Markdown body — instead of a card grid. That is the same pattern used by larger Marqdo sites such as 求道量子." | +| 5 | Style tables not stylesheets | style-tables | Named style tables (kicker, intro_title, card_title) bind through the third column of every layout table. | "Intro, cards, and chrome all use the bind shape front/back/style. The style column points at a named property table in styles/shell.mq.md. When compose_intro or compose_main runs, those tables become CSS classes on the page. Authors never open a .css file to tweak the demo look — they edit readable Markdown tables that stay next to the copy they style." | +| 6 | Forms from field and rule tables | forms-from-tables | Empty title on New fails from the rule table; a valid submit inserts a row shared with Admin. | "The New and Admin pages mount the same form object: a field table declares labels and types, a rule table declares required and max constraints with messages. Submit with an empty title and the error is server-side, not a client script. Fill a title and slug, submit again, and the row shows up in the card grid and under Admin — one schema, two surfaces, zero author JS." | +| 7 | Seed data is documentation | seed-is-docs | These paragraphs were written as a GFM seed table — the demo content is part of the program. | "Seed rows live beside the schema in db/articles.mq.md. On first boot the host inserts them when the articles table is empty. That means the demo narrative is versioned with the code: longer summaries for cards, fuller bodies for detail pages, and slugs that make deep links stable. Reviewers can open the seed table and see exactly what the venue site will show." | +| 8 | Why this Demo matters | why-demo-matters | WWW Demo needs a hands-on artifact reviewers can run, click, and compare to source in minutes. | "A Demo track asks for an implemented system, not a slide-only pitch. This sample is intentionally small: one SQLite table, a handful of routes, and a literary shell — yet it covers the paper claim (tables as the full stack) with a three-step script. Clone the repo, run the web-site sample, click a card, break a form, then open index.mq.md beside the browser. That loop is the publication." | diff --git a/examples/web-site/db/index.mq.md b/examples/web-site/db/index.mq.md index 3b5731e..7b8750f 100644 --- a/examples/web-site/db/index.mq.md +++ b/examples/web-site/db/index.mq.md @@ -1,22 +1,37 @@ --- markup: occlusion -title: db/index -description: Open sqlite, init articles, seed once. +title: web-site database lifecycle import: - web: ext/web/web.mq.md + data: ext/data/db.mq.md articles: articles.mq.md fs: lib/fs.mq.md + text: lib/text.mq.md --- +The database entry connects schema and literal seed leaves to the actual data resource. It no longer uses the removed web database constructor. Grant fs.write and plugin with the site directory as --fs-root; the SQLite path is resolved through that native root rather than the process working directory. + ## open -**store = > web.db url="sqlite:data/site.db"** -**fields = > articles.schema** -> `store`.init name=articles fields=`fields` -**rows = > store.select table="articles" limit=1** -1. `rows` - *store* -2. * - **seed = > articles.seed** - > `store`.insert table=articles rows=`seed` - *store* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | any | None | None selects data/site.db under the site root; tests provide a disposable explicit URI | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Initialized articles database resource with existing rows preserved | + +Use `url`=None to open the site's local database. Create the default data directory through native file operations, then resolve the actual SQLite filename within the granted root. An explicit SQLite path goes through the same root and symlink checks before the native database resource receives it. Other supported database URIs retain their resource-specific backend contract; they are not sandboxed by filesystem permissions. + +The schema reader preserves native field types and nullability. Initialization ensures the table exists, queries one row to distinguish an empty table, and inserts the original demonstration content only into an empty table. An existing or partly populated table is kept unchanged. This is not a column migrator, data repair tool or reason to delete a user's articles. A native connection, schema or insert diagnostic stops the caller before it starts serving. + +For isolated verification choose a caller-owned temporary SQLite file and copy the article data leaf under that granted site root. Keep the returned resource in the same program for subsequent queries. Close the process before cleaning its owned directory; do not run tests against the example's existing data directory. + +1. `url` == None + We **[Create only the site's default data directory](fs.make_dirs(path="data"))** and **file = [Resolve its database filename](fs.resolve(path="data/site.db"))** and **url = "sqlite:" + file**. +1. [The explicit or default URI selects SQLite](text.starts_with(text=`url`, prefix="sqlite:")) + We **file = [Read the selected SQLite path](text.replace(text=`url`, old="sqlite:", new="", count=1))** and **file = [Apply the native file-root policy](fs.resolve(path=`file`))** and **url = "sqlite:" + file**. +We **store = [Open the selected actual database resource](data.db(url=`url`))** and **fields = [Read the documented article schema](articles.schema())**. +We **[Ensure the table without clearing it](> `store`.init name="articles" fields=`fields`)** and **existing = [Check whether business records already exist](> `store`.select table="articles" limit=1)**. +1. not `existing` + We **seed = [Read the original demonstration data](articles.seed())** and **[Seed only the empty article table](> `store`.insert table="articles" rows=`seed`)**. +Once the selected database is ready, return *store* for the site's resource bindings. diff --git a/examples/web-site/forms.mq.md b/examples/web-site/forms.mq.md new file mode 100644 index 0000000..70dbf59 --- /dev/null +++ b/examples/web-site/forms.mq.md @@ -0,0 +1,24 @@ +--- +markup: occlusion +title: Shared article form and server validation +import: + form: ext/data/form.mq.md + document: lib/document.mq.md +--- + +New and Admin place the same article form reference. The serving entry mounts this resource once at article; rendering, validation and actual database submission therefore share field definitions and rules. The public creation path remains public as in the original demonstration, while direct access to the custom desk is role-gated. + +## article + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Insert form with title, slug, summary, Markdown body and original validation limits | + +Grant plugin and fs.read on the site root before mounting. The adjacent literal leaf keeps field/rule data readable without turning the workflow into a data dump. Title and slug are required, with original maxima of 120 and 80 characters. Summary and body remain optional, limited to 500 and 8000 characters. These are server rules even if a caller bypasses browser constraints. Constructing the resource writes no rows and grants no authentication. + +The field types remain text and textarea, retaining the original schema behavior. A rejected submission returns field messages and current CSRF for retry; success returns to the home list, where the current-query resource observes the new row. Keep every updated resource value before mounting; using an older value would lose attached fields or rules. + +We **fields = [Read the actual literal field contract](document.read_table(path="forms.tables.md", title="fields"))** and **rules = [Read the actual literal validation rules](document.read_table(path="forms.tables.md", title="rules"))**. + +We **selected = [Create the actual article insertion resource](form.form(table="articles"))** and **selected = [Attach the readable field records](> `selected`.fields fields=`fields`)** and **selected = [Attach the actual server rules](> `selected`.rules rules=`rules`)**. +Return *[Keep submission copy and its successful return target](> `selected`.labels submit="Publish" cancel="Cancel" cancel_href="/")*. diff --git a/examples/web-site/forms.tables.md b/examples/web-site/forms.tables.md new file mode 100644 index 0000000..bb62358 --- /dev/null +++ b/examples/web-site/forms.tables.md @@ -0,0 +1,27 @@ +# Article form data + +The callable contract is forms.mq.md. These are literal records, not another program or a second submission implementation. Fields map to the existing articles schema; native rendering and server validation consume the same records. + +## fields + +Title and slug are required. Summary and body remain optional, with their original input types. + +| @ | name | label | type | required | +|---|---|---|---|---| +| 1 | title | Title | text | True | +| 2 | slug | Slug | text | True | +| 3 | summary | Summary | textarea | False | +| 4 | body | Body | textarea | False | + +## rules + +These are the original server rules and error messages; browser hints do not replace them. + +| @ | field | rule | message | +|---|---|---|---| +| 1 | title | required | Title is required | +| 2 | title | max:120 | Title is too long | +| 3 | slug | required | Slug is required | +| 4 | slug | max:80 | Slug is too long | +| 5 | summary | max:500 | Summary is too long | +| 6 | body | max:8000 | Body is too long | diff --git a/examples/web-site/index.mq.md b/examples/web-site/index.mq.md index f837f8a..57d1f25 100644 --- a/examples/web-site/index.mq.md +++ b/examples/web-site/index.mq.md @@ -1,223 +1,60 @@ --- markup: occlusion -title: web-site -description: >- - WWW Demo sample — GFM tables for shell, schema, forms, styles, and admin. - Author business JavaScript: none. Author hand-written .css: none. +type: web +view: main +route: / +title: Marqdo Web Site import: + layout: components/index.mq.md + intro: components/intro.mq.md + articles: components/articles.mq.md + database: db/index.mq.md + forms: forms.mq.md + theme: styles/index.mq.md web: ext/web/web.mq.md - shell: styles/shell.mq.md - nav: components/nav.mq.md - side: components/side.mq.md - foot: components/foot.mq.md - desk: components/desk.mq.md - articles: db/articles.mq.md - db: db/index.mq.md + form: ext/data/form.mq.md + auth: ext/security/auth.mq.md + fs: lib/fs.mq.md + table: lib/table.mq.md --- -# main +This entry is the executable site handbook. Follow components/index for public and administration geometry, then Markdown leaves, current article resources, the form and database. Five declared Documents retain Home, About, New, Admin and slug detail. Session navigation and server access policy remain separate; the custom desk does not enable the unrelated native administration landing page. -This Markdown file is both the **site documentation** and the **running app**. -Routes, forms, validation, admin pages, and look-and-feel are **GFM tables** — -no hand-written business JavaScript and no author .css file. +## main -`home` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Public frame containing the readable introduction and current article cards | -| src | style | -|-----|-------| -| nav.`nav` | shell.`topnav` | -| side.`side` | shell.`side_panel` | -| foot.`foot` | shell.`footer` | +Startup assembly reads terminal Markdown and constructs a typed query, without querying or initializing a database. The retained application resource supplies current articles at request time. Shared layout preserves navigation, side rail, footer, SEO, fonts and the compiled literary theme. Follow each imported responsibility rather than rebuilding the complete page here. -Public shell (nav + side + foot). Desk shell drops the public side rail. +We **introduction = [Read the terminal home introduction](intro.nodes(name="home"))** and **cards = [Describe the current article cards](articles.cards())** and **body = [Keep the introduction before the records](table.concat(a=`introduction`, b=`cards`))**. +Return *[Place home inside the shared public frame](layout.frame(body=`body`, homepage=True))*. -`desk_shell` = +## serve -| src | style | -|-----|-------| -| desk.`nav` | shell.`topnav` | -| desk.`foot` | shell.`footer` | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| root | text | "examples/web-site" | Explicit site discovery directory from the checkout | +| port | number | 18081 | Loopback demonstration port | +| url | any | None | None uses retained site-root SQLite; tests supply an owned URI | -List cards: summary + slug link (click through to detail). +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Blocking listener after real data, form, authentication and desk policy bindings | -`index` = +Use `root`="examples/web-site", `port`=18081 and `url`=None from the checkout with --fs-root examples/web-site and plugin,fs.write,network.write. Database initialization preserves existing rows and seeds only an empty table. The original declaration leaves remain unchanged; styles/index projects their selectors onto the recursive View layout and restores the named style properties previously attached by removed compose APIs. -| front | back | style | -|-------|------|-------| -| title | articles.`articles`.title | shell.`card_title` | -| body | articles.`articles`.summary | shell.`card_body` | -| href | articles.`articles`.slug | | +Theme output is explicitly generated under public/generated before discovery. Preparation reads declared Documents but opens no listener. Mount the same public article form used by New and the desk, attach local fixture authentication, and protect the actual /admin path before listening. Keep every returned application. The admin/demo credentials are local demonstration data; replace the user store and network policy for a real deployment. Shutdown belongs to the supervising caller, not a hidden background process. -Detail bind for /post/{slug} (full Markdown body). +We **store = [Initialize the retained article database](database.open(url=`url`))** and **css = [Compile the actual View theme projection](theme.css())** and **[Create only the explicit generated resource directory](fs.make_dirs(path="public/generated"))** and **[Write the compiled theme through native IO](fs.atomic_write(path="public/generated/theme.css", text=`css`))**. +We **app = [Discover the five declared site Documents](web.prepare(root=`root`, host="127.0.0.1", port=`port`, db=`store`, static_dir="public"))** and **article = [Construct one shared server-validation resource](forms.article())** and **app = [Mount the public article submission explicitly](form.mount(app=`app`, id="article", form=`article`))**. -`detail` = +`users` = -| front | back | style | -|-------|------|-------| -| title | articles.`articles`.title | shell.`card_title` | -| body | articles.`articles`.body | | +| @ | username | password | role | +|---|---|---|---| +| 1 | admin | demo | admin | -`by_slug` = - -| field | op | value | -|-------|-----|-------| -| slug | = | {slug} | - -Home intro — same bind shape as main (front / back / style). - -`home_intro` = - -| front | back | style | -|-------|------|-------| -| kicker | WWW demo · tables as the full stack | shell.`kicker` | -| title | Marqdo | shell.`intro_title` | -| lede | "One executable Markdown artifact declares routes, forms, admin pages, and styles — no hand-written business JavaScript, no author .css. Click a card for the full article, then try the three steps below." | shell.`lede` | -| claim | 0 author JS | shell.`claim` | -| claim | 0 author .css | shell.`claim` | -| claim | GFM tables | shell.`claim` | -| step | "Click any card — /post/{slug} opens the detail page from the same articles table." | shell.`step` | -| step | "Open [New](/new) and submit with an empty title (validation from a rule table)." | shell.`step` | -| step | "Open top-nav **Login** (admin / demo), then **Admin** — gated desk with create form + list." | shell.`step` | - -`about_intro` = - -| front | back | style | -|-------|------|-------| -| kicker | about | shell.`kicker` | -| title | About | shell.`intro_title` | -| lede | "Documentation and the deployed site stay one .mq.md artifact. Layout and theme are GFM style tables in styles/shell.mq.md — structure without hand-written CSS or business JavaScript." | shell.`lede` | -| claim | docs = program | shell.`claim` | -| claim | server-side rules | shell.`claim` | -| claim | hands-on | shell.`claim` | - -`new_intro` = - -| front | back | style | -|-------|------|-------| -| kicker | form · try validation | shell.`kicker` | -| title | New article | shell.`intro_title` | -| lede | "Leave Title empty and submit — the error comes from the rule table, not client JavaScript. Then fill title, slug, and summary to create a row shared with Admin and the card grid." | shell.`lede` | - -`admin_intro` = - -| front | back | style | -|-------|------|-------| -| kicker | desk · you are in admin | shell.`kicker` | -| title | Admin | shell.`intro_title` | -| lede | "This is the management desk (login required): same articles schema as the public site, assembled as list + create form — not a separate SPA. Use Site in the topnav to return, or Logout to end the session." | shell.`lede` | -| claim | login-gated | shell.`claim` | -| claim | table-declared | shell.`claim` | -| claim | "create + list" | shell.`claim` | - -`post_intro` = - -| front | back | style | -|-------|------|-------| -| kicker | article · table-bound detail | shell.`kicker` | - -Article create form: field table + rules table (server-side validation). - -`article_fields` = - -| name | label | type | required | default | -|------|-------|------|----------|---------| -| title | Title | text | true | | -| slug | Slug | text | true | | -| summary | Summary | textarea | false | | -| body | Body | textarea | false | | - -`article_rules` = - -| field | rule | message | -|-------|------|---------| -| title | required | Title is required | -| title | max:120 | Title is too long | -| slug | required | Slug is required | -| slug | max:80 | Slug is too long | -| summary | max:500 | Summary is too long | -| body | max:8000 | Body is too long | - -SEO / Open Graph for the home page (still a table). - -`home_meta` = - -| key | value | -|-----|-------| -| description | Tables as the full stack — Marqdo Web demo with zero author business JavaScript. | -| og:type | website | -| og:title | Marqdo Web Site | - -Neat CJK sans for body; Great Vibes for English display. - -`fonts` = - -| rel | href | crossorigin | -|-----|------|-------------| -| preconnect | https://fonts.googleapis.com | | -| preconnect | https://fonts.gstatic.com | anonymous | -| stylesheet | https://fonts.googleapis.com/css2?family=Great+Vibes&family=Noto+Sans+SC:wght@300;400;500;700&family=Noto+Serif+SC:wght@400;600&display=swap | | - -**store = > db.open** -**site_css = > shell.css** - -**page = > web.page title="Marqdo Web Site" shell_css="off"** -**page = > page.compose_intro intro=home_intro** -**page = > page.meta meta=home_meta** -**page = > page.head table=fonts** -**page = > page.css css=site_css** -**page = > page.compose_components components=home** -**page = > page.compose_main main=index** -**page = > page.link_prefix prefix="/post/"** - -**about = > web.page title="About · Marqdo Web" shell_css="off"** -**about = > about.compose_intro intro=about_intro** -**about = > about.head table=fonts** -**about = > about.css css=site_css** -**about = > about.compose_components components=home** - -**article_form = > web.form table="articles" action="insert"** -**article_form = > article_form.fields fields=article_fields** -**article_form = > article_form.rules rules=article_rules** - -**new = > web.page title="New article · Marqdo Web" shell_css="off"** -**new = > new.compose_intro intro=new_intro** -**new = > new.head table=fonts** -**new = > new.css css=site_css** -**new = > new.compose_components components=home** -**new = > new.compose_form id="article" form=article_form** - -**desk = > web.page title="Admin · Marqdo Web" shell_css="off"** -**desk = > desk.chrome body_class="is-desk"** -**desk = > desk.compose_intro intro=admin_intro** -**desk = > desk.head table=fonts** -**desk = > desk.css css=site_css** -**desk = > desk.compose_components components=desk_shell** -**desk = > desk.compose_form id="article" form=article_form** -**desk = > desk.compose_main main=index** -**desk = > desk.link_prefix prefix="/post/"** - -**post = > web.page title="Article · Marqdo Web" shell_css="off"** -**post = > post.compose_intro intro=post_intro** -**post = > post.head table=fonts** -**post = > post.css css=site_css** -**post = > post.compose_components components=home** -**post = > post.compose_main main=detail** -**post = > post.query query=by_slug** -**post = > post.detail detail=True** - -Demo credentials (table-declared users — host session auth, no author JS). - -`admins` = - -| username | password | role | -|----------|----------|------| -| admin | demo | admin | - -**app = > web.app page=page db=store admin=False host="127.0.0.1" port=18081 shell_css="off" login_redirect="/admin" logout_redirect="/"** -**app = > app.route path="/about" page=about** -**app = > app.route path="/new" page=new** -**app = > app.route path="/admin" page=desk** -**app = > app.route path="/post/{slug}" page=post** -**app = > app.auth users=admins session_ttl=3600 login_path="/login" login_redirect="/admin" logout_redirect="/"** -**app = > app.gate path="/admin" roles="admin" match="prefix" on_deny="redirect" exclude="/login"** -> `app`.listen +We **app = [Attach native login sessions](auth.attach(app=`app`, users=`users`, login_path="/login", login_redirect="/admin", logout_redirect="/"))** and **app = [Protect direct requests to the custom desk](auth.gate(app=`app`, path="/admin", roles="admin", match="prefix", on_deny="redirect", exclude="/login"))**. +Return *[Listen after actual resources and policy are ready](web.listen(app=`app`))*. diff --git a/examples/web-site/pages/about.mq.md b/examples/web-site/pages/about.mq.md new file mode 100644 index 0000000..a28a170 --- /dev/null +++ b/examples/web-site/pages/about.mq.md @@ -0,0 +1,29 @@ +--- +markup: occlusion +type: web +view: main +route: /about +title: About · Marqdo Web +import: + layout: ../components/index.mq.md + intro: ../components/intro.mq.md + articles: ../components/articles.mq.md + component: ext/web/component/index.mq.md + form: ext/data/form.mq.md + table: lib/table.mq.md +--- + +This Document explicitly declares /about. Its introduction ends in a Markdown leaf and its frame is shared. Request resources retain their own data or submission responsibilities. No startup page function initializes the database or starts another listener. + +## main + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Page-specific content and request resources within the shared frame | + +Assembly reads Markdown with fs.read and creates pure descriptors. This explanation page requires no database query or form reference. Follow the layout imports to change one region without copying a page shell. + +Page structure stays stable while request-dependent resources observe current data and identity. A missing required resource remains a diagnostic rather than a fake successful response. + +We **body = [Read this page's terminal introduction](intro.nodes(name="about"))**. +Return *[Place the page in its selected recursive frame](layout.frame(body=`body`, management=False))*. diff --git a/examples/web-site/pages/desk.mq.md b/examples/web-site/pages/desk.mq.md new file mode 100644 index 0000000..3f812dd --- /dev/null +++ b/examples/web-site/pages/desk.mq.md @@ -0,0 +1,31 @@ +--- +markup: occlusion +type: web +view: main +route: /admin +title: Admin · Marqdo Web +import: + layout: ../components/index.mq.md + intro: ../components/intro.mq.md + articles: ../components/articles.mq.md + component: ext/web/component/index.mq.md + form: ext/data/form.mq.md + table: lib/table.mq.md +--- + +This Document explicitly declares /admin. Its introduction ends in a Markdown leaf and its frame is shared. The serving entry enforces an actual admin role gate before the desk renders. No startup page function initializes the database or starts another listener. + +## main + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Page-specific content and request resources within the shared frame | + +Assembly reads Markdown with fs.read and creates pure descriptors. The server resolves the mounted form using actual session CSRF and return context. It does not embed a stale startup token or a separate copy of validation rules. + +The desk keeps its own navigation and footer and has no public side rail. Its form intentionally shares the public article submission endpoint; gating presentation alone would not make that endpoint private, and the example does not claim otherwise. + +We **body = [Read this page's terminal introduction](intro.nodes(name="desk"))**. +We **selected = [Reference the same explicitly mounted article form](form.reference(id="article"))** and **controls = [Retain current request CSRF and validation context](component.resource(value=`selected`, slot="article-form"))** and **body = [Keep instructions before the actual form](table.concat(a=`body`, b=`controls`))**. +We **records = [Describe the same current article list](articles.cards())** and **body = [Retain the actual record resource](table.concat(a=`body`, b=`records`))**. +Return *[Place the page in its selected recursive frame](layout.frame(body=`body`, management=True))*. diff --git a/examples/web-site/pages/new.mq.md b/examples/web-site/pages/new.mq.md new file mode 100644 index 0000000..0d0aa6e --- /dev/null +++ b/examples/web-site/pages/new.mq.md @@ -0,0 +1,30 @@ +--- +markup: occlusion +type: web +view: main +route: /new +title: New article · Marqdo Web +import: + layout: ../components/index.mq.md + intro: ../components/intro.mq.md + articles: ../components/articles.mq.md + component: ext/web/component/index.mq.md + form: ext/data/form.mq.md + table: lib/table.mq.md +--- + +This Document explicitly declares /new. Its introduction ends in a Markdown leaf and its frame is shared. Request resources retain their own data or submission responsibilities. No startup page function initializes the database or starts another listener. + +## main + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Page-specific content and request resources within the shared frame | + +Assembly reads Markdown with fs.read and creates pure descriptors. The server resolves the mounted form using actual session CSRF and return context. It does not embed a stale startup token or a separate copy of validation rules. + +Page structure stays stable while request-dependent resources observe current data and identity. A missing required resource remains a diagnostic rather than a fake successful response. + +We **body = [Read this page's terminal introduction](intro.nodes(name="new"))**. +We **selected = [Reference the same explicitly mounted article form](form.reference(id="article"))** and **controls = [Retain current request CSRF and validation context](component.resource(value=`selected`, slot="article-form"))** and **body = [Keep instructions before the actual form](table.concat(a=`body`, b=`controls`))**. +Return *[Place the page in its selected recursive frame](layout.frame(body=`body`, management=False))*. diff --git a/examples/web-site/pages/post.mq.md b/examples/web-site/pages/post.mq.md new file mode 100644 index 0000000..2722abf --- /dev/null +++ b/examples/web-site/pages/post.mq.md @@ -0,0 +1,30 @@ +--- +markup: occlusion +type: web +view: main +route: /post/{slug} +title: Article · Marqdo Web +import: + layout: ../components/index.mq.md + intro: ../components/intro.mq.md + articles: ../components/articles.mq.md + component: ext/web/component/index.mq.md + form: ext/data/form.mq.md + table: lib/table.mq.md +--- + +This Document explicitly declares /post/{slug}. Its introduction ends in a Markdown leaf and its frame is shared. Request resources retain their own data or submission responsibilities. No startup page function initializes the database or starts another listener. + +## main + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Page-specific content and request resources within the shared frame | + +Assembly reads Markdown with fs.read and creates pure descriptors. The actual path capture selects the current database record at request time; full Markdown body is separate from list summary, and query strings cannot replace the route slug. + +Page structure stays stable while request-dependent resources observe current data and identity. A missing required resource remains a diagnostic rather than a fake successful response. + +We **body = [Read this page's terminal introduction](intro.nodes(name="post"))**. +We **records = [Describe the current full-body slug match](articles.detail())** and **body = [Retain the actual record resource](table.concat(a=`body`, b=`records`))**. +Return *[Place the page in its selected recursive frame](layout.frame(body=`body`, management=False))*. diff --git a/examples/web-site/styles/index.mq.md b/examples/web-site/styles/index.mq.md new file mode 100644 index 0000000..b6cf63e --- /dev/null +++ b/examples/web-site/styles/index.mq.md @@ -0,0 +1,98 @@ +--- +markup: occlusion +title: Literary theme entry for recursive View Documents +import: + document: lib/document.mq.md + web: ext/web/web.mq.md + table: lib/table.mq.md + text: lib/text.mq.md +--- + +Read this entry before changing presentation. shell.tables.md retains every original declaration and shell.mq.md can still compile the original CSS. This entry projects only selectors onto the explicit View tree, restores the named property tables formerly attached by compose, and adds the bounded wrapper geometry in view.tables.md. Colors, property values, media conditions, particles and keyframe bodies remain the original data. + +## _selector + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| selector | text | required | One original author-controlled selector | +| mappings | list | required | Explicit old/new structural addresses read from view.tables.md | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Equivalent selector scoped to the explicit recursive site frame | + +Use `selector` and `mappings` from the actual retained theme and migration leaf. The old body-level sidebar and desk classes now belong to site-layout, while the main region is a section. The mappings preserve Markdown's actual heading, category, badge list and reading steps rather than restoring a private intro-binding dialect. + +Global document backgrounds, root tokens, selection styling, resets and keyframes stay global. Local selectors gain site scope so basic View defaults cannot override the deliberate theme. This is the fixed migration of this known site tree, not a generic CSS parser or visitor-controlled rewrite. The caller reads mappings once per area and passes those rows here, keeping this helper pure and avoiding repeated filesystem reads. + +- [Apply this site's explicit structural address mappings](for mappings as mapping) + We **selector = [Replace only the known selector address](text.replace(text=`selector`, old=access(mapping, "old"), new=access(mapping, "new")))**. +1. `selector` == "*" or `selector` == "::selection" or text.starts_with(text=`selector`, prefix="body") or text.starts_with(text=`selector`, prefix="html") or text.starts_with(text=`selector`, prefix=":root") or text.starts_with(text=`selector`, prefix="@") + Return *selector* because document-level rules and keyframes keep their existing scope. +1. text.starts_with(text=`selector`, prefix=".site-layout") + Return *[Scope the layout-state selector once](".mq-document " + selector)*. +Return *[Keep region selectors within this site's own frame](".mq-document .site-layout " + selector)*. + + +## _table + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | text | required | Original vars, motion, layout, responsive, chrome or widgets section | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Original declaration rows with only their selector field projected | + +Use `name` with fs.read under the site root. Native Markdown reading preserves the original table and typed cells; from_columns converts its aligned columns to row records. Every row keeps the same property, value, optional media and original position. Only selector changes, and immutable updates preserve the retained source table. + +This function does not compile or write CSS. Keeping the projected rows callable makes migration evidence inspectable: compare them to the original native table, including keyframe values and media, before looking at browser output. A missing section, ragged column or unsupported literal remains a real diagnostic rather than silently dropping a style. The mapping applies to this known site tree, not arbitrary CSS supplied by a visitor. + +We **mappings = [Read the fixed structural migration table](document.read_table(path="styles/view.tables.md", title="selectors"))**. +We **columns = [Read the unchanged declaration leaf](document.read_table(path="styles/shell.tables.md", title=`name`))** and **rows = [Keep each original declaration as a record](table.from_columns(columns=`columns`))** and **projected = [Start the selector projection](table.empty_list())**. +- [Retain every declaration in its original position](for rows as row) + We **selector = [Project only this row's structural address](_selector(selector=access(row, "selector"), mappings=`mappings`))** and **record = [Keep every other declaration field unchanged](table.put(in=`row`, at="selector", value=`selector`))** and **projected = [Retain this original property and value](table.append(list=`projected`, item=`record`))**. +Return *projected* for actual compilation or independent comparison. + +## _property + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | text | required | Original named property/value section | +| selector | text | required | Known semantic target in the new View tree, without leading dot | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Compiled original properties at their explicit new target | + +Use `name` and `selector` with fs.read and plugin. Removed compose operations used to attach these named properties to generated fields. The same declarations now target the native navigation, side/footer, current card classes and terminal Markdown elements. Their values do not change, and they are not inferred from user content. + +The selector is authored by the theme entry and begins with mq-document so the native style compiler supplies its leading class dot. The explicit target makes old property tables useful without restoring an obsolete page-binding dialect. Compilation returns text only; the serving workflow owns the selected generated path and native write. + +We **properties = [Read the original named property declaration](document.read_table(path="styles/shell.tables.md", title=`name`))**. +Return *[Compile the known semantic target](web.make_style(name=`selector`, table=`properties`))*. + +## css + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Full View theme with original values, explicit selector projection and wrapper geometry | + +Call with fs.read and plugin on the selected site root. Tokens and keyframes keep their original order, followed by layout, responsive, chrome and widget rules. Named property declarations restore the typography and region surfaces that the old compose calls attached separately. The generated CSS contains no replacement palette or abbreviated theme. + +The final geometry table only adapts the existing runtime wrappers: it removes the basic preview width/font defaults, lets native navigation resources participate in the shared grid, and preserves the explicit sidebar/desk class relationship. Markdown feature bullets become the original flex badge group, and the first explanatory paragraph uses the original lede properties. This keeps the content leaf readable without a hidden HTML template. + +Compilation neither writes the stylesheet nor claims browser acceptance. The serving workflow writes the result once before discovery. Verify the real computed colors, type sizes, wide sidebar, narrow stacked order, current cards and gated desk. If a selector no longer reaches its intended node, repair that mapping rather than deleting the original visual capability. + +We **areas = [Read the preserved theme area order](document.read_table(path="styles/view.tables.md", title="areas"))**. + +We **parts = [Start the actual ordered theme](table.empty_list())**. +- [Compile every original theme area](for areas as name) + We **rows = [Retain all original values and media](_table(name=`name`))** and **compiled = [Compile the actual projected declarations](web.make_style(name=`name`, table=`rows`))** and **parts = [Keep the original cascade order](table.append(list=`parts`, item=`compiled`))**. + +We **properties = [Read the actual named-property targets](document.read_table(path="styles/view.tables.md", title="properties"))**. + +- [Restore each originally bound property group](for properties as property) + We **compiled = [Compile its explicit semantic target](_property(name=access(property, "name"), selector=access(property, "selector")))** and **parts = [Retain that real property group](table.append(list=`parts`, item=`compiled`))**. +We **geometry = [Read the bounded View-wrapper adaptation](document.read_table(path="styles/view.tables.md", title="geometry"))** and **compiled = [Compile native geometry adaptation](web.make_style(name="view", table=`geometry`))** and **parts = [Finish with the explicit wrapper rules](table.append(list=`parts`, item=`compiled`))**. +Return *[Keep actual compiled sections in order](text.str_join(xs=`parts`, sep=""))*. diff --git a/examples/web-site/styles/shell.mq.md b/examples/web-site/styles/shell.mq.md index a37d333..06e7d72 100644 --- a/examples/web-site/styles/shell.mq.md +++ b/examples/web-site/styles/shell.mq.md @@ -1,677 +1,277 @@ --- markup: occlusion -title: styles/shell -description: >- - Literary dark theme for examples/web-site — ink / wine / gold after the - anlian.cyou Zhang Ailing topic. GFM tables only; no author .css. +title: Retained literary theme declarations import: + document: lib/document.mq.md web: ext/web/web.mq.md + table: lib/table.mq.md text: lib/text.mq.md --- -Authors style the site with **GFM tables** only. App pages use `shell_css=off` -so host defaults do not fight this theme. Palette mirrors -[海上花开](https://www.anlian.cyou/topics/author-zhangailing/): night ink, -wine, cold gold, serif display. +This file retains original declaration readers and original CSS compilation for migration comparison. The current site uses styles/index.mq.md for the actual View projection. Do not mistake an unchanged original hash for proof that new selectors reach their intended nodes. Each literal section remains independently callable. ## vars -`vars` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | -| selector | property | value | -|----------|----------|-------| -| :root | --ink | #0a0809 | -| :root | --ink-lift | #141012 | -| :root | --wine | #6b1e3a | -| :root | --wine-soft | rgba(107,30,58,0.35) | -| :root | --gold | #d4af37 | -| :root | --gold-dim | rgba(212,175,55,0.45) | -| :root | --gold-soft | rgba(212,175,55,0.12) | -| :root | --paper | rgba(255,248,240,0.92) | -| :root | --paper-dim | rgba(255,248,240,0.72) | -| :root | --paper-faint | rgba(255,248,240,0.48) | -| :root | --glass | rgba(20,12,18,0.72) | -| :root | --glass-strong | rgba(20,12,18,0.88) | -| :root | --border | rgba(212,175,55,0.22) | -| :root | --border-soft | rgba(212,175,55,0.12) | -| :root | --danger | #e8a0a8 | -| :root | --radius | 4px | -| :root | --radius-sm | 2px | -| :root | --space-2 | 8px | -| :root | --space-3 | 12px | -| :root | --space-4 | 16px | -| :root | --space-5 | 20px | -| :root | --space-6 | 24px | -| :root | --space-8 | 32px | -| :root | --text | 16px | -| :root | --leading | "1.75" | -| :root | --shadow | "0 24px 80px rgba(0,0,0,.55), inset 0 1px 0 rgba(255,255,255,.06)" | -| :root | --shadow-card | "0 12px 40px rgba(107,30,58,.35)" | -| :root | --ring | "0 0 0 2px rgba(212,175,55,.35)" | -| :root | --serif | "'Noto Serif SC', 'Source Serif 4', Georgia, serif" | -| :root | --sans | "'Noto Sans SC', 'IBM Plex Sans', system-ui, sans-serif" | -| :root | --display | "'Great Vibes', 'Allura', cursive" | -| :root | --mono | "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace" | -| ::selection | background | rgba(212,175,55,0.35) | -| ::selection | color | var(--paper) | +Root palette, typefaces, spacing and elevation tokens. -*`vars`* +Compile these declarations before rules that reference their custom properties. The selection-color rows remain global alongside :root; neither the View migration nor a caller should scope those tokens inside one card. Editing a value changes the shared theme, so compare real compiled CSS and browser colors rather than renaming a property locally. + +Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. + +Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="vars"))*. ## motion -`motion` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | -| selector | property | value | -|----------|----------|-------| -| @keyframes rise 0% | opacity | "0" | -| @keyframes rise 0% | transform | translateY(14px) | -| @keyframes rise 100% | opacity | "1" | -| @keyframes rise 100% | transform | translateY(0) | -| @keyframes float 0% | transform | translateY(0) | -| @keyframes float 0% | opacity | "0.7" | -| @keyframes float 50% | transform | translateY(6px) | -| @keyframes float 50% | opacity | "1" | -| @keyframes float 100% | transform | translateY(0) | -| @keyframes float 100% | opacity | "0.7" | -| @keyframes goldPulse 0% | text-shadow | "0 0 24px rgba(212,175,55,.2)" | -| @keyframes goldPulse 50% | text-shadow | "0 0 48px rgba(212,175,55,.45)" | -| @keyframes goldPulse 100% | text-shadow | "0 0 24px rgba(212,175,55,.2)" | -| @keyframes particleDrift 0% | transform | translate3d(0,0,0) | -| @keyframes particleDrift 50% | transform | translate3d(-2.5vw, 1.5vh, 0) | -| @keyframes particleDrift 100% | transform | translate3d(0,0,0) | -| @keyframes particleDrift2 0% | transform | translate3d(0,0,0) | -| @keyframes particleDrift2 50% | transform | translate3d(2vw, -2vh, 0) | -| @keyframes particleDrift2 100% | transform | translate3d(0,0,0) | -| @keyframes nebulaPulse 0% | opacity | "0.55" | -| @keyframes nebulaPulse 50% | opacity | "0.9" | -| @keyframes nebulaPulse 100% | opacity | "0.55" | +Original entrance, floating, particle and glow keyframes. -*`motion`* +Keyframe selectors and their property values remain global and in their original order. Animation timing belongs to the consuming rule. Reading this data does not schedule an animation; the browser applies the compiled stylesheet. The View projection must not prefix these addresses with a component class. + +Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. + +Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="motion"))*. ## layout -`layout` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | -| selector | property | value | -|----------|----------|-------| -| * | box-sizing | border-box | -| html | scroll-behavior | smooth | -| html | -webkit-text-size-adjust | 100% | -| body | margin | "0" | -| body | min-height | 100vh | -| body | font-family | var(--sans) | -| body | font-weight | "400" | -| body | font-size | var(--text) | -| body | line-height | var(--leading) | -| body | color | var(--paper) | -| body | background | var(--ink) | -| body | background-image | "radial-gradient(ellipse 90% 55% at 50% -15%, rgba(107,30,58,.5), transparent 58%), radial-gradient(ellipse 55% 45% at 92% 75%, rgba(212,175,55,.14), transparent 55%), radial-gradient(ellipse 40% 35% at 8% 70%, rgba(107,30,58,.22), transparent 60%), linear-gradient(180deg, #0a0809 0%, #120c10 45%, #0a0809 100%)" | -| body | background-attachment | fixed | -| body | display | grid | -| body | grid-template-rows | "auto 1fr auto" | -| body | -webkit-font-smoothing | antialiased | -| body | position | relative | -| body | overflow-x | hidden | -| body::before | content | '""' | -| body::before | position | fixed | -| body::before | inset | "0" | -| body::before | z-index | "1" | -| body::before | pointer-events | none | -| body::before | opacity | "0.1" | -| body::before | background-image | "url(\"data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E\")" | -| html::before | content | '""' | -| html::before | position | fixed | -| html::before | inset | "0" | -| html::before | z-index | "0" | -| html::before | pointer-events | none | -| html::before | background-image | "radial-gradient(ellipse 50% 40% at 15% 30%, rgba(107,30,58,.35), transparent 70%), radial-gradient(ellipse 45% 35% at 85% 60%, rgba(212,175,55,.12), transparent 65%), radial-gradient(ellipse 40% 30% at 50% 90%, rgba(107,30,58,.25), transparent 70%)" | -| html::before | animation | "nebulaPulse 12s ease-in-out infinite" | -| body::after | content | '""' | -| body::after | position | fixed | -| body::after | top | "0" | -| body::after | left | "0" | -| body::after | width | "2px" | -| body::after | height | "2px" | -| body::after | z-index | "2" | -| body::after | pointer-events | none | -| body::after | border-radius | 50% | -| body::after | background | transparent | -| body::after | box-shadow | "82vw 15vh 0px 0px rgba(212,175,55,0.55),29vw 18vh 0px 1px rgba(212,175,55,0.25),95vw 70vh 1px 0px rgba(212,175,55,0.55),4vw 12vh 0px 1px rgba(212,175,55,0.35),78vw 4vh 0px 1px rgba(245,230,200,0.5),84vw 90vh 1px 0px rgba(245,230,200,0.5),58vw 76vh 0px 0px rgba(255,248,240,0.4),90vw 55vh 0px 0px rgba(255,248,240,0.4),28vw 98vh 0px 0px rgba(255,248,240,0.4),49vw 13vh 0px 1px rgba(255,248,240,0.4),34vw 6vh 1px 1px rgba(212,175,55,0.25),16vw 49vh 0px 1px rgba(212,175,55,0.55),80vw 47vh 0px 1px rgba(245,230,200,0.5),9vw 6vh 0px 0px rgba(212,175,55,0.25),11vw 30vh 1px 0px rgba(212,175,55,0.55),59vw 82vh 0px 0px rgba(255,248,240,0.4),46vw 27vh 0px 1px rgba(212,175,55,0.25),88vw 83vh 0px 1px rgba(212,175,55,0.55),94vw 32vh 1px 0px rgba(212,175,55,0.35),35vw 82vh 0px 1px rgba(212,175,55,0.25),42vw 99vh 0px 0px rgba(212,175,55,0.55),41vw 52vh 0px 0px rgba(255,248,240,0.4),73vw 92vh 0px 1px rgba(255,248,240,0.4),64vw 51vh 1px 0px rgba(212,175,55,0.25),34vw 18vh 0px 1px rgba(212,175,55,0.35),75vw 55vh 1px 0px rgba(245,230,200,0.5),29vw 18vh 1px 0px rgba(245,230,200,0.5),97vw 7vh 0px 1px rgba(212,175,55,0.55),21vw 88vh 0px 0px rgba(107,30,58,0.45),49vw 77vh 0px 1px rgba(107,30,58,0.45),2vw 88vh 0px 1px rgba(212,175,55,0.25),69vw 97vh 0px 0px rgba(255,248,240,0.4),38vw 56vh 1px 0px rgba(212,175,55,0.35),93vw 93vh 0px 1px rgba(255,248,240,0.4),14vw 81vh 0px 0px rgba(255,248,240,0.4),48vw 98vh 0px 1px rgba(212,175,55,0.35),42vw 63vh 0px 0px rgba(212,175,55,0.55),40vw 31vh 0px 1px rgba(212,175,55,0.55),11vw 11vh 1px 0px rgba(212,175,55,0.25),98vw 69vh 0px 1px rgba(212,175,55,0.35),61vw 71vh 0px 1px rgba(212,175,55,0.35),78vw 55vh 0px 1px rgba(212,175,55,0.35),40vw 52vh 0px 0px rgba(212,175,55,0.25),67vw 58vh 0px 0px rgba(212,175,55,0.55),9vw 44vh 0px 1px rgba(212,175,55,0.55),29vw 1vh 0px 0px rgba(212,175,55,0.55),9vw 5vh 0px 1px rgba(255,248,240,0.4),31vw 36vh 1px 0px rgba(212,175,55,0.25),70vw 17vh 1px 0px rgba(212,175,55,0.25),61vw 53vh 0px 0px rgba(212,175,55,0.35),85vw 56vh 1px 0px rgba(255,248,240,0.4),60vw 94vh 0px 0px rgba(212,175,55,0.55),52vw 94vh 0px 0px rgba(255,248,240,0.4),25vw 25vh 1px 0px rgba(245,230,200,0.5),55vw 24vh 1px 0px rgba(255,248,240,0.4),10vw 57vh 0px 0px rgba(245,230,200,0.5),84vw 70vh 0px 0px rgba(212,175,55,0.55),22vw 53vh 1px 0px rgba(107,30,58,0.45),52vw 8vh 1px 0px rgba(212,175,55,0.35),50vw 34vh 0px 0px rgba(107,30,58,0.45),90vw 94vh 1px 0px rgba(245,230,200,0.5),25vw 38vh 0px 1px rgba(212,175,55,0.35),95vw 70vh 0px 0px rgba(212,175,55,0.55),7vw 75vh 0px 0px rgba(107,30,58,0.45),66vw 11vh 0px 1px rgba(212,175,55,0.35),9vw 87vh 1px 0px rgba(212,175,55,0.35),73vw 32vh 0px 1px rgba(245,230,200,0.5),11vw 54vh 0px 0px rgba(212,175,55,0.25),27vw 86vh 0px 0px rgba(212,175,55,0.25),34vw 51vh 0px 0px rgba(212,175,55,0.35),41vw 97vh 0px 0px rgba(212,175,55,0.55),80vw 73vh 0px 1px rgba(212,175,55,0.55)" | -| body::after | animation | "particleDrift 48s ease-in-out infinite" | -| html::after | content | '""' | -| html::after | position | fixed | -| html::after | top | "0" | -| html::after | left | "0" | -| html::after | width | "1px" | -| html::after | height | "1px" | -| html::after | z-index | "2" | -| html::after | pointer-events | none | -| html::after | border-radius | 50% | -| html::after | background | transparent | -| html::after | box-shadow | "28vw 65vh 0 0 rgba(255,248,240,0.25),17vw 45vh 0 0 rgba(212,175,55,0.3),32vw 48vh 0 0 rgba(255,248,240,0.25),21vw 57vh 0 0 rgba(107,30,58,0.3),91vw 39vh 0 0 rgba(107,30,58,0.3),84vw 68vh 0 0 rgba(212,175,55,0.3),86vw 71vh 0 0 rgba(255,248,240,0.25),85vw 14vh 0 0 rgba(212,175,55,0.3),34vw 15vh 0 0 rgba(212,175,55,0.3),96vw 71vh 0 0 rgba(212,175,55,0.3),35vw 37vh 0 0 rgba(107,30,58,0.3),27vw 92vh 0 0 rgba(255,248,240,0.25),27vw 88vh 0 0 rgba(107,30,58,0.3),34vw 65vh 0 0 rgba(255,248,240,0.25),33vw 7vh 0 0 rgba(212,175,55,0.3),82vw 55vh 0 0 rgba(255,248,240,0.25),6vw 1vh 0 0 rgba(255,248,240,0.25),99vw 17vh 0 0 rgba(107,30,58,0.3),34vw 21vh 0 0 rgba(107,30,58,0.3),57vw 71vh 0 0 rgba(107,30,58,0.3),55vw 72vh 0 0 rgba(212,175,55,0.3),15vw 10vh 0 0 rgba(107,30,58,0.3),20vw 70vh 0 0 rgba(212,175,55,0.3),48vw 75vh 0 0 rgba(107,30,58,0.3),19vw 56vh 0 0 rgba(212,175,55,0.3),6vw 40vh 0 0 rgba(255,248,240,0.25),6vw 46vh 0 0 rgba(212,175,55,0.3),88vw 32vh 0 0 rgba(107,30,58,0.3),14vw 46vh 0 0 rgba(107,30,58,0.3),53vw 80vh 0 0 rgba(107,30,58,0.3),20vw 31vh 0 0 rgba(212,175,55,0.3),23vw 53vh 0 0 rgba(212,175,55,0.3),23vw 95vh 0 0 rgba(255,248,240,0.25),53vw 86vh 0 0 rgba(107,30,58,0.3),32vw 35vh 0 0 rgba(212,175,55,0.3),90vw 14vh 0 0 rgba(255,248,240,0.25),5vw 61vh 0 0 rgba(212,175,55,0.3),26vw 59vh 0 0 rgba(255,248,240,0.25),40vw 30vh 0 0 rgba(212,175,55,0.3),4vw 85vh 0 0 rgba(212,175,55,0.3),52vw 43vh 0 0 rgba(255,248,240,0.25),9vw 99vh 0 0 rgba(255,248,240,0.25),45vw 83vh 0 0 rgba(107,30,58,0.3),52vw 87vh 0 0 rgba(107,30,58,0.3),43vw 4vh 0 0 rgba(212,175,55,0.3),34vw 23vh 0 0 rgba(107,30,58,0.3),34vw 5vh 0 0 rgba(212,175,55,0.3),77vw 56vh 0 0 rgba(255,248,240,0.25)" | -| html::after | animation | "particleDrift2 64s ease-in-out infinite" | -| body.has-sidebar | grid-template-columns | "14rem minmax(0, 1fr)" | -| body.has-sidebar | grid-template-areas | '"top top" "side main" "foot foot"' | -| body.no-sidebar | grid-template-areas | '"top" "main" "foot"' | -| body.layout-stacked | grid-template-areas | '"top" "main" "foot"' | -| body.is-desk | grid-template-areas | '"top" "main" "foot"' | -| header.topnav | grid-area | top | -| aside.side | grid-area | side | -| main.main | grid-area | main | -| footer.foot | grid-area | foot | -| header.topnav | position | relative | -| header.topnav | z-index | "20" | -| aside.side | position | relative | -| aside.side | z-index | "10" | -| main.main | position | relative | -| main.main | z-index | "10" | -| footer.foot | position | relative | -| footer.foot | z-index | "10" | -| main.main | width | "100%" | -| main.main | max-width | "min(78rem, 100%)" | -| main.main | padding | "var(--space-8) var(--space-6) 4rem" | -| main.main | animation | "rise .8s cubic-bezier(.22,1,.36,1) both" | -| a | color | var(--gold) | -| a | text-decoration | none | -| a | transition | color 0.25s ease | -| a:hover | color | #f5e6c8 | -| code | font-family | var(--mono) | -| code | font-size | "0.82em" | -| code | font-weight | "400" | -| code | background | rgba(0,0,0,0.35) | -| code | border | 1px solid var(--border-soft) | -| code | padding | "0.12em 0.45em" | -| code | border-radius | var(--radius-sm) | -| code | color | var(--gold) | +Document background, typography and original region-grid declarations. -*`layout`* +The original body layout classes describe the old page shell. Current View use projects those known addresses to the explicit site-layout region through styles/index; their property values remain unchanged. Keep document-level backgrounds and particle layers global, and compare actual wide/narrow geometry after any edit. + +Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. + +Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="layout"))*. ## responsive -`responsive` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | -| media | selector | property | value | -|-------|----------|----------|-------| -| (max-width: 860px) | body.has-sidebar | grid-template-columns | 1fr | -| (max-width: 860px) | body.has-sidebar | grid-template-areas | '"top" "main" "side" "foot"' | -| (max-width: 860px) | aside.side | border-right | "0" | -| (max-width: 860px) | aside.side | border-top | 1px solid var(--border-soft) | -| (max-width: 860px) | main.main | padding | "var(--space-6) var(--space-4) var(--space-8)" | -| (max-width: 860px) | .content.cards | grid-template-columns | 1fr | -| (max-width: 860px) | .site-form form | grid-template-columns | 1fr | -| (max-width: 860px) | .site-form label:nth-child(1) | grid-column | "1 / -1" | -| (max-width: 860px) | .site-form label:nth-child(2) | grid-column | "1 / -1" | -| (max-width: 860px) | header.topnav | padding | "0.85rem var(--space-4)" | -| (max-width: 860px) | .intro_title | font-size | "2.4rem" | -| (prefers-reduced-motion: reduce) | main.main | animation | none | -| (prefers-reduced-motion: reduce) | .kicker | animation | none | -| (prefers-reduced-motion: reduce) | article.card | transition | none | -| (prefers-reduced-motion: reduce) | body::after | animation | none | -| (prefers-reduced-motion: reduce) | html::after | animation | none | -| (prefers-reduced-motion: reduce) | html::before | animation | none | +Original media-conditioned layout and reduced-motion rows. -*`responsive`* +These rows retain media text as a separate column. Width conditions collapse the public grid and change padding; prefers-reduced-motion disables selected animation without deleting its keyframes. Preserve row ordering and media alongside the value, rather than checking only that a selector name still appears in CSS. + +Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. + +Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="responsive"))*. ## topnav -`topnav` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | -| property | value | -|----------|-------| -| position | sticky | -| top | "0" | -| z-index | "40" | -| display | flex | -| align-items | center | -| justify-content | flex-start | -| gap | var(--space-4) | -| padding | "1rem var(--space-6)" | -| background | "linear-gradient(180deg, rgba(10,8,9,.92) 0%, rgba(10,8,9,.55) 70%, transparent 100%)" | -| backdrop-filter | blur(10px) | -| -webkit-backdrop-filter | blur(10px) | -| border-bottom | 1px solid var(--border-soft) | +Named property/value declarations for the top navigation surface. -*`topnav`* +The original sticky positioning, gradient, blur, spacing and border are still applied to the native topnav class. Links and their current-session conditions belong to the navigation resource. A property table cannot authenticate a visitor or make a route exist, and compiling it does not mount a stylesheet. + +Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. + +Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="topnav"))*. ## side_panel -`side_panel` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | -| property | value | -|----------|-------| -| background | "rgba(10,8,9,.55)" | -| padding | "var(--space-6) var(--space-4)" | -| border-right | 1px solid var(--border-soft) | +Named property/value declarations for the public side rail. -*`side_panel`* +The side rail's background, padding and separator distinguish task links from article content. Its external grid position belongs to the parent frame, and the desk intentionally omits it. Keep this visual responsibility separate from the link table and from the native session policy. + +Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. + +Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="side_panel"))*. ## footer -`footer` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | -| property | value | -|----------|-------| -| color | var(--paper-faint) | -| font-size | "0.8rem" | -| letter-spacing | "0.08em" | -| padding | "var(--space-5) var(--space-6)" | -| border-top | 1px solid var(--border-soft) | -| background | "rgba(10,8,9,.75)" | +Named property/value declarations for the closing region. -*`footer`* +These values retain the original footer color, type size, spacing, border and background. The Markdown footer owns actual destinations; this table neither creates links nor starts logout. The same surface properties can style public and desk footers while their terminal content stays separate. + +Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. + +Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="footer"))*. ## card_title -`card_title` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | -| property | value | -|----------|-------| -| font-family | var(--serif) | -| font-size | "1.15rem" | -| font-weight | "600" | -| margin | "0 0 var(--space-2)" | -| color | var(--gold) | -| letter-spacing | "0.02em" | -| line-height | "1.35" | +Named property/value typography for article-card headings. -*`card_title`* +The current-query renderer escapes article titles and retains its native h2 structure. The View theme targets that structure with these original properties, rather than returning to front/back page bindings. This reader does not query articles, truncate titles or modify their stored text. + +Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. + +Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="card_title"))*. ## card_body -`card_body` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | -| property | value | -|----------|-------| -| color | var(--paper-dim) | -| margin | "0" | -| line-height | "1.65" | -| font-size | "0.9rem" | -| font-weight | "400" | -| display | "-webkit-box" | -| -webkit-box-orient | vertical | -| -webkit-line-clamp | "3" | -| overflow | hidden | +Named property/value typography for card summaries. -*`card_body`* +Summary data belongs to the current article query, and full Markdown body remains reserved for detail. These properties affect only appearance; they do not choose or replace content. After changing the selector target, verify that both escaped summaries and full article bodies keep their separate behavior. + +Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. + +Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="card_body"))*. ## chrome -Panel + claim/steps group layout (field look comes from named bind styles). +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | -`chrome` = +Original introduction panels, badge container, reading steps and full-article rules. -| selector | property | value | -|----------|----------|-------| -| .main-intro | background | var(--glass) | -| .main-intro | border | 1px solid var(--border) | -| .main-intro | border-radius | var(--radius) | -| .main-intro | padding | "2.25rem 1.75rem 1.85rem" | -| .main-intro | box-shadow | var(--shadow) | -| .main-intro | backdrop-filter | blur(16px) | -| .main-intro | -webkit-backdrop-filter | blur(16px) | -| .main-intro | margin-bottom | var(--space-8) | -| .main-intro > .claim | display | flex | -| .main-intro > .claim | flex-wrap | wrap | -| .main-intro > .claim | gap | var(--space-2) | -| .main-intro > .claim | margin | "0 0 var(--space-6)" | -| .main-intro > .steps | margin | "0" | -| .main-intro > .steps | padding | "var(--space-5) var(--space-5) var(--space-5) 1.5rem" | -| .main-intro > .steps | color | var(--paper-dim) | -| .main-intro > .steps | background | "rgba(0,0,0,.35)" | -| .main-intro > .steps | border | 1px solid var(--border-soft) | -| .main-intro > .steps | border-left | 2px solid var(--gold-dim) | -| .main-intro > .steps | border-radius | var(--radius) | -| .main-intro > .steps | font-size | "0.95rem" | -| .main-intro > .steps | letter-spacing | "0.02em" | -| .main-intro > .steps a | color | var(--gold) | -| .main-intro > .steps a | font-weight | "500" | -| .main-intro > .steps a:hover | color | #f5e6c8 | -| .article | background | var(--glass) | -| .article | border | 1px solid var(--border) | -| .article | border-radius | var(--radius) | -| .article | padding | "2rem 1.75rem" | -| .article | box-shadow | var(--shadow) | -| .article | backdrop-filter | blur(16px) | -| .article | -webkit-backdrop-filter | blur(16px) | -| .article-title | font-family | var(--serif) | -| .article-title | font-size | "clamp(1.75rem, 4vw, 2.35rem)" | -| .article-title | font-weight | "600" | -| .article-title | color | var(--gold) | -| .article-title | letter-spacing | "0.04em" | -| .article-title | margin | "0 0 var(--space-5)" | -| .article-title | line-height | "1.25" | -| .article-body | color | var(--paper-dim) | -| .article-body | font-family | var(--sans) | -| .article-body | font-size | "1.02rem" | -| .article-body | line-height | "1.85" | -| .article-body.md p | margin | "0 0 1.1rem" | -| .article-body.md a | color | var(--gold) | -| article.card | cursor | pointer | -| a.card-link | color | inherit | -| a.card-link | text-decoration | none | -| a.card-link:hover | color | inherit | +Current introductions are terminal Markdown, so the View mapping addresses real headings, bullets and ordered lists. Article selectors continue to match the native detail renderer. Keep those mappings explicit and retain the original values; do not hide layout inside authored HTML to recover an old selector. -*`chrome`* +Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. + +Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="chrome"))*. ## kicker -`kicker` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | -| property | value | -|----------|-------| -| letter-spacing | "0.32em" | -| text-transform | uppercase | -| font-size | "0.72rem" | -| color | var(--gold-dim) | -| margin | "0 0 var(--space-4)" | -| font-weight | "400" | -| font-family | var(--sans) | -| animation | "float 2.8s ease-in-out infinite" | +Named property/value typography for the introduction category. -*`kicker`* +The original letter spacing, color, small type and floating animation target the Markdown blockquote used for the category. Its content remains an ordinary readable line in the leaf. Compiling these properties does not create that content or make the browser fetch a font. + +Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. + +Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="kicker"))*. ## intro_title -`intro_title` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | -| property | value | -|----------|-------| -| font-family | var(--display) | -| font-size | "clamp(3rem, 10vw, 4.8rem)" | -| font-weight | "400" | -| line-height | "1.15" | -| letter-spacing | "0.04em" | -| margin | "0 0 var(--space-4)" | -| color | transparent | -| background | "linear-gradient(135deg, #f5e6c8 0%, var(--gold) 42%, var(--wine) 100%)" | -| -webkit-background-clip | text | -| background-clip | text | -| animation | "goldPulse 4.5s ease-in-out infinite" | +Named property/value typography for the primary introduction heading. -*`intro_title`* +These declarations retain the display font, responsive size, gradient text and glow animation. The View theme applies them to the actual Markdown h1, avoiding an extra heading-size multiplier on a wrapper. Browser validation checks the computed font family and size; reading this table alone cannot prove rendering. + +Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. + +Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="intro_title"))*. ## lede -`lede` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | -| property | value | -|----------|-------| -| color | var(--paper-dim) | -| max-width | "34rem" | -| line-height | "1.85" | -| margin | "0 0 var(--space-5)" | -| font-size | "1.05rem" | -| letter-spacing | "0.02em" | -| font-weight | "400" | -| font-family | var(--sans) | +Named property/value typography for supporting introduction prose. -*`lede`* +The original width, line height, color, spacing and typeface target the leaf's explanatory paragraph. It remains separate from claim bullets and numbered steps. Keep the selector on the real paragraph rather than styling a wrapper and relying on browser default margins to approximate the old appearance. + +Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. + +Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="lede"))*. ## claim -`claim` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | -| property | value | -|----------|-------| -| display | inline-flex | -| align-items | center | -| padding | "0.2rem 0.65rem" | -| border-radius | var(--radius-sm) | -| background | var(--wine-soft) | -| color | #f0c9d4 | -| font-size | "0.68rem" | -| font-weight | "500" | -| letter-spacing | "0.14em" | -| border | 1px solid rgba(107,30,58,0.5) | +Named property/value declarations for each short feature badge. -*`claim`* +The Markdown bullet list is the original flex badge container, while each item receives these original inline badge properties. The container's gap and wrapping belong to the chrome section. This distinction preserves both readable list content and the actual visual grouping without another binding-table language. + +Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. + +Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="claim"))*. ## step -`step` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | -| property | value | -|----------|-------| -| margin | "0.55rem 0" | +Original margin declaration for one guided-reading step. -*`step`* +This section has a single property row, so its native result contains scalar cells rather than aligned lists. The same style compiler accepts that shape. The ordered Markdown list owns step numbering and links; this value only supplies the original per-item spacing and does not reorder the reading sequence. + +Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. + +Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="step"))*. ## widgets -`widgets` = +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | -| selector | property | value | -|----------|----------|-------| -| ul.nav | display | flex | -| ul.nav | flex-wrap | wrap | -| ul.nav | align-items | center | -| ul.nav | gap | "0.35rem 1rem" | -| ul.nav | list-style | none | -| ul.nav | margin | "0" | -| ul.nav | padding | "0" | -| ul.nav a | display | inline-flex | -| ul.nav a | align-items | center | -| ul.nav a | text-decoration | none | -| ul.nav a | color | var(--paper-dim) | -| ul.nav a | padding | "0.35rem 0" | -| ul.nav a | border-radius | "0" | -| ul.nav a | font-weight | "400" | -| ul.nav a | font-size | "0.8rem" | -| ul.nav a | letter-spacing | "0.14em" | -| ul.nav a | transition | color 0.25s ease | -| ul.nav a:hover | background | transparent | -| ul.nav a:hover | color | var(--gold) | -| ul.nav a:hover | text-decoration | none | -| ul.nav a[href="/admin"] | color | var(--gold) | -| ul.nav a[href="/admin"] | letter-spacing | "0.18em" | -| ul.nav a[href="/admin"] | border-bottom | 1px solid var(--gold-dim) | -| ul.side-nav a[href="/admin"] | color | var(--gold) | -| body.is-desk header.topnav | border-bottom | 1px solid rgba(107,30,58,0.55) | -| body.is-desk header.topnav | box-shadow | "0 12px 40px rgba(107,30,58,.18)" | -| body.is-desk .main-intro | border-left | 3px solid var(--wine) | -| body.is-desk .site-form | border-color | rgba(107,30,58,0.45) | -| body.is-desk .site-form | box-shadow | "0 0 0 1px rgba(212,175,55,.12), 0 18px 48px rgba(0,0,0,.35)" | -| body.is-desk .content.cards | margin-top | var(--space-6) | -| ul.nav li:first-child a | font-family | var(--display) | -| ul.nav li:first-child a | font-weight | "400" | -| ul.nav li:first-child a | color | var(--gold) | -| ul.nav li:first-child a | font-size | "1.85rem" | -| ul.nav li:first-child a | letter-spacing | "0.06em" | -| ul.nav li:first-child a | padding | "0.1rem 0.2rem 0.1rem 0" | -| ul.nav li:first-child a:hover | background | transparent | -| ul.nav li:first-child a:hover | color | #f5e6c8 | -| .side-label | display | block | -| .side-label | font-size | "0" | -| .side-label | margin | "0 0 var(--space-4)" | -| .side-label::before | content | '"Path"' | -| .side-label::before | display | block | -| .side-label::before | font-size | "0.68rem" | -| .side-label::before | letter-spacing | "0.28em" | -| .side-label::before | text-transform | uppercase | -| .side-label::before | color | var(--gold-dim) | -| .side-label::before | font-weight | "400" | -| ul.side-nav | list-style | none | -| ul.side-nav | margin | "0" | -| ul.side-nav | padding | "0" | -| ul.side-nav | display | grid | -| ul.side-nav | gap | "2px" | -| ul.side-nav | border-left | 1px solid var(--border) | -| ul.side-nav | padding-left | "0.85rem" | -| ul.side-nav | margin-left | "0.25rem" | -| ul.side-nav a | display | block | -| ul.side-nav a | text-decoration | none | -| ul.side-nav a | color | var(--paper-dim) | -| ul.side-nav a | padding | "0.45rem 0.35rem" | -| ul.side-nav a | border-radius | "0" | -| ul.side-nav a | font-weight | "400" | -| ul.side-nav a | font-size | "0.88rem" | -| ul.side-nav a | letter-spacing | "0.06em" | -| ul.side-nav a | border | "0" | -| ul.side-nav a | position | relative | -| ul.side-nav a:hover | background | transparent | -| ul.side-nav a:hover | border-color | transparent | -| ul.side-nav a:hover | color | var(--gold) | -| ul.side-nav a:hover | text-decoration | none | -| ul.side-nav a:hover | box-shadow | none | -| ul.foot-nav | display | flex | -| ul.foot-nav | gap | var(--space-4) | -| ul.foot-nav | list-style | none | -| ul.foot-nav | margin | "0" | -| ul.foot-nav | padding | "0" | -| ul.foot-nav a | color | var(--paper-faint) | -| ul.foot-nav a | font-weight | "400" | -| ul.foot-nav a | letter-spacing | "0.1em" | -| ul.foot-nav a | font-size | "0.78rem" | -| ul.foot-nav a:hover | color | var(--gold) | -| .content.cards | display | grid | -| .content.cards | gap | var(--space-4) | -| .content.cards | margin-top | "0" | -| .content.cards | grid-template-columns | "repeat(auto-fill, minmax(16rem, 1fr))" | -| article.card | background | "rgba(0,0,0,.35)" | -| article.card | border | 1px solid var(--border-soft) | -| article.card | border-radius | var(--radius-sm) | -| article.card | padding | "1.35rem 1.15rem" | -| article.card | box-shadow | none | -| article.card | transition | "border-color .35s ease, box-shadow .35s ease, transform .35s ease" | -| article.card:hover | transform | "translateY(-3px)" | -| article.card:hover | box-shadow | var(--shadow-card) | -| article.card:hover | border-color | var(--gold-dim) | -| .site-form | background | var(--glass) | -| .site-form | border | 1px solid var(--border) | -| .site-form | border-radius | var(--radius) | -| .site-form | padding | "var(--space-6) var(--space-6) var(--space-7, 1.75rem)" | -| .site-form | margin | "0 0 var(--space-6)" | -| .site-form | max-width | "100%" | -| .site-form | width | "100%" | -| .site-form | box-shadow | var(--shadow) | -| .site-form | backdrop-filter | blur(16px) | -| .site-form | -webkit-backdrop-filter | blur(16px) | -| .site-form .meta | display | none | -| .site-form form | display | grid | -| .site-form form | grid-template-columns | "minmax(0, 1fr) minmax(0, 1fr)" | -| .site-form form | column-gap | var(--space-5) | -| .site-form form | row-gap | var(--space-5) | -| .site-form form | gap | var(--space-5) | -| .site-form form | margin | "0" | -| .site-form form | width | "100%" | -| .site-form form | max-width | "100%" | -| .site-form label | display | grid | -| .site-form label | gap | var(--space-2) | -| .site-form label | margin | "0" | -| .site-form label | min-width | "0" | -| .site-form label | font-weight | "400" | -| .site-form label | color | var(--gold) | -| .site-form label | font-size | "0.78rem" | -| .site-form label | letter-spacing | "0.16em" | -| .site-form label | text-transform | uppercase | -| .site-form label:nth-child(1) | grid-column | "1" | -| .site-form label:nth-child(2) | grid-column | "2" | -| .site-form label:nth-child(n+3) | grid-column | "1 / -1" | -| .site-form .actions | grid-column | "1 / -1" | -| .site-form input | -webkit-appearance | none | -| .site-form textarea | -webkit-appearance | none | -| .site-form input | appearance | none | -| .site-form textarea | appearance | none | -| .site-form input | box-sizing | border-box | -| .site-form textarea | box-sizing | border-box | -| .site-form input | display | block | -| .site-form textarea | display | block | -| .site-form input | width | "100%" | -| .site-form textarea | width | "100%" | -| .site-form input | height | "2.75rem" | -| .site-form textarea | min-height | "10rem" | -| .site-form label:nth-child(4) textarea | min-height | "14rem" | -| .site-form textarea | resize | vertical | -| .site-form input | padding | "0 0.9rem" | -| .site-form textarea | padding | "0.75rem 0.9rem" | -| .site-form input | border | 1px solid var(--border) | -| .site-form textarea | border | 1px solid var(--border) | -| .site-form input | border-radius | var(--radius-sm) | -| .site-form textarea | border-radius | var(--radius-sm) | -| .site-form input | background | "rgba(0,0,0,.4)" | -| .site-form textarea | background | "rgba(0,0,0,.4)" | -| .site-form input | color | var(--paper) | -| .site-form textarea | color | var(--paper) | -| .site-form input | font | inherit | -| .site-form textarea | font | inherit | -| .site-form input | font-size | "0.95rem" | -| .site-form textarea | font-size | "0.95rem" | -| .site-form input | line-height | "1.4" | -| .site-form textarea | line-height | "1.65" | -| .site-form input | transition | "border-color .2s ease, box-shadow .2s ease" | -| .site-form textarea | transition | "border-color .2s ease, box-shadow .2s ease" | -| .site-form input:hover | border-color | var(--gold-dim) | -| .site-form textarea:hover | border-color | var(--gold-dim) | -| .site-form input:focus | outline | none | -| .site-form textarea:focus | outline | none | -| .site-form input:focus | border-color | var(--gold) | -| .site-form textarea:focus | border-color | var(--gold) | -| .site-form input:focus | box-shadow | var(--ring) | -| .site-form textarea:focus | box-shadow | var(--ring) | -| .site-form input[readonly] | background | "rgba(0,0,0,.25)" | -| .site-form input[readonly] | color | var(--paper-faint) | -| .site-form .err | color | var(--danger) | -| .site-form .err | font-size | "0.8rem" | -| .site-form .err | font-weight | "500" | -| .site-form .err | letter-spacing | "0.04em" | -| .site-form .actions | display | flex | -| .site-form .actions | align-items | center | -| .site-form .actions | gap | var(--space-4) | -| .site-form .actions | margin-top | var(--space-2) | -| .site-form .actions | flex-wrap | wrap | -| .site-form button | -webkit-appearance | none | -| .site-form button | appearance | none | -| .site-form button | height | "2.75rem" | -| .site-form button | padding | "0 1.35rem" | -| .site-form button | background | "linear-gradient(135deg, #f5e6c8, var(--gold))" | -| .site-form button | color | var(--ink) | -| .site-form button | border | "0" | -| .site-form button | border-radius | 999px | -| .site-form button | font-weight | "600" | -| .site-form button | font-size | "0.85rem" | -| .site-form button | letter-spacing | "0.12em" | -| .site-form button | cursor | pointer | -| .site-form button | box-shadow | "0 8px 28px rgba(212,175,55,.28)" | -| .site-form button | transition | "transform .2s ease, box-shadow .2s ease, filter .2s ease" | -| .site-form button:hover | filter | brightness(1.06) | -| .site-form button:hover | transform | "translateY(-1px)" | -| .site-form button:hover | box-shadow | "0 12px 36px rgba(212,175,55,.4)" | -| .site-form .actions a | color | var(--paper-faint) | -| .site-form .actions a | font-weight | "400" | -| .site-form .actions a | text-decoration | none | -| .site-form .actions a | font-size | "0.85rem" | -| .site-form .actions a | letter-spacing | "0.08em" | -| .site-form .actions a:hover | color | var(--gold) | -| .flash.err | color | var(--danger) | -| .flash.err | font-weight | "500" | +Original card, form, flash and administration state declarations. -*`widgets`* +Hover and focus rules, field widths, action rows and desk-specific styles remain in their original order. The native form resource owns validation and submission. Theme projection changes only structural addresses; a visual form error is not proof that a server rejected data, so keep real failed and successful submissions in acceptance. + +Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. + +Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="widgets"))*. + + +## _compile + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | text | required | Exact original section in shell.tables.md | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | One theme section compiled at its original selectors | + +Use `name` with fs.read and plugin on the site root. Native reading preserves original values and geometry; the style compiler handles selectors, media and keyframes. This retained helper intentionally keeps old-shell addresses for migration comparison. Current serving uses styles/index for explicit View targets. A missing section remains diagnostic, and returned text neither writes a file nor proves the new structure is styled. + +We **declarations = [Read this section's actual original declarations](document.read_table(path="styles/shell.tables.md", title=`name`))**. +Return *[Compile original addresses for retained comparison](web.make_style(name=`name`, table=`declarations`))*. ## css -**v = > vars** -**m = > motion** -**l = > layout** -**r = > responsive** -**c = > chrome** -**w = > widgets** -**css_v = > web.make_style name="vars" table=v** -**css_m = > web.make_style name="motion" table=m** -**css_l = > web.make_style name="layout" table=l** -**css_r = > web.make_style name="responsive" table=r** -**css_c = > web.make_style name="chrome" table=c** -**css_w = > web.make_style name="widgets" table=w** +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Baseline CSS preserving the six original areas and cascade | -`parts` = +Grant fs.read and plugin on the site root. Compile tokens, keyframes, layout, responsive, chrome and widgets in their original order and concatenate them exactly as before. Named properties remain independently readable but are not added to this baseline, which would change its original cascade; the View entry restores them at actual semantic targets. -| css | -|-----| -| `css_v` | -| `css_m` | -| `css_l` | -| `css_r` | -| `css_c` | -| `css_w` | +The current site loads styles/index output rather than this old-shell baseline. Equal hashes prove retained compilation, not selector reach, font delivery or mobile geometry. Pair verify's actual row comparison with browser acceptance, and let the serving workflow explicitly write the actual projected theme. -**out = > text.str_join xs=`parts` sep=""** -*out* +`names` = + +| name | +|---| +| vars | +| motion | +| layout | +| responsive | +| chrome | +| widgets | + +We **parts = [Start the ordered compiled sections](table.empty_list())**. +- [Compile each area in the declared cascade order](for names as name) + We **css = [Compile the selected theme area](_compile(name=`name`))** and **parts = [Preserve its original position](table.append(list=`parts`, item=`css`))**. +Return *[Join the compiled sections without changing separators](text.str_join(xs=`parts`, sep=""))*. diff --git a/examples/web-site/styles/shell.tables.md b/examples/web-site/styles/shell.tables.md new file mode 100644 index 0000000..98fa364 --- /dev/null +++ b/examples/web-site/styles/shell.tables.md @@ -0,0 +1,602 @@ +# Theme declarations + +Literal theme declarations. Callable use and CSS assembly are documented next to this file in shell.mq.md. Each section preserves one native table, including its column names and literal types. + +## vars + +Palette, typefaces, spacing and elevation tokens used by every region. + +| selector | property | value | +|----------|----------|-------| +| :root | --ink | #0a0809 | +| :root | --ink-lift | #141012 | +| :root | --wine | #6b1e3a | +| :root | --wine-soft | rgba(107,30,58,0.35) | +| :root | --gold | #d4af37 | +| :root | --gold-dim | rgba(212,175,55,0.45) | +| :root | --gold-soft | rgba(212,175,55,0.12) | +| :root | --paper | rgba(255,248,240,0.92) | +| :root | --paper-dim | rgba(255,248,240,0.72) | +| :root | --paper-faint | rgba(255,248,240,0.48) | +| :root | --glass | rgba(20,12,18,0.72) | +| :root | --glass-strong | rgba(20,12,18,0.88) | +| :root | --border | rgba(212,175,55,0.22) | +| :root | --border-soft | rgba(212,175,55,0.12) | +| :root | --danger | #e8a0a8 | +| :root | --radius | 4px | +| :root | --radius-sm | 2px | +| :root | --space-2 | 8px | +| :root | --space-3 | 12px | +| :root | --space-4 | 16px | +| :root | --space-5 | 20px | +| :root | --space-6 | 24px | +| :root | --space-8 | 32px | +| :root | --text | 16px | +| :root | --leading | "1.75" | +| :root | --shadow | "0 24px 80px rgba(0,0,0,.55), inset 0 1px 0 rgba(255,255,255,.06)" | +| :root | --shadow-card | "0 12px 40px rgba(107,30,58,.35)" | +| :root | --ring | "0 0 0 2px rgba(212,175,55,.35)" | +| :root | --serif | "'Noto Serif SC', 'Source Serif 4', Georgia, serif" | +| :root | --sans | "'Noto Sans SC', 'IBM Plex Sans', system-ui, sans-serif" | +| :root | --display | "'Great Vibes', 'Allura', cursive" | +| :root | --mono | "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace" | +| ::selection | background | rgba(212,175,55,0.35) | +| ::selection | color | var(--paper) | + +## motion + +Entrance, floating, particle and glow keyframes; animation timings remain in consuming selectors. + +| selector | property | value | +|----------|----------|-------| +| @keyframes rise 0% | opacity | "0" | +| @keyframes rise 0% | transform | translateY(14px) | +| @keyframes rise 100% | opacity | "1" | +| @keyframes rise 100% | transform | translateY(0) | +| @keyframes float 0% | transform | translateY(0) | +| @keyframes float 0% | opacity | "0.7" | +| @keyframes float 50% | transform | translateY(6px) | +| @keyframes float 50% | opacity | "1" | +| @keyframes float 100% | transform | translateY(0) | +| @keyframes float 100% | opacity | "0.7" | +| @keyframes goldPulse 0% | text-shadow | "0 0 24px rgba(212,175,55,.2)" | +| @keyframes goldPulse 50% | text-shadow | "0 0 48px rgba(212,175,55,.45)" | +| @keyframes goldPulse 100% | text-shadow | "0 0 24px rgba(212,175,55,.2)" | +| @keyframes particleDrift 0% | transform | translate3d(0,0,0) | +| @keyframes particleDrift 50% | transform | translate3d(-2.5vw, 1.5vh, 0) | +| @keyframes particleDrift 100% | transform | translate3d(0,0,0) | +| @keyframes particleDrift2 0% | transform | translate3d(0,0,0) | +| @keyframes particleDrift2 50% | transform | translate3d(2vw, -2vh, 0) | +| @keyframes particleDrift2 100% | transform | translate3d(0,0,0) | +| @keyframes nebulaPulse 0% | opacity | "0.55" | +| @keyframes nebulaPulse 50% | opacity | "0.9" | +| @keyframes nebulaPulse 100% | opacity | "0.55" | + +## layout + +Page grid, background, typography, navigation and main content rules. + +| selector | property | value | +|----------|----------|-------| +| * | box-sizing | border-box | +| html | scroll-behavior | smooth | +| html | -webkit-text-size-adjust | 100% | +| body | margin | "0" | +| body | min-height | 100vh | +| body | font-family | var(--sans) | +| body | font-weight | "400" | +| body | font-size | var(--text) | +| body | line-height | var(--leading) | +| body | color | var(--paper) | +| body | background | var(--ink) | +| body | background-image | "radial-gradient(ellipse 90% 55% at 50% -15%, rgba(107,30,58,.5), transparent 58%), radial-gradient(ellipse 55% 45% at 92% 75%, rgba(212,175,55,.14), transparent 55%), radial-gradient(ellipse 40% 35% at 8% 70%, rgba(107,30,58,.22), transparent 60%), linear-gradient(180deg, #0a0809 0%, #120c10 45%, #0a0809 100%)" | +| body | background-attachment | fixed | +| body | display | grid | +| body | grid-template-rows | "auto 1fr auto" | +| body | -webkit-font-smoothing | antialiased | +| body | position | relative | +| body | overflow-x | hidden | +| body::before | content | '""' | +| body::before | position | fixed | +| body::before | inset | "0" | +| body::before | z-index | "1" | +| body::before | pointer-events | none | +| body::before | opacity | "0.1" | +| body::before | background-image | "url(\"data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E\")" | +| html::before | content | '""' | +| html::before | position | fixed | +| html::before | inset | "0" | +| html::before | z-index | "0" | +| html::before | pointer-events | none | +| html::before | background-image | "radial-gradient(ellipse 50% 40% at 15% 30%, rgba(107,30,58,.35), transparent 70%), radial-gradient(ellipse 45% 35% at 85% 60%, rgba(212,175,55,.12), transparent 65%), radial-gradient(ellipse 40% 30% at 50% 90%, rgba(107,30,58,.25), transparent 70%)" | +| html::before | animation | "nebulaPulse 12s ease-in-out infinite" | +| body::after | content | '""' | +| body::after | position | fixed | +| body::after | top | "0" | +| body::after | left | "0" | +| body::after | width | "2px" | +| body::after | height | "2px" | +| body::after | z-index | "2" | +| body::after | pointer-events | none | +| body::after | border-radius | 50% | +| body::after | background | transparent | +| body::after | box-shadow | "82vw 15vh 0px 0px rgba(212,175,55,0.55),29vw 18vh 0px 1px rgba(212,175,55,0.25),95vw 70vh 1px 0px rgba(212,175,55,0.55),4vw 12vh 0px 1px rgba(212,175,55,0.35),78vw 4vh 0px 1px rgba(245,230,200,0.5),84vw 90vh 1px 0px rgba(245,230,200,0.5),58vw 76vh 0px 0px rgba(255,248,240,0.4),90vw 55vh 0px 0px rgba(255,248,240,0.4),28vw 98vh 0px 0px rgba(255,248,240,0.4),49vw 13vh 0px 1px rgba(255,248,240,0.4),34vw 6vh 1px 1px rgba(212,175,55,0.25),16vw 49vh 0px 1px rgba(212,175,55,0.55),80vw 47vh 0px 1px rgba(245,230,200,0.5),9vw 6vh 0px 0px rgba(212,175,55,0.25),11vw 30vh 1px 0px rgba(212,175,55,0.55),59vw 82vh 0px 0px rgba(255,248,240,0.4),46vw 27vh 0px 1px rgba(212,175,55,0.25),88vw 83vh 0px 1px rgba(212,175,55,0.55),94vw 32vh 1px 0px rgba(212,175,55,0.35),35vw 82vh 0px 1px rgba(212,175,55,0.25),42vw 99vh 0px 0px rgba(212,175,55,0.55),41vw 52vh 0px 0px rgba(255,248,240,0.4),73vw 92vh 0px 1px rgba(255,248,240,0.4),64vw 51vh 1px 0px rgba(212,175,55,0.25),34vw 18vh 0px 1px rgba(212,175,55,0.35),75vw 55vh 1px 0px rgba(245,230,200,0.5),29vw 18vh 1px 0px rgba(245,230,200,0.5),97vw 7vh 0px 1px rgba(212,175,55,0.55),21vw 88vh 0px 0px rgba(107,30,58,0.45),49vw 77vh 0px 1px rgba(107,30,58,0.45),2vw 88vh 0px 1px rgba(212,175,55,0.25),69vw 97vh 0px 0px rgba(255,248,240,0.4),38vw 56vh 1px 0px rgba(212,175,55,0.35),93vw 93vh 0px 1px rgba(255,248,240,0.4),14vw 81vh 0px 0px rgba(255,248,240,0.4),48vw 98vh 0px 1px rgba(212,175,55,0.35),42vw 63vh 0px 0px rgba(212,175,55,0.55),40vw 31vh 0px 1px rgba(212,175,55,0.55),11vw 11vh 1px 0px rgba(212,175,55,0.25),98vw 69vh 0px 1px rgba(212,175,55,0.35),61vw 71vh 0px 1px rgba(212,175,55,0.35),78vw 55vh 0px 1px rgba(212,175,55,0.35),40vw 52vh 0px 0px rgba(212,175,55,0.25),67vw 58vh 0px 0px rgba(212,175,55,0.55),9vw 44vh 0px 1px rgba(212,175,55,0.55),29vw 1vh 0px 0px rgba(212,175,55,0.55),9vw 5vh 0px 1px rgba(255,248,240,0.4),31vw 36vh 1px 0px rgba(212,175,55,0.25),70vw 17vh 1px 0px rgba(212,175,55,0.25),61vw 53vh 0px 0px rgba(212,175,55,0.35),85vw 56vh 1px 0px rgba(255,248,240,0.4),60vw 94vh 0px 0px rgba(212,175,55,0.55),52vw 94vh 0px 0px rgba(255,248,240,0.4),25vw 25vh 1px 0px rgba(245,230,200,0.5),55vw 24vh 1px 0px rgba(255,248,240,0.4),10vw 57vh 0px 0px rgba(245,230,200,0.5),84vw 70vh 0px 0px rgba(212,175,55,0.55),22vw 53vh 1px 0px rgba(107,30,58,0.45),52vw 8vh 1px 0px rgba(212,175,55,0.35),50vw 34vh 0px 0px rgba(107,30,58,0.45),90vw 94vh 1px 0px rgba(245,230,200,0.5),25vw 38vh 0px 1px rgba(212,175,55,0.35),95vw 70vh 0px 0px rgba(212,175,55,0.55),7vw 75vh 0px 0px rgba(107,30,58,0.45),66vw 11vh 0px 1px rgba(212,175,55,0.35),9vw 87vh 1px 0px rgba(212,175,55,0.35),73vw 32vh 0px 1px rgba(245,230,200,0.5),11vw 54vh 0px 0px rgba(212,175,55,0.25),27vw 86vh 0px 0px rgba(212,175,55,0.25),34vw 51vh 0px 0px rgba(212,175,55,0.35),41vw 97vh 0px 0px rgba(212,175,55,0.55),80vw 73vh 0px 1px rgba(212,175,55,0.55)" | +| body::after | animation | "particleDrift 48s ease-in-out infinite" | +| html::after | content | '""' | +| html::after | position | fixed | +| html::after | top | "0" | +| html::after | left | "0" | +| html::after | width | "1px" | +| html::after | height | "1px" | +| html::after | z-index | "2" | +| html::after | pointer-events | none | +| html::after | border-radius | 50% | +| html::after | background | transparent | +| html::after | box-shadow | "28vw 65vh 0 0 rgba(255,248,240,0.25),17vw 45vh 0 0 rgba(212,175,55,0.3),32vw 48vh 0 0 rgba(255,248,240,0.25),21vw 57vh 0 0 rgba(107,30,58,0.3),91vw 39vh 0 0 rgba(107,30,58,0.3),84vw 68vh 0 0 rgba(212,175,55,0.3),86vw 71vh 0 0 rgba(255,248,240,0.25),85vw 14vh 0 0 rgba(212,175,55,0.3),34vw 15vh 0 0 rgba(212,175,55,0.3),96vw 71vh 0 0 rgba(212,175,55,0.3),35vw 37vh 0 0 rgba(107,30,58,0.3),27vw 92vh 0 0 rgba(255,248,240,0.25),27vw 88vh 0 0 rgba(107,30,58,0.3),34vw 65vh 0 0 rgba(255,248,240,0.25),33vw 7vh 0 0 rgba(212,175,55,0.3),82vw 55vh 0 0 rgba(255,248,240,0.25),6vw 1vh 0 0 rgba(255,248,240,0.25),99vw 17vh 0 0 rgba(107,30,58,0.3),34vw 21vh 0 0 rgba(107,30,58,0.3),57vw 71vh 0 0 rgba(107,30,58,0.3),55vw 72vh 0 0 rgba(212,175,55,0.3),15vw 10vh 0 0 rgba(107,30,58,0.3),20vw 70vh 0 0 rgba(212,175,55,0.3),48vw 75vh 0 0 rgba(107,30,58,0.3),19vw 56vh 0 0 rgba(212,175,55,0.3),6vw 40vh 0 0 rgba(255,248,240,0.25),6vw 46vh 0 0 rgba(212,175,55,0.3),88vw 32vh 0 0 rgba(107,30,58,0.3),14vw 46vh 0 0 rgba(107,30,58,0.3),53vw 80vh 0 0 rgba(107,30,58,0.3),20vw 31vh 0 0 rgba(212,175,55,0.3),23vw 53vh 0 0 rgba(212,175,55,0.3),23vw 95vh 0 0 rgba(255,248,240,0.25),53vw 86vh 0 0 rgba(107,30,58,0.3),32vw 35vh 0 0 rgba(212,175,55,0.3),90vw 14vh 0 0 rgba(255,248,240,0.25),5vw 61vh 0 0 rgba(212,175,55,0.3),26vw 59vh 0 0 rgba(255,248,240,0.25),40vw 30vh 0 0 rgba(212,175,55,0.3),4vw 85vh 0 0 rgba(212,175,55,0.3),52vw 43vh 0 0 rgba(255,248,240,0.25),9vw 99vh 0 0 rgba(255,248,240,0.25),45vw 83vh 0 0 rgba(107,30,58,0.3),52vw 87vh 0 0 rgba(107,30,58,0.3),43vw 4vh 0 0 rgba(212,175,55,0.3),34vw 23vh 0 0 rgba(107,30,58,0.3),34vw 5vh 0 0 rgba(212,175,55,0.3),77vw 56vh 0 0 rgba(255,248,240,0.25)" | +| html::after | animation | "particleDrift2 64s ease-in-out infinite" | +| body.has-sidebar | grid-template-columns | "14rem minmax(0, 1fr)" | +| body.has-sidebar | grid-template-areas | '"top top" "side main" "foot foot"' | +| body.no-sidebar | grid-template-areas | '"top" "main" "foot"' | +| body.layout-stacked | grid-template-areas | '"top" "main" "foot"' | +| body.is-desk | grid-template-areas | '"top" "main" "foot"' | +| header.topnav | grid-area | top | +| aside.side | grid-area | side | +| main.main | grid-area | main | +| footer.foot | grid-area | foot | +| header.topnav | position | relative | +| header.topnav | z-index | "20" | +| aside.side | position | relative | +| aside.side | z-index | "10" | +| main.main | position | relative | +| main.main | z-index | "10" | +| footer.foot | position | relative | +| footer.foot | z-index | "10" | +| main.main | width | "100%" | +| main.main | max-width | "min(78rem, 100%)" | +| main.main | padding | "var(--space-8) var(--space-6) 4rem" | +| main.main | animation | "rise .8s cubic-bezier(.22,1,.36,1) both" | +| a | color | var(--gold) | +| a | text-decoration | none | +| a | transition | color 0.25s ease | +| a:hover | color | #f5e6c8 | +| code | font-family | var(--mono) | +| code | font-size | "0.82em" | +| code | font-weight | "400" | +| code | background | rgba(0,0,0,0.35) | +| code | border | 1px solid var(--border-soft) | +| code | padding | "0.12em 0.45em" | +| code | border-radius | var(--radius-sm) | +| code | color | var(--gold) | + +## responsive + +Media conditions that collapse the side panel and card grid on small screens. + +| media | selector | property | value | +|-------|----------|----------|-------| +| (max-width: 860px) | body.has-sidebar | grid-template-columns | 1fr | +| (max-width: 860px) | body.has-sidebar | grid-template-areas | '"top" "main" "side" "foot"' | +| (max-width: 860px) | aside.side | border-right | "0" | +| (max-width: 860px) | aside.side | border-top | 1px solid var(--border-soft) | +| (max-width: 860px) | main.main | padding | "var(--space-6) var(--space-4) var(--space-8)" | +| (max-width: 860px) | .content.cards | grid-template-columns | 1fr | +| (max-width: 860px) | .site-form form | grid-template-columns | 1fr | +| (max-width: 860px) | .site-form label:nth-child(1) | grid-column | "1 / -1" | +| (max-width: 860px) | .site-form label:nth-child(2) | grid-column | "1 / -1" | +| (max-width: 860px) | header.topnav | padding | "0.85rem var(--space-4)" | +| (max-width: 860px) | .intro_title | font-size | "2.4rem" | +| (prefers-reduced-motion: reduce) | main.main | animation | none | +| (prefers-reduced-motion: reduce) | .kicker | animation | none | +| (prefers-reduced-motion: reduce) | article.card | transition | none | +| (prefers-reduced-motion: reduce) | body::after | animation | none | +| (prefers-reduced-motion: reduce) | html::after | animation | none | +| (prefers-reduced-motion: reduce) | html::before | animation | none | + +## topnav + +Property/value style attached to the top navigation binding. + +| property | value | +|----------|-------| +| position | sticky | +| top | "0" | +| z-index | "40" | +| display | flex | +| align-items | center | +| justify-content | flex-start | +| gap | var(--space-4) | +| padding | "1rem var(--space-6)" | +| background | "linear-gradient(180deg, rgba(10,8,9,.92) 0%, rgba(10,8,9,.55) 70%, transparent 100%)" | +| backdrop-filter | blur(10px) | +| -webkit-backdrop-filter | blur(10px) | +| border-bottom | 1px solid var(--border-soft) | + +## side_panel + +Property/value style for the secondary navigation and explanatory panel. + +| property | value | +|----------|-------| +| background | "rgba(10,8,9,.55)" | +| padding | "var(--space-6) var(--space-4)" | +| border-right | 1px solid var(--border-soft) | + +## footer + +Property/value style for the closing navigation and attribution. + +| property | value | +|----------|-------| +| color | var(--paper-faint) | +| font-size | "0.8rem" | +| letter-spacing | "0.08em" | +| padding | "var(--space-5) var(--space-6)" | +| border-top | 1px solid var(--border-soft) | +| background | "rgba(10,8,9,.75)" | + +## card_title + +Property/value typography for a linked article title. + +| property | value | +|----------|-------| +| font-family | var(--serif) | +| font-size | "1.15rem" | +| font-weight | "600" | +| margin | "0 0 var(--space-2)" | +| color | var(--gold) | +| letter-spacing | "0.02em" | +| line-height | "1.35" | + +## card_body + +Property/value typography for an article's summary. + +| property | value | +|----------|-------| +| color | var(--paper-dim) | +| margin | "0" | +| line-height | "1.65" | +| font-size | "0.9rem" | +| font-weight | "400" | +| display | "-webkit-box" | +| -webkit-box-orient | vertical | +| -webkit-line-clamp | "3" | +| overflow | hidden | + +## chrome + +Grouped selectors for introduction panels, claims, reading steps and full article content. + +| selector | property | value | +|----------|----------|-------| +| .main-intro | background | var(--glass) | +| .main-intro | border | 1px solid var(--border) | +| .main-intro | border-radius | var(--radius) | +| .main-intro | padding | "2.25rem 1.75rem 1.85rem" | +| .main-intro | box-shadow | var(--shadow) | +| .main-intro | backdrop-filter | blur(16px) | +| .main-intro | -webkit-backdrop-filter | blur(16px) | +| .main-intro | margin-bottom | var(--space-8) | +| .main-intro > .claim | display | flex | +| .main-intro > .claim | flex-wrap | wrap | +| .main-intro > .claim | gap | var(--space-2) | +| .main-intro > .claim | margin | "0 0 var(--space-6)" | +| .main-intro > .steps | margin | "0" | +| .main-intro > .steps | padding | "var(--space-5) var(--space-5) var(--space-5) 1.5rem" | +| .main-intro > .steps | color | var(--paper-dim) | +| .main-intro > .steps | background | "rgba(0,0,0,.35)" | +| .main-intro > .steps | border | 1px solid var(--border-soft) | +| .main-intro > .steps | border-left | 2px solid var(--gold-dim) | +| .main-intro > .steps | border-radius | var(--radius) | +| .main-intro > .steps | font-size | "0.95rem" | +| .main-intro > .steps | letter-spacing | "0.02em" | +| .main-intro > .steps a | color | var(--gold) | +| .main-intro > .steps a | font-weight | "500" | +| .main-intro > .steps a:hover | color | #f5e6c8 | +| .article | background | var(--glass) | +| .article | border | 1px solid var(--border) | +| .article | border-radius | var(--radius) | +| .article | padding | "2rem 1.75rem" | +| .article | box-shadow | var(--shadow) | +| .article | backdrop-filter | blur(16px) | +| .article | -webkit-backdrop-filter | blur(16px) | +| .article-title | font-family | var(--serif) | +| .article-title | font-size | "clamp(1.75rem, 4vw, 2.35rem)" | +| .article-title | font-weight | "600" | +| .article-title | color | var(--gold) | +| .article-title | letter-spacing | "0.04em" | +| .article-title | margin | "0 0 var(--space-5)" | +| .article-title | line-height | "1.25" | +| .article-body | color | var(--paper-dim) | +| .article-body | font-family | var(--sans) | +| .article-body | font-size | "1.02rem" | +| .article-body | line-height | "1.85" | +| .article-body.md p | margin | "0 0 1.1rem" | +| .article-body.md a | color | var(--gold) | +| article.card | cursor | pointer | +| a.card-link | color | inherit | +| a.card-link | text-decoration | none | +| a.card-link:hover | color | inherit | + +## kicker + +Property/value typography for the small introductory category label. + +| property | value | +|----------|-------| +| letter-spacing | "0.32em" | +| text-transform | uppercase | +| font-size | "0.72rem" | +| color | var(--gold-dim) | +| margin | "0 0 var(--space-4)" | +| font-weight | "400" | +| font-family | var(--sans) | +| animation | "float 2.8s ease-in-out infinite" | + +## intro_title + +Property/value typography and responsive size for the main introduction heading. + +| property | value | +|----------|-------| +| font-family | var(--display) | +| font-size | "clamp(3rem, 10vw, 4.8rem)" | +| font-weight | "400" | +| line-height | "1.15" | +| letter-spacing | "0.04em" | +| margin | "0 0 var(--space-4)" | +| color | transparent | +| background | "linear-gradient(135deg, #f5e6c8 0%, var(--gold) 42%, var(--wine) 100%)" | +| -webkit-background-clip | text | +| background-clip | text | +| animation | "goldPulse 4.5s ease-in-out infinite" | + +## lede + +Property/value typography for the supporting introduction paragraph. + +| property | value | +|----------|-------| +| color | var(--paper-dim) | +| max-width | "34rem" | +| line-height | "1.85" | +| margin | "0 0 var(--space-5)" | +| font-size | "1.05rem" | +| letter-spacing | "0.02em" | +| font-weight | "400" | +| font-family | var(--sans) | + +## claim + +Property/value style used by the short feature claims. + +| property | value | +|----------|-------| +| display | inline-flex | +| align-items | center | +| padding | "0.2rem 0.65rem" | +| border-radius | var(--radius-sm) | +| background | var(--wine-soft) | +| color | #f0c9d4 | +| font-size | "0.68rem" | +| font-weight | "500" | +| letter-spacing | "0.14em" | +| border | 1px solid rgba(107,30,58,0.5) | + +## step + +Initial demonstration records in their original column-oriented shape; ids and stable slugs retain their meaning. + +| property | value | +|----------|-------| +| margin | "0.55rem 0" | + +## widgets + +Cards, forms, flash messages and administration controls, including hover and focus states. + +| selector | property | value | +|----------|----------|-------| +| ul.nav | display | flex | +| ul.nav | flex-wrap | wrap | +| ul.nav | align-items | center | +| ul.nav | gap | "0.35rem 1rem" | +| ul.nav | list-style | none | +| ul.nav | margin | "0" | +| ul.nav | padding | "0" | +| ul.nav a | display | inline-flex | +| ul.nav a | align-items | center | +| ul.nav a | text-decoration | none | +| ul.nav a | color | var(--paper-dim) | +| ul.nav a | padding | "0.35rem 0" | +| ul.nav a | border-radius | "0" | +| ul.nav a | font-weight | "400" | +| ul.nav a | font-size | "0.8rem" | +| ul.nav a | letter-spacing | "0.14em" | +| ul.nav a | transition | color 0.25s ease | +| ul.nav a:hover | background | transparent | +| ul.nav a:hover | color | var(--gold) | +| ul.nav a:hover | text-decoration | none | +| ul.nav a[href="/admin"] | color | var(--gold) | +| ul.nav a[href="/admin"] | letter-spacing | "0.18em" | +| ul.nav a[href="/admin"] | border-bottom | 1px solid var(--gold-dim) | +| ul.side-nav a[href="/admin"] | color | var(--gold) | +| body.is-desk header.topnav | border-bottom | 1px solid rgba(107,30,58,0.55) | +| body.is-desk header.topnav | box-shadow | "0 12px 40px rgba(107,30,58,.18)" | +| body.is-desk .main-intro | border-left | 3px solid var(--wine) | +| body.is-desk .site-form | border-color | rgba(107,30,58,0.45) | +| body.is-desk .site-form | box-shadow | "0 0 0 1px rgba(212,175,55,.12), 0 18px 48px rgba(0,0,0,.35)" | +| body.is-desk .content.cards | margin-top | var(--space-6) | +| ul.nav li:first-child a | font-family | var(--display) | +| ul.nav li:first-child a | font-weight | "400" | +| ul.nav li:first-child a | color | var(--gold) | +| ul.nav li:first-child a | font-size | "1.85rem" | +| ul.nav li:first-child a | letter-spacing | "0.06em" | +| ul.nav li:first-child a | padding | "0.1rem 0.2rem 0.1rem 0" | +| ul.nav li:first-child a:hover | background | transparent | +| ul.nav li:first-child a:hover | color | #f5e6c8 | +| .side-label | display | block | +| .side-label | font-size | "0" | +| .side-label | margin | "0 0 var(--space-4)" | +| .side-label::before | content | '"Path"' | +| .side-label::before | display | block | +| .side-label::before | font-size | "0.68rem" | +| .side-label::before | letter-spacing | "0.28em" | +| .side-label::before | text-transform | uppercase | +| .side-label::before | color | var(--gold-dim) | +| .side-label::before | font-weight | "400" | +| ul.side-nav | list-style | none | +| ul.side-nav | margin | "0" | +| ul.side-nav | padding | "0" | +| ul.side-nav | display | grid | +| ul.side-nav | gap | "2px" | +| ul.side-nav | border-left | 1px solid var(--border) | +| ul.side-nav | padding-left | "0.85rem" | +| ul.side-nav | margin-left | "0.25rem" | +| ul.side-nav a | display | block | +| ul.side-nav a | text-decoration | none | +| ul.side-nav a | color | var(--paper-dim) | +| ul.side-nav a | padding | "0.45rem 0.35rem" | +| ul.side-nav a | border-radius | "0" | +| ul.side-nav a | font-weight | "400" | +| ul.side-nav a | font-size | "0.88rem" | +| ul.side-nav a | letter-spacing | "0.06em" | +| ul.side-nav a | border | "0" | +| ul.side-nav a | position | relative | +| ul.side-nav a:hover | background | transparent | +| ul.side-nav a:hover | border-color | transparent | +| ul.side-nav a:hover | color | var(--gold) | +| ul.side-nav a:hover | text-decoration | none | +| ul.side-nav a:hover | box-shadow | none | +| ul.foot-nav | display | flex | +| ul.foot-nav | gap | var(--space-4) | +| ul.foot-nav | list-style | none | +| ul.foot-nav | margin | "0" | +| ul.foot-nav | padding | "0" | +| ul.foot-nav a | color | var(--paper-faint) | +| ul.foot-nav a | font-weight | "400" | +| ul.foot-nav a | letter-spacing | "0.1em" | +| ul.foot-nav a | font-size | "0.78rem" | +| ul.foot-nav a:hover | color | var(--gold) | +| .content.cards | display | grid | +| .content.cards | gap | var(--space-4) | +| .content.cards | margin-top | "0" | +| .content.cards | grid-template-columns | "repeat(auto-fill, minmax(16rem, 1fr))" | +| article.card | background | "rgba(0,0,0,.35)" | +| article.card | border | 1px solid var(--border-soft) | +| article.card | border-radius | var(--radius-sm) | +| article.card | padding | "1.35rem 1.15rem" | +| article.card | box-shadow | none | +| article.card | transition | "border-color .35s ease, box-shadow .35s ease, transform .35s ease" | +| article.card:hover | transform | "translateY(-3px)" | +| article.card:hover | box-shadow | var(--shadow-card) | +| article.card:hover | border-color | var(--gold-dim) | +| .site-form | background | var(--glass) | +| .site-form | border | 1px solid var(--border) | +| .site-form | border-radius | var(--radius) | +| .site-form | padding | "var(--space-6) var(--space-6) var(--space-7, 1.75rem)" | +| .site-form | margin | "0 0 var(--space-6)" | +| .site-form | max-width | "100%" | +| .site-form | width | "100%" | +| .site-form | box-shadow | var(--shadow) | +| .site-form | backdrop-filter | blur(16px) | +| .site-form | -webkit-backdrop-filter | blur(16px) | +| .site-form .meta | display | none | +| .site-form form | display | grid | +| .site-form form | grid-template-columns | "minmax(0, 1fr) minmax(0, 1fr)" | +| .site-form form | column-gap | var(--space-5) | +| .site-form form | row-gap | var(--space-5) | +| .site-form form | gap | var(--space-5) | +| .site-form form | margin | "0" | +| .site-form form | width | "100%" | +| .site-form form | max-width | "100%" | +| .site-form label | display | grid | +| .site-form label | gap | var(--space-2) | +| .site-form label | margin | "0" | +| .site-form label | min-width | "0" | +| .site-form label | font-weight | "400" | +| .site-form label | color | var(--gold) | +| .site-form label | font-size | "0.78rem" | +| .site-form label | letter-spacing | "0.16em" | +| .site-form label | text-transform | uppercase | +| .site-form label:nth-child(1) | grid-column | "1" | +| .site-form label:nth-child(2) | grid-column | "2" | +| .site-form label:nth-child(n+3) | grid-column | "1 / -1" | +| .site-form .actions | grid-column | "1 / -1" | +| .site-form input | -webkit-appearance | none | +| .site-form textarea | -webkit-appearance | none | +| .site-form input | appearance | none | +| .site-form textarea | appearance | none | +| .site-form input | box-sizing | border-box | +| .site-form textarea | box-sizing | border-box | +| .site-form input | display | block | +| .site-form textarea | display | block | +| .site-form input | width | "100%" | +| .site-form textarea | width | "100%" | +| .site-form input | height | "2.75rem" | +| .site-form textarea | min-height | "10rem" | +| .site-form label:nth-child(4) textarea | min-height | "14rem" | +| .site-form textarea | resize | vertical | +| .site-form input | padding | "0 0.9rem" | +| .site-form textarea | padding | "0.75rem 0.9rem" | +| .site-form input | border | 1px solid var(--border) | +| .site-form textarea | border | 1px solid var(--border) | +| .site-form input | border-radius | var(--radius-sm) | +| .site-form textarea | border-radius | var(--radius-sm) | +| .site-form input | background | "rgba(0,0,0,.4)" | +| .site-form textarea | background | "rgba(0,0,0,.4)" | +| .site-form input | color | var(--paper) | +| .site-form textarea | color | var(--paper) | +| .site-form input | font | inherit | +| .site-form textarea | font | inherit | +| .site-form input | font-size | "0.95rem" | +| .site-form textarea | font-size | "0.95rem" | +| .site-form input | line-height | "1.4" | +| .site-form textarea | line-height | "1.65" | +| .site-form input | transition | "border-color .2s ease, box-shadow .2s ease" | +| .site-form textarea | transition | "border-color .2s ease, box-shadow .2s ease" | +| .site-form input:hover | border-color | var(--gold-dim) | +| .site-form textarea:hover | border-color | var(--gold-dim) | +| .site-form input:focus | outline | none | +| .site-form textarea:focus | outline | none | +| .site-form input:focus | border-color | var(--gold) | +| .site-form textarea:focus | border-color | var(--gold) | +| .site-form input:focus | box-shadow | var(--ring) | +| .site-form textarea:focus | box-shadow | var(--ring) | +| .site-form input[readonly] | background | "rgba(0,0,0,.25)" | +| .site-form input[readonly] | color | var(--paper-faint) | +| .site-form .err | color | var(--danger) | +| .site-form .err | font-size | "0.8rem" | +| .site-form .err | font-weight | "500" | +| .site-form .err | letter-spacing | "0.04em" | +| .site-form .actions | display | flex | +| .site-form .actions | align-items | center | +| .site-form .actions | gap | var(--space-4) | +| .site-form .actions | margin-top | var(--space-2) | +| .site-form .actions | flex-wrap | wrap | +| .site-form button | -webkit-appearance | none | +| .site-form button | appearance | none | +| .site-form button | height | "2.75rem" | +| .site-form button | padding | "0 1.35rem" | +| .site-form button | background | "linear-gradient(135deg, #f5e6c8, var(--gold))" | +| .site-form button | color | var(--ink) | +| .site-form button | border | "0" | +| .site-form button | border-radius | 999px | +| .site-form button | font-weight | "600" | +| .site-form button | font-size | "0.85rem" | +| .site-form button | letter-spacing | "0.12em" | +| .site-form button | cursor | pointer | +| .site-form button | box-shadow | "0 8px 28px rgba(212,175,55,.28)" | +| .site-form button | transition | "transform .2s ease, box-shadow .2s ease, filter .2s ease" | +| .site-form button:hover | filter | brightness(1.06) | +| .site-form button:hover | transform | "translateY(-1px)" | +| .site-form button:hover | box-shadow | "0 12px 36px rgba(212,175,55,.4)" | +| .site-form .actions a | color | var(--paper-faint) | +| .site-form .actions a | font-weight | "400" | +| .site-form .actions a | text-decoration | none | +| .site-form .actions a | font-size | "0.85rem" | +| .site-form .actions a | letter-spacing | "0.08em" | +| .site-form .actions a:hover | color | var(--gold) | +| .flash.err | color | var(--danger) | +| .flash.err | font-weight | "500" | diff --git a/examples/web-site/styles/view.tables.md b/examples/web-site/styles/view.tables.md new file mode 100644 index 0000000..ff958db --- /dev/null +++ b/examples/web-site/styles/view.tables.md @@ -0,0 +1,71 @@ +# View geometry adaptation + +These are literal declarations for the explicit View wrappers. The original palette, motion, typography and component properties remain in shell.tables.md. The callable theme entry explains how these small geometry rules connect the recursive frame to that preserved data. + +## geometry + +The basic preview wrapper should inherit this site's own fonts and full width. Resource placeholders remain structural values but their native semantic children participate in the original named grid. Lists use Markdown rather than a private intro binding table. + +| selector | property | value | +|---|---|---| +| .mq-document .mq-view | max-width | none | +| .mq-document .mq-view | margin | 0 | +| .mq-document .mq-view | padding | 0 | +| .mq-document .mq-view | line-height | inherit | +| .mq-document .mq-view | font-family | inherit | +| .mq-document .site-layout | display | grid | +| .mq-document .site-layout | grid-template-rows | auto 1fr auto | +| .mq-document .site-layout | min-height | 100vh | +| .mq-document .site-layout > .slot-nav | display | contents | +| .mq-document .site-layout > .slot-sidebar | display | contents | +| .mq-document .site-layout .main-intro ul | padding | 0 | +| .mq-document .site-layout .main-intro ul | list-style | none | +| .mq-document .site-layout .main-intro li > p | margin | 0 | +| .mq-document .site-layout .main-intro blockquote > p | margin | 0 | + +## selectors + +Only these structural addresses change. The original property, value, media and order remain untouched; this is a site migration table, not a new page language. + +| @ | old | new | +|---|---|---| +| 1 | body.has-sidebar | .site-layout.has-sidebar | +| 2 | body.no-sidebar | .site-layout.no-sidebar | +| 3 | body.layout-stacked | .site-layout.layout-stacked | +| 4 | body.is-desk | .site-layout.is-desk | +| 5 | main.main | section.main | +| 6 | .main-intro > .claim | .main-intro ul | +| 7 | .main-intro > .steps | .main-intro ol | +| 8 | .intro_title | .main-intro h1 | +| 9 | .kicker | .main-intro blockquote | + +## areas + +Compile these original sections in the same cascade order. + +| name | +|---| +| vars | +| motion | +| layout | +| responsive | +| chrome | +| widgets | + + +## properties + +Restore every originally attached named property table at its actual semantic target. The native style compiler adds the leading class dot to each selected name. + +| @ | name | selector | +|---|---|---| +| 1 | topnav | mq-document .site-layout .topnav | +| 2 | side_panel | mq-document .site-layout .side | +| 3 | footer | mq-document .site-layout .foot | +| 4 | card_title | mq-document .site-layout .content.cards h2 | +| 5 | card_body | mq-document .site-layout .content.cards p | +| 6 | kicker | mq-document .site-layout .main-intro blockquote | +| 7 | intro_title | mq-document .site-layout .main-intro h1 | +| 8 | lede | mq-document .site-layout .main-intro .slot-intro-content > p | +| 9 | claim | mq-document .site-layout .main-intro ul > li | +| 10 | step | mq-document .site-layout .main-intro ol > li | diff --git a/examples/web-site/verify.mq.md b/examples/web-site/verify.mq.md new file mode 100644 index 0000000..bbc3ae5 --- /dev/null +++ b/examples/web-site/verify.mq.md @@ -0,0 +1,58 @@ +--- +markup: occlusion +title: Executable theme migration evidence +import: + document: lib/document.mq.md + table: lib/table.mq.md + hash: lib/hash.mq.md + result: lib/result.mq.md + theme: styles/index.mq.md + original: styles/shell.mq.md +--- + +This verification reads actual source declarations and compiles both the retained original and the View projection. It neither certifies the whole site nor replaces HTTP and browser tests. Call theme_values with plugin,fs.read and --fs-root examples/web-site; use an owned copy when validating other site operations. + +## theme_values + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result containing verified original row count and real CSS identities | + +Each of the six original areas is read through the native Markdown table reader. Compare every projected record to its original after removing only selector: values, media, properties, ordering and row count must match. Tokens and keyframe selectors themselves must remain unchanged. A mismatch returns an actual failed Result before claiming preservation. + +The original and projected CSS hashes identify actual compiled outputs; a different View hash is expected because its semantic addresses and wrapper geometry changed. They are not a visual acceptance certificate. Browser tests separately inspect the real palette, title typography, grid, form flow and current records. This tool makes the preserved declarations reviewable without hiding the implementation in another language. + +`areas` = + +| name | +|---| +| vars | +| motion | +| layout | +| responsive | +| chrome | +| widgets | + +We **count = 0**. +- [Compare each actual original area to its projection](for areas as name) + We **columns = [Read the source declaration leaf](document.read_table(path="styles/shell.tables.md", title=`name`))** and **rows = [Retain original row order](table.from_columns(columns=`columns`))** and **projected = [Run the actual selector projection](theme._table(name=`name`))**. + 1. len(`rows`) != len(`projected`) + Return *[Keep a dropped declaration visible](result.error(code="site.theme_rows", message=`name`, operation="theme_values"))*. + We **position = 0**. + - [Compare original property, value and media for every row](for rows as row) + We **actual = [Read the same projected position](table.at(xs=`projected`, i=`position`))** and **before = [Set aside only the original selector](table.delete(map=`row`, key="selector"))** and **after = [Set aside only the projected selector](table.delete(map=`actual`, key="selector"))**. + 1. `before` != `after` + Return *[Keep any changed declaration payload visible](result.error(code="site.theme_value", message=`name`, operation="theme_values"))*. + 1. `name` == "vars" or `name` == "motion" + 1. access(`row`, "selector") != access(`actual`, "selector") + Return *[Keep global token/keyframe addresses unchanged](result.error(code="site.theme_global", message=`name`, operation="theme_values"))*. + We **position = position + 1** and **count = count + 1**. +We **old_css = [Compile the retained original theme](original.css())** and **view_css = [Compile the actual View theme](theme.css())** and **original_sha256 = [Identify real original CSS bytes](hash.sha256(text=`old_css`))** and **view_sha256 = [Identify real projected CSS bytes](hash.sha256(text=`view_css`))**. + +`evidence` = + +| preserved_rows | original_sha256 | view_sha256 | +|---|---|---| +| `count` | `original_sha256` | `view_sha256` | + +Return *[Expose real preservation and compilation evidence](result.ok(value=`evidence`))*. diff --git a/examples/web-spa-app/README.md b/examples/web-spa-app/README.md index f1441db..1112175 100644 --- a/examples/web-spa-app/README.md +++ b/examples/web-spa-app/README.md @@ -1,14 +1,16 @@ # web-spa-app -Marqdo **native SPA**: list → detail → edit with client routes + `scope=memory` store. Zero author JS. +这个工程演示列表、详情、编辑和新建之间的浏览器路由。客户端用原生记录保存条目,以稳定 id 选择内容;刷新页面后恢复演示数据,不提供持久化存储。用户输入通过文本效果和结构化列表显示。 -## Run +从仓库根目录先构建浏览器运行时,再启动可调用服务: -```bash -marqdo wasm build -o examples/web-spa-app/static -cd examples/web-spa-app -marqdo run index.mq.md -# http://127.0.0.1:18093 +```sh +marqdo call skills/marqdo-dev/index.mq.md build_browser 'out="examples/web-spa-app/static"' --effects plugin,process.exec,fs.write --fs-root . --require-ok --json +marqdo call examples/web-spa-app/index.mq.md serve --effects plugin,fs.read,network.write --fs-root . --json ``` -Design: [ext-web-spa.md](../../doc/design/ext-web-spa.md). +打开 http://127.0.0.1:18093。构建需要兼容的 WASM 工具链;缺少时按 [工具链手册](../../skills/marqdo-dev/toolchain.mq.md) 准备工作区编译器,并把返回的 compiler 传给 build_browser。不要用旧版运行时替代当前源码的构建。 + +工程入口 [index.mq.md](index.mq.md) 负责发现和服务;[components/index.mq.md](components/index.mq.md) 逐层组合导航和视图面板;[客户端源码](static/client.mq.md) 说明事件、路由和状态更新。修改内容从 Markdown 叶子开始,修改布局在组件中完成。 + +[开发手册](../../skills/marqdo-dev/index.mq.md) 的 test_browser 使用当前构建验证实际列表编辑、浏览器后退、输入转义和移动端布局。设计背景见 [SPA 设计](../../doc/design/ext-web-spa.md)。 diff --git a/examples/web-spa-app/components/controls.mq.md b/examples/web-spa-app/components/controls.mq.md new file mode 100644 index 0000000..78c9036 --- /dev/null +++ b/examples/web-spa-app/components/controls.mq.md @@ -0,0 +1,47 @@ +--- +markup: occlusion +title: Native control leaves +import: + component: ext/web/component/index.mq.md + table: lib/table.mq.md +--- + +These small leaves retain accessible ids and plain text. Parent components decide their arrangement; callbacks use the same ids in the client wiring. + +## button + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | text | required | Stable id used by the client event table | +| label | text | required | Plain button text | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | One native button leaf | + +Use `id` and `label` for one event target. A button has type button so it does not accidentally submit a surrounding form. Its label stays plain text, including quotes and angle brackets. This function describes a control and performs no click, navigation or DOM mutation. The same leaf is reused by navigation, detail actions and editor actions. + +`attrs` = + +| id | type | +|---|---| +| `id` | button | + +Return *[Describe this native action button](component.element(kind="button", value=`label`, attrs=`attrs`, slot=`id`))*. + +## text + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | text | required | Stable client text target | +| value | text | "" | Initial plain text | +| kind | text | "text" | Native text, title or pre kind | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | One native text target | + +Use `id`, `value`="" and `kind`="text" to declare a simple display leaf. Initial content is escaped by the renderer, and later updates use browser set_text rather than HTML. Select pre for a log or title for the page heading. The control carries no sibling layout, state machine or event handler; its parent owns placement. + +We **attrs = [Retain the stable text target](table.put(in=None, at="id", value=`id`))**. +Return *[Describe the native text leaf](component.element(kind=`kind`, value=`value`, attrs=`attrs`, slot=`id`))*. diff --git a/examples/web-spa-app/components/index.mq.md b/examples/web-spa-app/components/index.mq.md new file mode 100644 index 0000000..9915994 --- /dev/null +++ b/examples/web-spa-app/components/index.mq.md @@ -0,0 +1,24 @@ +--- +markup: occlusion +title: SPA homepage assembly +import: + nav: nav.mq.md + panels: panels/index.mq.md + controls: controls.mq.md + client: ext/web/client/index.mq.md + table: lib/table.mq.md +--- + +The homepage composes navigation, heading, independent panels, status and the official runtime Resource. + +## nodes + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Complete structured homepage without raw HTML | + +This root contains component relationships only. Navigation and panels are ordinary child modules; their content and controls are already simple leaves. The official client runtime is a script Resource referencing built static assets, so no page HTML or author JavaScript is needed. The title and log use stable text targets. A valid node tree does not prove the WASM asset exists; build it and mount the static directory before opening the page. + +We **navigation = [Assemble the navigation component](nav.nodes())** and **title = [Describe the changing page heading](controls.text(id="title", value="Items", kind="title"))** and **content = [Assemble the independent panels](panels.nodes())** and **log = [Describe the status text leaf](controls.text(id="log", value="spa ready", kind="pre"))** and **runtime = [Reference the official client program](client.nodes(source="/static/client.mq.md"))**. +We **head = [Keep navigation before the heading](table.concat(a=`navigation`, b=`title`))** and **body = [Keep panels after the heading](table.concat(a=`head`, b=`content`))** and **visible = [Place feedback after the panels](table.concat(a=`body`, b=`log`))**. +Return *[Retain the runtime as a separate Resource](table.concat(a=`visible`, b=`runtime`))*. diff --git a/examples/web-spa-app/components/nav.mq.md b/examples/web-spa-app/components/nav.mq.md new file mode 100644 index 0000000..7841d24 --- /dev/null +++ b/examples/web-spa-app/components/nav.mq.md @@ -0,0 +1,21 @@ +--- +markup: occlusion +title: SPA navigation +import: + controls: controls.mq.md + component: ext/web/component/index.mq.md + table: lib/table.mq.md +--- + +Navigation composes reusable native buttons; the client owns their transitions. + +## nodes + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Navigation containing Items and New controls | + +The two buttons have independent stable ids and shared accessible button semantics. They contain labels only; selecting an item or opening an editor belongs to the client callbacks. Their parent is a nav region, so this file expresses one placement responsibility without duplicating the surrounding page. + +We **items = [Describe the list action](controls.button(id="nav-list", label="Items"))** and **create = [Describe the creation action](controls.button(id="nav-new", label="New"))** and **children = [Keep their reading order](table.concat(a=`items`, b=`create`))**. +Return *[Place these actions in navigation](component.wrap(children=`children`, kind="nav", slot="navigation"))*. diff --git a/examples/web-spa-app/components/panels/detail.mq.md b/examples/web-spa-app/components/panels/detail.mq.md new file mode 100644 index 0000000..b2a7e42 --- /dev/null +++ b/examples/web-spa-app/components/panels/detail.mq.md @@ -0,0 +1,29 @@ +--- +markup: occlusion +title: Detail panel +import: + controls: ../controls.mq.md + component: ext/web/component/index.mq.md + table: lib/table.mq.md +--- + +Detail separates its changing text from the reusable Edit and Back action leaves. + +## nodes + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Initially hidden detail panel | + +The body has id detail-body and receives plain text after selection. Edit retains the selected stable id; Back returns to the list. Neither action's behavior is embedded in markup. The panel starts hidden and the shared client paint function explicitly controls its hidden attribute, using the same ids as the other panels. + +We **body = [Describe the selected record's text target](controls.text(id="detail-body"))** and **edit = [Describe the edit action](controls.button(id="btn-edit", label="Edit"))** and **back = [Describe the list action](controls.button(id="btn-back", label="Back"))**. +We **buttons = [Keep the action order](table.concat(a=`edit`, b=`back`))** and **actions = [Group only these detail actions](component.wrap(children=`buttons`, kind="row", slot="detail-actions"))** and **children = [Keep data before actions](table.concat(a=`body`, b=`actions`))**. + +`attrs` = + +| id | hidden | +|---|---| +| view-detail | True | + +Return *[Describe the independent detail panel](component.wrap(children=`children`, kind="section", attrs=`attrs`, slot="detail-panel"))*. diff --git a/examples/web-spa-app/components/panels/edit.mq.md b/examples/web-spa-app/components/panels/edit.mq.md new file mode 100644 index 0000000..19f5c33 --- /dev/null +++ b/examples/web-spa-app/components/panels/edit.mq.md @@ -0,0 +1,37 @@ +--- +markup: occlusion +title: Editor panel +import: + controls: ../controls.mq.md + component: ext/web/component/index.mq.md + table: lib/table.mq.md +--- + +The editor is a native input plus reusable action leaves. Saving remains a client transition, not an implicit HTTP form. + +## nodes + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Initially hidden editor with accessible label and native input | + +The label's for attribute names edit-title, the same input read by the Save binding. The input keeps a plain text value. Save validates nonempty text in Marqdo before changing the record list; Cancel changes the route without calling that update. This component describes controls only and starts hidden. The parent keeps field content separate from the action row, allowing the existing responsive layout renderer to place them. + +We **label_attrs = [Associate the label with its input](table.put(in=None, at="for", value="edit-title"))** and **label = [Describe the visible field label](component.element(kind="label", value="Title", attrs=`label_attrs`, slot="title-label"))**. + +`input_attrs` = + +| id | name | type | +|---|---|---| +| edit-title | title | text | + +We **input = [Describe the native title input](component.element(kind="input", attrs=`input_attrs`, slot="title-input"))** and **field = [Keep label and input together](table.concat(a=`label`, b=`input`))**. +We **save = [Describe the save action](controls.button(id="btn-save", label="Save"))** and **cancel = [Describe the cancel action](controls.button(id="btn-cancel", label="Cancel"))** and **buttons = [Keep these editor actions ordered](table.concat(a=`save`, b=`cancel`))** and **actions = [Group the action row](component.wrap(children=`buttons`, kind="row", slot="editor-actions"))** and **children = [Place the field before its actions](table.concat(a=`field`, b=`actions`))**. + +`attrs` = + +| id | hidden | +|---|---| +| view-edit | True | + +Return *[Describe the independent editor panel](component.wrap(children=`children`, kind="section", attrs=`attrs`, slot="editor-panel"))*. diff --git a/examples/web-spa-app/components/panels/index.mq.md b/examples/web-spa-app/components/panels/index.mq.md new file mode 100644 index 0000000..fba67b8 --- /dev/null +++ b/examples/web-spa-app/components/panels/index.mq.md @@ -0,0 +1,22 @@ +--- +markup: occlusion +title: SPA panel assembly +import: + listing: list.mq.md + detail: detail.mq.md + editor: edit.mq.md + table: lib/table.mq.md +--- + +This parent owns only the three sibling panel relationships. + +## nodes + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Ordered list, detail and editor panel rows | + +Each child owns one panel and names its own native controls. This function retains their structured values and stable order; the client independently selects visibility using hidden attributes. It does not render a second page or concatenate HTML. Changes to editor fields therefore remain inside the editor component instead of growing a single application string. + +We **list = [Assemble the listing component](listing.nodes())** and **view = [Assemble the detail component](detail.nodes())** and **edit = [Assemble the editor component](editor.nodes())** and **first = [Retain list and detail order](table.concat(a=`list`, b=`view`))**. +Return *[Keep the editor as the third sibling](table.concat(a=`first`, b=`edit`))*. diff --git a/examples/web-spa-app/components/panels/list.mq.md b/examples/web-spa-app/components/panels/list.mq.md new file mode 100644 index 0000000..7bc7221 --- /dev/null +++ b/examples/web-spa-app/components/panels/list.mq.md @@ -0,0 +1,28 @@ +--- +markup: occlusion +title: List panel +import: + component: ext/web/component/index.mq.md + table: lib/table.mq.md +--- + +The existing list container is populated by the official bridge's structured render_list effect. + +## nodes + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Initially visible list panel with its Markdown hint | + +The empty native list provides id items for delegated clicks. Its actual entries come from native client records and use stable data-id attributes. The hint is ordinary Markdown and knows nothing about item data or routing. Only this parent sets the list panel's visibility; detail and editor remain separate components. + +We **empty = [Start with no server-owned item rows](table.empty_list())** and **target = [Name the client-owned list container](table.put(in=None, at="id", value="items"))** and **list = [Describe the native unordered list](component.wrap(children=`empty`, kind="list", attrs=`target`, slot="items"))**. +We **hint = [Keep the instruction as ordinary Markdown](component.markdown(text="Click an item for detail.", slot="list-hint"))** and **children = [Place the hint after its list](table.concat(a=`list`, b=`hint`))**. + +`attrs` = + +| id | hidden | +|---|---| +| view-list | False | + +Return *[Describe the visible list panel](component.wrap(children=`children`, kind="section", attrs=`attrs`, slot="list-panel"))*. diff --git a/examples/web-spa-app/index.mq.md b/examples/web-spa-app/index.mq.md index 7c9856a..59d3af2 100644 --- a/examples/web-spa-app/index.mq.md +++ b/examples/web-spa-app/index.mq.md @@ -1,25 +1,39 @@ --- markup: occlusion -title: web-spa-app -description: Native Marqdo SPA — list/detail/edit via WASM client routes + memory store +type: web +view: main +route: / +title: Marqdo SPA — Document layout and native client records import: + home: components/index.mq.md web: ext/web/web.mq.md + http: ext/net/http.mq.md --- -# main +The Document's main assembles View nodes; serve owns the process lifetime. Build current WASM assets into static before starting. From the checkout root, call serve with plugin,fs.read,network.write and --fs-root examples/web-spa-app. List, detail and edit behavior stays in static/client.mq.md, with native row records and the official bridge's list effect. -Full-page client app (zero author JS). Build assets first: +## main -``` -marqdo wasm build -o examples/web-spa-app/static -``` +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Homepage View rows | -**`embed` = > web.client_embed bridge="/static/marqdo-bridge.js" wasm="/static/marqdo_wasm.wasm" source="/static/client.mq.md" boot=True** +The page delegates layout to the component root. Follow that root into navigation and the three independent panels until reaching plain text, Markdown or a native control leaf. The runtime is a structured Resource. This function neither starts a server nor mixes client state into a page HTML string; serve later mounts the actual assets. -**`intro` = "

      Items

        Click an item for detail.

        " + embed**
        +Return *[Assemble the inspectable homepage](home.nodes())*.
         
        -**page = > web.page title="Marqdo SPA" intro=intro layout="bare"**
        -**app = > web.app page=page host="127.0.0.1" port=18093**
        -**app = > app.static dir="static" mount="/static"**
        -**app = > app.redirect from="/item" to="/" permanent=False**
        -> `app`.listen
        +## serve
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| root | text | "examples/web-spa-app" | Explicit site directory from the checkout root |
        +| port | number | 18093 | Loopback listen port |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Blocking site listener result |
        +
        +Use `root`="examples/web-spa-app" and `port`=18093. The site prepares declared Documents and Endpoints, mounts static, then binds the existing /item redirect through the network resource. The explicit localhost address matches this demonstration's scope. Browser transitions use history inside the page; the server redirect preserves the old direct /item entry behavior. This function blocks until its supervisor stops it, and missing assets remain a real build prerequisite.
        +
        +We **app = [Prepare the declared page and static mount](web.prepare(root=`root`, host="127.0.0.1", port=`port`, static_dir="static"))** and **app = [Preserve the declared direct-entry redirect](http.redirect(app=`app`, from="/item", to="/", permanent=False))**.
        +Return *[Listen after all resources are bound](web.listen(app=`app`))*.
        diff --git a/examples/web-spa-app/static/client.mq.md b/examples/web-spa-app/static/client.mq.md
        index 4ef7020..4cda98d 100644
        --- a/examples/web-spa-app/static/client.mq.md
        +++ b/examples/web-spa-app/static/client.mq.md
        @@ -1,33 +1,46 @@
         ---
         markup: occlusion
        -title: spa client
        -description: routes table + memory store; list / detail / edit
        +title: SPA client with native records and structured browser effects
         import:
           browser: lib/browser.mq.md
           table: lib/table.mq.md
        -  text: lib/text.mq.md
         ---
         
        +The Document supplies native controls; this client supplies transitions between list, detail and edit. BrowserSession retains the entry state between callbacks. Stable ids keep selection separate from user text, and all dynamic list content is sent as records to the existing official bridge.
        +
         # main
         
        -Routes (documentation + titles). Runtime switches panels by `path`.
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Boot bindings, initial list, memory storage and panel effects |
         
        -`routes` =
        +This client keeps route, selection and records in the browser session's native Marqdo entry state. Titles are text; stable ids select records even when a title contains punctuation or is edited. The initial list is a row table rather than a newline string. Boot binds the existing controls, seeds the memory store and paints the first view immediately. Storage lasts for this client session; it is not a server database or durable reload persistence. Page geometry and labels live in separate Document components. Event callbacks only calculate state changes and return instructions for the official bridge.
         
        -| @ | 路径 | 面板 | 标题 |
        -|---|------|------|------|
        -| 1 | / | #view-list | Items |
        -| 2 | /item | #view-detail | Detail |
        -| 3 | /edit | #view-edit | Edit |
        +We **route = "/"** and **cur_id = ""** and **next_id = 2** to start with no selected record.
         
        -**`path` = "/"**
        -**`cur_id` = ""**
        -**`items` = "Alpha\nBeta"**
        +`items` =
         
        -`wire` =
        +| @ | id | title |
        +|---|---|---|
        +| 1 | "1" | Alpha |
        +| 2 | "2" | Beta |
        +
        +We **bindings = [Read the explicit event wiring](_bindings())** and **wired = [Describe those control bindings](table.put(in=None, at="wire", value=`bindings`))**.
        +We **painted = [Paint the initial list without changing history](spa_paint(records=`items`, path=`route`, selected_id=`cur_id`, update_url=False))**.
        +After boot, return *[Keep bindings and initial effects together](browser.merge(a=`wired`, b=`painted`))*.
        +
        +## _bindings
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | list | Explicit delegated event rows for existing native controls |
        +
        +These rows connect the Document's stable ids to Marqdo callbacks. List clicks are delegated to li[data-id], so replacing list entries does not discard the listener. Save reads the existing input value, and browser back/forward supplies path to on_pop. The bridge owns event dispatch; this table does not contain author JavaScript or page HTML. Every referenced callback below has an actual parameter and return contract.
        +
        +`bindings` =
         
         | @ | 选择器 | 事件 | 调用 | 委托 | 值选择器 |
        -|---|--------|------|------|------|----------|
        +|---|---|---|---|---|---|
         | 1 | "#nav-list" | click | go_list | | |
         | 2 | "#nav-new" | click | go_new | | |
         | 3 | "#items" | click | open_item | "li[data-id]" | |
        @@ -35,142 +48,193 @@ Routes (documentation + titles). Runtime switches panels by `path`.
         | 5 | "#btn-back" | click | go_list | | |
         | 6 | "#btn-save" | click | save_item | | "#edit-title" |
         | 7 | "#btn-cancel" | click | go_list | | |
        -| 8 | "window" | popstate | on_pop | | |
        +| 8 | window | popstate | on_pop | | |
         
        -`seed` =
        -
        -| op | key | value | scope |
        -|----|-----|-------|-------|
        -| set | spa-items | `items` | memory |
        -
        -**`w` = > table.put in=None at="wire" value=wire**
        -**`s` = > browser.storage spec=seed**
        -**`boot` = > browser.merge a=w b=s**
        -**`ready` = > browser.set_text sel="#log" text="spa ready — click Items"**
        -*> browser.merge a=boot b=ready*
        +Return *bindings*.
         
         ## on_pop
        -    + `path`=""
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| path | text | "" | Location path supplied by the browser's popstate event |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Panel, list and storage effects without pushing a second history entry |
        +
        +Use `path`="" from the event payload. Route state uses a different name so assigning the event value changes shared state instead of shadowing a path parameter. An empty payload leaves the current route unchanged. Painting a history event deliberately avoids spa_goto: pressing Back must not create another forward history record.
         
         1. `path` != ""
        -    **`path` = path**
        -2. *
        -    ****
        -*> spa_render*
        +  We **route = [Retain the location supplied by the browser](path)**.
        +Return *[Repaint the restored route without another navigation](spa_paint(records=`items`, path=`route`, selected_id=`cur_id`, update_url=False))*.
         
         ## go_list
        -**`path` = "/"**
        -**`cur_id` = ""**
        -*> spa_render*
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | List panel effects and one navigation instruction |
        +
        +The Items and Back controls share this transition. Clear the selected id so the list does not retain an editing target, switch the shared route to the list path, then paint through the common function. Stored item data remains unchanged. The browser bridge performs the returned navigation and DOM instructions after the state update.
        +
        +We **route = "/"** and **cur_id = ""**.
        +Return *[Show the current list](spa_paint(records=`items`, path=`route`, selected_id=`cur_id`))*.
         
         ## go_new
        -**`path` = "/edit"**
        -**`cur_id` = ""**
        -*> spa_render*
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Empty editor effects and one navigation instruction |
        +
        +Creating a record opens the editor without selecting an existing id. Save allocates an id only after nonempty text arrives, so merely opening or cancelling this panel does not insert a blank record. The common paint function puts an empty value in the native input and hides the other panels.
        +
        +We **route = "/edit"** and **cur_id = ""**.
        +Return *[Open the empty editor](spa_paint(records=`items`, path=`route`, selected_id=`cur_id`))*.
         
         ## go_edit
        -**`path` = "/edit"**
        -*> spa_render*
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Editor effects for the existing selection |
        +
        +Editing keeps the selected id and changes only the current panel. The paint function looks up the current title from native rows, so a renamed record is still found by its stable id. Navigation and rendering remain instructions for the bridge; this callback neither writes a file nor calls a server.
        +
        +We **route = "/edit"**.
        +Return *[Show the selected record in the editor](spa_paint(records=`items`, path=`route`, selected_id=`cur_id`))*.
         
         ## open_item
        -    + `data_id`=""
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| data_id | text | "" | Stable data-id from the delegated list item |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | any | Detail effects, or None when no record id was clicked |
        +
        +Use `data_id`="" from the delegated event. A click outside a real list entry must not invent a selection. Keep the id separately from its displayed title; quoted text, angle brackets and later renames therefore do not alter the event identity. Actual text is selected when the detail panel is painted.
         
         1. `data_id` != ""
        -    **`cur_id` = data_id**
        -    **`path` = "/item"**
        -    *> spa_render*
        -2. *
        -    ****
        +  We **cur_id = [Retain the clicked record identity](data_id)** and **route = "/item"**.
        +  Return *[Show the selected record](spa_paint(records=`items`, path=`route`, selected_id=`cur_id`))*.
        +If no record was clicked, return *None*.
         
         ## save_item
        -    + `value`=""
         
        -1. `value` != ""
        -    1. `cur_id` != ""
        -        **`parts` = > text.str_split s=items sep="\n"**
        -        **`next` = ""**
        -        - [item](遍历 parts 为 item)
        -            1. `item` != ""
        -                1. `item` == `cur_id`
        -                    1. `next` == ""
        -                        **`next` = value**
        -                    2. *
        -                        **`next` = next + "\n" + value**
        -                2. *
        -                    1. `next` == ""
        -                        **`next` = item**
        -                    2. *
        -                        **`next` = next + "\n" + item**
        -        **`items` = next**
        -        **`cur_id` = value**
        -    2. *
        -        1. `items` == ""
        -            **`items` = value**
        -        2. *
        -            **`items` = items + "\n" + value**
        -        **`cur_id` = value**
        -    **`path` = "/item"**
        -    *> spa_render*
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| value | text | "" | Plain title from the native editor input |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Saved detail effects, or a title-required text effect |
        +
        +Use `value`="" from the Save binding. Empty text returns a validation message before changing data. For an existing id, replace that row's title while retaining all ids and row order. For a new record, allocate the next native integer id and convert it to event text. The resulting records are kept in the session and mirrored to the memory store by painting. No HTML is generated from a title and no external interpreter performs the array update. Cancel bypasses this function entirely.
        +
        +1. `value` == ""
        +  Return *[Explain the required title](browser.set_text(sel="#log", text="title required"))*.
        +1. `cur_id` != ""
        +  We **updated = [Start the replacement record list](table.empty_list())**.
        +  - [Retain each record or replace only its title](for items as item)
        +    1. access(`item`, "id") == `cur_id`
        +      We **item = [Update the title without changing its id](table.put(in=`item`, at="title", value=`value`))**.
        +    We **updated = [Retain this row in its original order](table.append(list=`updated`, item=`item`))**.
        +  We **items = [Keep the completed native row list](updated)**.
         2. *
        -    *> browser.set_text sel="#log" text="title required"*
        +  We **next_id = next_id + 1** and **cur_id = [Use the stable integer id as event text](str(next_id))**.
        +
        +  `item` =
        +
        +  | id | title |
        +  |---|---|
        +  | `cur_id` | `value` |
        +
        +  We **items = [Append the new native record](table.append(list=`items`, item=`item`))**.
        +We **route = "/item"** after a successful save.
        +Return *[Display and mirror the saved record](spa_paint(records=`items`, path=`route`, selected_id=`cur_id`))*.
        +
        +## _list_rows
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| records | list | required | Native rows with id and title |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | list | Bridge list items containing escaped text and stable data-id attributes |
        +
        +Use `records` as the only list input. Each output item carries plain text plus an attribute record; the official bridge performs text escaping when it renders the list. The source never interpolates a title into an HTML tag. The delegated click id comes from the original record id, preserving selection independently of the displayed title.
        +
        +We **rows = [Start the browser list descriptions](table.empty_list())**.
        +- [Describe every native record as a text item](for records as record)
        +  We **label = [Read its plain title](access(`record`, "title"))** and **id = [Read its stable identity](access(`record`, "id"))** and **attrs = [Retain the delegated event id](table.put(in=None, at="data-id", value=`id`))**.
        +
        +  `row` =
        +
        +  | text | attrs |
        +  |---|---|
        +  | `label` | `attrs` |
        +
        +  We **rows = [Retain this structured list item](table.append(list=`rows`, item=`row`))**.
        +Return *rows*.
         
         ## spa_render
        -*> spa_paint*
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Current panel, list, memory and navigation effects |
        +
        +This named entry preserves the common rendering callback used by the demonstration. It delegates to the same paint function as direct transitions so panel selection, item text and memory storage stay consistent. No page string is compiled or evaluated here; the returned value is a normal bridge instruction record.
        +
        +Return *[Paint the current native state](spa_paint(records=`items`, path=`route`, selected_id=`cur_id`))*.
         
         ## spa_paint
        -**`hide` = > table.put in=None at="hidden" value=""**
        -**`show` = > table.put in=None at="hidden" value=False**
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| records | list | required | Native item rows to display and mirror |
        +| path | text | required | Current client route |
        +| selected_id | text | required | Stable selected id, or empty for a new item |
        +| update_url | bool | True | False for history events and initial boot; True for user navigation |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | One complete structured effect map for the current native state |
        +
        +Use `records`, `path`, `selected_id` and `update_url`=True for ordinary user navigation, and False when repainting an existing history entry. The selected row is found by id; all content remains plain text. Three panels receive explicit hidden flags, while title, detail and log text are described together. Browser merge replaces whole top-level effect keys, so combining those text targets first prevents later messages from discarding earlier text updates. List rows go through render_list, and the editor value changes only while that panel is active. Storage uses a record list in the memory scope. This function describes effects and performs no direct DOM, network or file access.
        +
        +We **selected = [Find the native record by stable identity](table.find(list=`records`, key="id", value=`selected_id`))** and **body = ""** and **title = "Items"**.
        +1. `selected` != None
        +  We **body = [Read the current selected title](access(`selected`, "title"))**.
         1. `path` == "/item"
        -    `attrs` =
        +  We **title = "Detail"**.
        +1. `path` == "/edit"
        +  We **title = "Edit"**.
        +We **list_flag = [Hide the list outside its route](table.put(in=None, at="hidden", value=(path != "/")))** and **detail_flag = [Show only the detail route](table.put(in=None, at="hidden", value=(path != "/item")))** and **edit_flag = [Show only the editor route](table.put(in=None, at="hidden", value=(path != "/edit")))**.
         
        -    | #view-detail | #view-list | #view-edit |
        -    |--------------|------------|------------|
        -    | `show` | `hide` | `hide` |
        -    **`title` = "Detail"**
        -    **`body` = cur_id**
        -2. *
        -    1. `path` == "/edit"
        -        `attrs` =
        +`visibility` =
         
        -        | #view-edit | #view-list | #view-detail |
        -        |------------|------------|--------------|
        -        | `show` | `hide` | `hide` |
        -        **`title` = "Edit"**
        -        **`body` = cur_id**
        -    2. *
        -        `attrs` =
        +| #view-list | #view-detail | #view-edit |
        +|---|---|---|
        +| `list_flag` | `detail_flag` | `edit_flag` |
        +
        +`texts` =
        +
        +| #title | #detail-body | #log |
        +|---|---|---|
        +| `title` | `body` | `path` |
        +
        +We **ret = [Describe all text updates in one effect](browser.wrap(key="set_text", value=`texts`))** and **flags = [Describe the three panel visibility updates](browser.wrap(key="set_attr", value=`visibility`))** and **ret = [Keep independent text and attribute effects](browser.merge(a=`ret`, b=`flags`))**.
        +We **rows = [Describe record text without HTML](_list_rows(records=`records`))** and **listing = [Replace the existing list using structured items](browser.render_list(sel="#items", items=`rows`))** and **ret = [Retain the list update](browser.merge(a=`ret`, b=`listing`))**.
        +1. `path` == "/edit"
        +  We **edit = [Populate the native editor input](browser.set_value(sel="#edit-title", value=`body`))** and **ret = [Retain the input value update](browser.merge(a=`ret`, b=`edit`))**.
        +1. `update_url`
        +  We **navigation = [Navigate only for a user transition](browser.spa_goto(url=`path`))** and **ret = [Retain this history instruction](browser.merge(a=`ret`, b=`navigation`))**.
         
        -        | #view-list | #view-detail | #view-edit |
        -        |------------|--------------|------------|
        -        | `show` | `hide` | `hide` |
        -        **`title` = "Items"**
        -        **`body` = ""**
        -**`parts` = > text.str_split s=items sep="\n"**
        -**`html` = ""**
        -- [item](遍历 parts 为 item)
        -    1. `item` != ""
        -        **`html` = html + "
      • " + item + "
      • "** `persist` = | op | key | value | scope | -|----|-----|-------|-------| -| set | spa-items | `items` | memory | +|---|---|---|---| +| set | spa-items | `records` | memory | -**`t` = > browser.set_text sel="#title" text=title** -**`a` = > browser.wrap key="set_attr" value=attrs** -**`ret` = > browser.merge a=t b=a** -**`list` = > browser.set_html sel="#items" html=html** -**`ret` = > browser.merge a=ret b=list** -**`d` = > browser.set_text sel="#detail-body" text=body** -**`ret` = > browser.merge a=ret b=d** -1. `path` == "/edit" - **`v` = > browser.set_value sel="#edit-title" value=cur_id** - **`ret` = > browser.merge a=ret b=v** -2. * - **** -**`nav` = > browser.spa_goto url=path** -**`ret` = > browser.merge a=ret b=nav** -**`log` = > browser.set_text sel="#log" text=path** -**`ret` = > browser.merge a=ret b=log** -**`sav` = > browser.storage spec=persist** -*> browser.merge a=ret b=sav* +We **storage = [Mirror the native records in memory](browser.storage(spec=`persist`))**. +Return *[Keep the completed paint and memory instructions](browser.merge(a=`ret`, b=`storage`))*. diff --git a/examples/web-tenant-saas/README.md b/examples/web-tenant-saas/README.md new file mode 100644 index 0000000..21a0124 --- /dev/null +++ b/examples/web-tenant-saas/README.md @@ -0,0 +1,13 @@ +# web-tenant-saas + +从仓库根目录运行: + +```sh +marqdo call examples/web-tenant-saas/index.mq.md serve --effects plugin,fs.write,network.write --fs-root examples/web-tenant-saas --json +``` + +打开 http://127.0.0.1:18092,比较页面里的 Acme 与 Beta 查询链接。缺少 t 参数时返回 400;返回的 JSON 包含 rows 列表。首次空库初始化两篇笔记,重启保留已有记录。 + +[工程入口](index.mq.md) 串联 [数据库初始化](db/index.mq.md)、[租户选择](../../ext/security/tenant.mq.md) 与 [JSON 查询资源](../../ext/data/api.mq.md)。页面内容位于 [intro.md](intro.md),无原生 HTML 壳。 + +这是允许匿名切换租户的本机过滤演示。生产访问隔离还需要鉴权与成员关系检查。回归测试 web_handbook 覆盖两种后端的租户过滤、缺少参数与用户记录重启保留。 diff --git a/examples/web-tenant-saas/db/index.mq.md b/examples/web-tenant-saas/db/index.mq.md new file mode 100644 index 0000000..411529b --- /dev/null +++ b/examples/web-tenant-saas/db/index.mq.md @@ -0,0 +1,47 @@ +--- +markup: occlusion +title: Tenant demonstration database +import: + db: ext/data/db.mq.md + fs: lib/fs.mq.md +--- + +This initializer owns one demonstration table. It keeps existing rows and seeds only an empty table. Pass a disposable absolute SQLite URI for tests; no caller should need to delete a user's data to repeat initialization. + +## open + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | any | None | None chooses data/tenant-saas.db under the granted site root; otherwise an explicit SQLite URI | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Initialized database resource containing retained user rows or initial demo notes | + +Use `url`=None with fs.write and plugin on the site root. The default path is resolved through the native filesystem so its location does not change with the process working directory. An explicit SQLite URI belongs to the caller, who must grant and manage that native database boundary. This initializer never deletes rows or resets ids during a restart. + +The schema preserves the title and tenant_id fields used by the scoped query. Check for any existing row before seeding; a nonempty or partially populated database is retained as supplied. Only a completely empty table receives the two notes. This is an idempotent demonstration initializer, not a migration or repair tool. + +1. `url` == None + We **[Create the site's selected data directory](fs.make_dirs(path="data"))** and **path = [Resolve the native database filename](fs.resolve(path="data/tenant-saas.db"))** and **url = "sqlite:" + path**. + +`fields` = + +| name | type | nullable | +|---|---|---| +| id | integer | False | +| title | text | False | +| tenant_id | text | False | + +We **store = [Open the selected database resource](db.db(url=`url`))** and **[Ensure the demonstration table exists](> `store`.init name="items" fields=`fields`)** and **existing = [Observe whether any business rows already exist](> `store`.select table="items" limit=1)**. +1. not `existing` + + `rows` = + + | @ | title | tenant_id | + |---|---|---| + | 1 | Acme note | acme | + | 2 | Beta note | beta | + + We **[Insert both initial notes only into the empty table](> `store`.insert table="items" rows=`rows`)**. +Once the selected database is ready, return *store* for route discovery and binding. diff --git a/examples/web-tenant-saas/index.mq.md b/examples/web-tenant-saas/index.mq.md index fedb4c8..dcd8133 100644 --- a/examples/web-tenant-saas/index.mq.md +++ b/examples/web-tenant-saas/index.mq.md @@ -1,35 +1,54 @@ --- markup: occlusion -title: web-tenant-saas demo -description: Dual-tenant isolation via ?t= query + tenant_scope JSON API. +type: web +view: main +route: / +title: Tenant SaaS — explicit database and request resources import: + component: ext/web/component/index.mq.md + fs: lib/fs.mq.md web: ext/web/web.mq.md + api: ext/data/api.mq.md + tenant: ext/security/tenant.mq.md + database: db/index.mq.md --- -# main +Read the Markdown leaf for the visible demonstration, the database entry for initialization, and the two resource leaves for query and tenant binding. The old startup DELETE is removed: restarting a demo must preserve existing rows. This loopback site intentionally allows choosing a demo tenant; it does not claim authenticated membership. -`items_schema` = +## main -| name | type | nullable | -|------|------|----------| -| id | integer | false | -| title | text | false | -| tenant_id | text | false | +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Native View nodes containing the Markdown explanation and query links | -`api` = +The page is a single content leaf because its internal structure is already simple Markdown. No raw HTML shell or browser script is needed. Site discovery reads it relative to the chosen site root; the returned node data is assembled before any listener starts. The API and database lifecycle remain in serve, so rendering the explanation cannot clear or recreate business data. + +We **intro = [Read the terminal content through the granted site root](fs.read_text(path="intro.md"))**. +Return *[Describe the explanation as a Markdown leaf](component.markdown(text=`intro`, slot="tenant-introduction"))*. + +## serve + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| root | text | "examples/web-tenant-saas" | Explicit site discovery directory relative to the checkout | +| port | number | 18092 | Local listener port | +| url | any | None | None selects the site-root database; tests pass a disposable SQLite URI | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Blocking listener with explicit tenant-filtered JSON queries | + +Use `root`="examples/web-tenant-saas", `port`=18092 and `url`=None with plugin, fs.write and network.write. Set --fs-root to this site's directory so default database files belong to the site. The discovery root is explicit and independent of that filesystem grant. Preparation initializes retained records, discovers the explanation, then binds request tenant selection and the read-only query table before listening. + +The route explicitly scopes its query by tenant_id. With the resolver attached, missing tenant context is rejected rather than returning both tenants. Selection via t is intentionally open for this local example; real user access requires a separate authentication and membership policy. Keep both bindings together when editing the flow. + +We **store = [Initialize without deleting existing user rows](database.open(url=`url`))** and **app = [Discover the page with its retained database resource](web.prepare(root=`root`, host="127.0.0.1", port=`port`, db=`store`))** and **app = [Resolve the explicit request tenant selector](tenant.attach(app=`app`, mode="path", param="t", default_scope=False))**. + +`routes` = | path | method | table | order | limit | tenant_scope | -|------|--------|-------|-------|-------|--------------| -| api/items | GET | items | id | 50 | true | +|---|---|---|---|---|---| +| api/items | GET | items | id | 50 | True | -**db = > web.db url="sqlite:data/tenant-saas.db"** -> `db`.init name=items fields=`items_schema` -> `db`.exec sql="DELETE FROM items" -> `db`.exec sql="INSERT INTO items(title, tenant_id) VALUES('Acme note','acme')" -> `db`.exec sql="INSERT INTO items(title, tenant_id) VALUES('Beta note','beta')" - -**page = > web.page title="Tenant SaaS" intro="

        Try /api/items?t=acme vs /api/items?t=beta.

        "** -**app = > web.app page=`page` db=`db` host="127.0.0.1" port=18092 admin=False** -**app = > `app`.tenant mode="path" param="t" default_scope=False** -**app = > `app`.configure json=`api`** -> `app`.listen +We **app = [Bind the explicit tenant-scoped read-only query](api.mount(app=`app`, routes=`routes`))**. +Return *[Listen after data and request policy are ready](web.listen(app=`app`))*. diff --git a/examples/web-tenant-saas/intro.md b/examples/web-tenant-saas/intro.md new file mode 100644 index 0000000..f822603 --- /dev/null +++ b/examples/web-tenant-saas/intro.md @@ -0,0 +1,11 @@ +# Two-tenant query demonstration + +Compare [Acme notes](/api/items?t=acme) with [Beta notes](/api/items?t=beta). +Each response selects only rows belonging to the chosen tenant. +A [request without a tenant](/api/items) is rejected. + +This local demonstration permits anonymous tenant selection. It demonstrates +query filtering and does not authenticate a user or prove tenant membership. + +Restarting the server retains existing database rows. The initializer adds +the two demonstration notes only when the table is completely empty. diff --git a/examples/web-ws-room/home.mq.md b/examples/web-ws-room/home.mq.md new file mode 100644 index 0000000..2504311 --- /dev/null +++ b/examples/web-ws-room/home.mq.md @@ -0,0 +1,29 @@ +--- +markup: occlusion +title: Room page components +import: + component: ext/web/component/index.mq.md + table: lib/table.mq.md + fs: lib/fs.mq.md +--- + +The parent contains an introduction and one log control. Ordinary copy lives in intro.md; the control keeps only its event target and plain initial text. Content has no transport setup, server lifetime or generated HTML. + +## nodes + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Ordered introduction and log control rows | + +The introduction is a terminal Markdown content block and is read within the granted site root. The event log is a preformatted native leaf with id log; incoming client messages may replace its text without changing the layout. Attribute values remain typed data until rendering, and initial text is escaped. These two independent responsibilities are merged in reading order, without a string of raw HTML or a second layout schema. + +We **intro = [Read the terminal Markdown content](fs.read_text(path="intro.md"))** and **overview = [Describe the introduction as Markdown](component.markdown(text=`intro`, slot="intro"))**. + +`attributes` = + +| id | aria-live | +|---|---| +| log | polite | + +We **log = [Describe the independent event log](component.element(kind="pre", value="Connect a client to /chat/lobby.", attrs=`attributes`, slot="log"))**. +Return *[Keep introduction and event log in reading order](table.concat(a=`overview`, b=`log`))*. diff --git a/examples/web-ws-room/index.mq.md b/examples/web-ws-room/index.mq.md index 9ea9768..afed66f 100644 --- a/examples/web-ws-room/index.mq.md +++ b/examples/web-ws-room/index.mq.md @@ -1,14 +1,40 @@ --- markup: occlusion -title: web-ws-room demo -description: Dynamic room WS with presence (G-WS1/2 bag). Open / and connect via bridge or wscat. +type: web +view: main +route: / +title: Room transport composed from Documents and Resources import: web: ext/web/web.mq.md + socket: ext/net/websocket.mq.md + home: home.mq.md --- -# main +This local demonstration serves a Markdown introduction and a native log control. The page is a Document; the room transport is an explicitly bound network resource. From the checkout root, call serve with --effects plugin,fs.read,network.write and --fs-root examples/web-ws-room. It blocks until the supervising process stops it. Connect a WebSocket client to /chat/lobby to join chat.room.lobby; presence uses the same native room protocol as other transports. This loopback-only example explicitly permits anonymous room access; a deployed site should attach authentication and retain the default private route policy. -**page = > web.page title="WS room" intro="

        Chat room lobby via /chat/lobby. Presence joins chat.room.lobby.presence.

        "**
        -**app = > web.app page=`page` host="127.0.0.1" port=18091 admin=False**
        -**app = > `app`.route_ws path="/chat/{id}" mode="room" room_key="chat.room.{id}" presence=True**
        -> `app`.listen
        +## main
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | list | The homepage View rows, without starting a server |
        +
        +The Document's main function only assembles content. The introduction remains a Markdown leaf and the event log is one native control with a stable id. The parent keeps those responsibilities as separate nodes, so changing the transport does not require rewriting the page as HTML. The View renderer receives structured values, and reading the content requires the granted site root.
        +
        +After selecting the homepage components, return *[Assemble the readable room page](home.nodes())*.
        +
        +## serve
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| root | text | "examples/web-ws-room" | Explicit site directory relative to the current working directory |
        +| port | number | 18091 | Loopback server port |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Blocking listener result for the declared page and room route |
        +
        +Use `root`="examples/web-ws-room" and `port`=18091 from the checkout root. Preparing the site performs Document discovery and one startup assembly before any socket opens. Then the network resource binds /chat/{id} using the chat.room.{id} room template and publishes presence messages. This intentionally public local demo sets require_auth=False; it is not a recommendation to expose anonymous production rooms. Keep each returned app value because binding updates are immutable. The final listener retains the original site root for callbacks and resources.
        +
        +We **app = [Discover the site's Documents and Endpoints](web.prepare(root=`root`, host="127.0.0.1", port=`port`))**.
        +We **app = [Bind the room and its presence channel](socket.route(app=`app`, path="/chat/{id}", mode="room", room_key="chat.room.{id}", presence=True, require_auth=False))**.
        +After all bindings are ready, return *[Listen with the complete site resources](web.listen(app=`app`))*.
        diff --git a/examples/web-ws-room/intro.md b/examples/web-ws-room/intro.md
        new file mode 100644
        index 0000000..de85c9d
        --- /dev/null
        +++ b/examples/web-ws-room/intro.md
        @@ -0,0 +1,5 @@
        +# WebSocket room
        +
        +Join **lobby** through `/chat/lobby`. Messages are shared in `chat.room.lobby`; the native presence channel announces participants.
        +
        +Open two controlled clients to observe room messages and presence. This demonstration listens only on the local host and explicitly permits anonymous room access.
        diff --git a/ext/VERSION b/ext/VERSION
        index e70b452..24ba9a3 100644
        --- a/ext/VERSION
        +++ b/ext/VERSION
        @@ -1 +1 @@
        -2.6.0
        +2.7.0
        diff --git a/ext/data/admin.mq.md b/ext/data/admin.mq.md
        new file mode 100644
        index 0000000..8513e54
        --- /dev/null
        +++ b/ext/data/admin.mq.md
        @@ -0,0 +1,24 @@
        +---
        +markup: occlusion
        +title: Native administration resource
        +import:
        +  table: lib/table.mq.md
        +---
        +
        +This single-purpose resource enables the existing native administration surface on a prepared app. It does not construct a page or configure unrelated middleware. Attach real authentication afterwards so the native runtime adds its administration gate before listening. Custom Document desks remain ordinary declared routes and do not need this switch.
        +
        +## enable
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| app | map | required | Prepared application retaining its native admin_prefix, normally /admin |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Updated app with native administration enabled; no listener starts |
        +
        +Use `app` before attaching authentication and before listen. This pure resource composition retains the app's database, discovered Documents and other bindings, and changes only the existing native admin flag. The runtime lists only the business tables associated with explicitly mounted forms, shows up to 100 current rows per table, and links to those actual form resources. It does not enumerate unrelated credential/session tables or expose arbitrary SQL. The native renderer owns this landing page and its reserved route namespace. It does not create a second application configuration API.
        +
        +Authentication must be configured separately. When it is attached after enabling this surface, the existing native admin policy installs the default administration gate. The caller keeps the returned application and verifies both denied and accepted requests. Enabling a UI is not proof that credentials or database access have been authorized; the explicit server workflow supplies those dependencies.
        +
        +Return *[Enable only the native administration surface](table.put(in=`app`, at="admin", value=True))*.
        diff --git a/ext/data/api.mq.md b/ext/data/api.mq.md
        new file mode 100644
        index 0000000..d86be11
        --- /dev/null
        +++ b/ext/data/api.mq.md
        @@ -0,0 +1,28 @@
        +---
        +markup: occlusion
        +title: Read-only JSON query routes for a database-backed site
        +import:
        +  plugin: lib/plugin.mq.md
        +---
        +
        +Use this leaf when a prepared web application needs native read-only database JSON routes. Database connections remain owned by db.mq.md; request tenant selection remains owned by the security tenant resource. This module only binds an explicit query table before listening. It does not introduce a second application configuration language.
        +
        +## mount
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| app | any | required | Prepared application with its database resource |
        +| routes | any | required | GFM rows with path, method, table, order, limit and optional tenant_scope |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | any | Updated app containing the selected JSON query route set |
        +
        +Use `app` and `routes` with plugin. The table uses site-relative paths, database table names, a native order expression and row limits. This binding replaces the application's JSON query route set; supply all desired query routes in one readable table. Other middleware settings are retained. Keep the returned app for subsequent resource bindings and listen.
        +
        +Set tenant_scope to True only together with tenant.attach from ext/security/tenant.mq.md. With tenant resolution enabled, a scoped query requires a resolved tenant and adds an equality filter on its configured column. Tenant selectors do not authenticate users or prove membership. Protect private data through real authentication and trusted tenant selection; a query-string demonstration deliberately permits choosing either demo tenant.
        +
        +The native route surface selects rows and returns a JSON object with a rows list; it does not implement arbitrary SQL, write endpoints or form submission. Reading this source grants no network access and mounting does not listen. Extend native query behavior in the existing web middleware implementation, keep database policy visible in the route table, and test missing-tenant as well as cross-tenant responses.
        +
        +We **native = [Resolve the maintained database/web boundary](plugin.native_path(name="web"))** and **[Load its existing route implementation](plugin.load(path=`native`))**.
        +Return *[Bind this explicit JSON query route table](web_app_middleware(app=`app`, cors=None, security=None, compress=None, body_limit=None, json_routes=`routes`, access_log=None, cache_control=None, proxy=None, invoke=None))*.
        diff --git a/ext/data/form.mq.md b/ext/data/form.mq.md
        index a567917..2d4194a 100644
        --- a/ext/data/form.mq.md
        +++ b/ext/data/form.mq.md
        @@ -26,6 +26,51 @@ We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="
           We **[End this run with the selected exit status](sys.exit(code=1))**.
         Return *None*.
         
        +
        +## reference
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| id | text | required | Exact id explicitly registered with mount |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Pure form_ref Resource for component.resource |
        +
        +Use `id` to reference the same mounted form that handles submissions. This constructor does not create a form, load a plugin or register a route. Serving resolves the id after preparing the request's actual CSRF token and return path. An unknown id is a real request error; it cannot become an empty successful form.
        +
        +The form's field/rule resource remains the single source for rendering and validation. Error responses retain the current CSRF token so the user can correct a field and resubmit. Authorization belongs to mount's optional role gate and the server's authentication policy, not the visibility of this node.
        +
        +`resource` =
        +
        +| _type | id |
        +|---|---|
        +| form_ref | `id` |
        +
        +Return *resource* for explicit placement in the existing View schema.
        +
        +## mount
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| app | any | required | Prepared web application with its actual database |
        +| id | text | required | Explicit system-form identifier used by reference |
        +| form | any | required | Form resource containing fields, rules and submission action |
        +| roles | any | None | None keeps public form behavior; otherwise gate the actual system form route |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | any | Updated app with this form and optional server role gate |
        +
        +Use `app`, `id`, `form` and `roles`=None before listening. Keep the returned app. The native system form route uses the same resource to validate and submit; component.resource only places its reference in the readable page layout. No user route is implicitly registered. System endpoints remain visible through web.inspect.
        +
        +For a private form, provide roles explicitly so the actual /_form/id GET and POST path is gated as well as any containing page. Merely hiding a form or gating its presentation URL is insufficient. Configure authentication separately. A public creation example can retain roles=None. Existing sessions must submit the correct CSRF token; field-validation retries keep that token in the response.
        +
        +We **[Load the existing form implementation](_load())** and **mounted = [Bind this form to its explicit system id](web_app_mount_form(app=`app`, id=`id`, form=`form`))**.
        +1. `roles` != None
        +  We **mounted = [Protect the actual system form endpoint](web_app_gate(app=`mounted`, path="/_form/" + id, roles=`roles`, permissions="", match="exact", on_deny="redirect", exclude=None))**.
        +Return *mounted* after the explicit form resource and policy are attached.
        +
         # form
         
         | 参数 | 类型 | 默认 | 说明 |
        diff --git a/ext/data/index.mq.md b/ext/data/index.mq.md
        index acfd3e0..a6bbd25 100644
        --- a/ext/data/index.mq.md
        +++ b/ext/data/index.mq.md
        @@ -6,12 +6,18 @@ import:
           db_api: ext/data/db.mq.md
           fs: lib/fs.mq.md
           path: lib/path.mq.md
        +  result: lib/result.mq.md
         ---
         
         Start here when a program needs persistent records, short-lived values, object storage or forms.
         The public resource files remain the implementation: [database](db.mq.md) owns schemas and
         transactions, [cache](cache.mq.md) owns expiry, [storage](storage.mq.md) owns blobs and upload
         validation, and [forms](form.mq.md) separates validation, rendering and submission.
        +[View queries](view.mq.md) (中文:[视图](视图.mq.md)) retain current records inside recursive View nodes.
        +[Native administration](admin.mq.md) exposes only mounted forms and their business tables.
        +中文作者可以使用[表单](表单.mq.md)构造、定义字段规则、引用与挂载资源,使用[后台](后台.mq.md)启用同一个原生管理入口。
        +[JSON query routes](api.mq.md) bind read-only database responses to a prepared site;
        +pair tenant-scoped queries with the explicit security tenant resource.
         
         These modules use the native web plugin. In this source checkout build it with
         scripts/build-web-plugin.sh; installed packages follow the web package installation route.
        @@ -22,7 +28,7 @@ Neither example needs a cloud account, credentials or an external service.
         
         ```sh
         marqdo call ext/data/index.mq.md memory_cache 'key="manual"' 'value="ready"' --effects plugin --json
        -marqdo call ext/data/index.mq.md transaction_roundtrip "root=\"$MQ_WORK\"" --effects plugin,fs.write --fs-root "$MQ_WORK" --json
        +marqdo call ext/data/index.mq.md transaction_roundtrip --effects plugin,fs.write --fs-root "$MQ_WORK" --json
         ```
         
         A resource constructor creates an object; its methods need that actual receiver. Use the free
        @@ -62,19 +68,22 @@ so another operation does not inherit it. Return *stored* as observed, including
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| root | text | required | Absolute disposable root, matching --fs-root; native resource URLs need an absolute path |
        +| root | text | "." | Expected filesystem root; the default uses the actual --fs-root context |
         
         | 返回 | 类型 | 说明 |
         |---|---|---|
         | result | map | The committed row list and native commit/rollback outcomes; the second insert is rolled back |
         
        -Use the absolute `root` supplied for --fs-root. This isolated-file example shows the whole ownership sequence: create a schema, begin a transaction,
        +Use `root`="." for the actual --fs-root context, or pass the same absolute root explicitly. This isolated-file example shows the whole ownership sequence: create a schema, begin a transaction,
         write through its receiver, finish it, and read outside it. A second transaction is explicitly
         rolled back. The standalone txn constructor wraps the actual native identifier and connection URL;
         it does not begin another transaction or invent an identifier.
         
        +We **actual_root = [Resolve the actual granted filesystem root](fs.resolve(path="."))** and **expected_root = [Check the optional explicit root](fs.resolve(path=`root`))**.
        +1. `actual_root` != `expected_root`
        +  Return *[Keep an inconsistent resource root explicit](result.error(code="data.root", message="root must match the granted filesystem root", operation="transaction_roundtrip"))*.
         First **directory = [Create an owned temporary directory under the granted root](fs.temp_dir(prefix="data-manual"))**.
        -The filesystem helper returns a root-relative name. We retain **work_dir = [Resolve that owned name against the explicit root](path.join(a=`root`, b=`directory`))**
        +The filesystem helper returns a root-relative name. We retain **work_dir = [Resolve the owned name through the actual filesystem context](fs.resolve(path=`directory`))**
         and **[Check that this absolute directory is inside the granted filesystem root](fs.stat(path=`work_dir`))**
         before giving any path to the native database. We select **database_path = [Choose the SQLite file inside that directory](path.join(a=`work_dir`, b="manual.db"))**
         and select **database_url = "sqlite:" + database_path** before creating
        diff --git a/ext/data/view.mq.md b/ext/data/view.mq.md
        new file mode 100644
        index 0000000..b345e00
        --- /dev/null
        +++ b/ext/data/view.mq.md
        @@ -0,0 +1,40 @@
        +---
        +markup: occlusion
        +title: Request-time database View resources
        +---
        +
        +Use this single-file resource handbook when a recursively composed page needs current database rows on each request. Construction is pure: it records a query without connecting, selecting or rendering HTML. Place the result in component.resource and retain view: main for startup layout assembly. The application supplies its actual database resource when serving.
        +
        +Do not combine view: main with automatic data_source metadata. Ordinary Documents keep that metadata path; explicit View pages use this query Resource instead. A missing database, invalid condition or backend failure remains a request error, never a fabricated empty list. See [the request-resource design](../../doc/design/web-view-resources.md).
        +
        +## query
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| source | text | required | Existing table on the serving application's database |
        +| where | any | None | Native condition map or list; route placeholders resolve from actual request params |
        +| order | text | "" | Native database ordering, such as -created_at |
        +| limit | number | 50 | Integer from 1 through 1000 |
        +| detail | bool | False | False renders cards; True renders the first matching full article |
        +| link_prefix | text | "/post/" | Site-relative prefix applied to row slugs, or empty for no prefix |
        +| tenant_scope | bool | False | Require an attached tenant policy and current tenant filter |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Pure data_query Resource; no query has executed yet |
        +
        +Use `source`, `where`=None, `order`="", `limit`=50, `detail`=False, `link_prefix`="/post/" and `tenant_scope`=False. The native renderer validates the contract before listening, then selects current records for each request. Card titles and summaries are escaped; article content uses the existing Markdown renderer. Detail mode prefers the complete body/content even when a summary exists.
        +
        +Rows follow the current Document convention: title, slug or href, summary, body or content, optional created_at/meta and tag. This fixed projection preserves the native card/article surface without restoring a private binding-table DSL. Layout remains in parent components; this resource only supplies one dynamic content region. For a different domain projection, keep a separate documented resource rather than passing arbitrary page configuration.
        +
        +Conditions are copied before replacing route placeholders, so one request cannot mutate another's retained definition. Path parameters take precedence over query keys. A requested tenant scope requires actual tenant configuration and context; direct selectors do not prove user membership. Link visibility and data filtering do not replace authentication or server authorization.
        +
        +This constructor needs no effects. Serving needs the actual web/database plugin and the launcher grants. Rendering the Resource offline without request context reports that requirement explicitly. Reading this file does not authorize a query, write or network listener.
        +
        +`resource` =
        +
        +| _type | source | where | order | limit | detail | link_prefix | tenant_scope |
        +|---|---|---|---|---|---|---|---|
        +| data_query | `source` | `where` | `order` | `limit` | `detail` | `link_prefix` | `tenant_scope` |
        +
        +Once its intended request behavior is explicit, return *resource* for placement in a View resource node.
        diff --git a/ext/data/后台.mq.md b/ext/data/后台.mq.md
        new file mode 100644
        index 0000000..10f0289
        --- /dev/null
        +++ b/ext/data/后台.mq.md
        @@ -0,0 +1,24 @@
        +---
        +markup: occlusion
        +title: 原生后台资源
        +import:
        +  admin: ext/data/admin.mq.md
        +---
        +
        +本文件与 admin.mq.md 的原生后台开关对应。自定义后台 Document 继续显式声明自己的路由;这里仅启用已有的原生后台。先准备应用,再启用后台、附加鉴权,最后监听。它不承担任意页面配置或数据库管理语言。
        +
        +## 启用
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 应用 | map | 必填 | 准备站点返回的应用,保留数据库和后台路径 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| 结果 | map | 只改变原生后台标志的新应用;未开始监听 |
        +
        +输入`应用`,本操作是纯资源组合,无需插件,不创建路由服务器或新数据库。保留返回的新应用后再附加鉴权,使原生策略安装默认后台门禁。后台只列显式挂载表单关联的业务表,每表展示至多 100 条当前记录,并链接到真实表单。
        +
        +它不枚举其他凭据、会话表,也不开放任意 SQL。启用展示能力不证明用户已经认证,应验证匿名拒绝与已登录访问两个方向。自定义内容布局继续由 View 与 Document 负责;不要为后台添加新的通用配置袋。
        +
        +配置后返回 *[启用已有的原生后台能力](admin.enable(app=`应用`))*。
        diff --git a/ext/data/表单.mq.md b/ext/data/表单.mq.md
        new file mode 100644
        index 0000000..c463994
        --- /dev/null
        +++ b/ext/data/表单.mq.md
        @@ -0,0 +1,110 @@
        +---
        +markup: occlusion
        +title: 表单资源:构造、规则、引用与挂载
        +import:
        +  form: ext/data/form.mq.md
        +---
        +
        +本文件对应英文 form.mq.md 的服务端装配工作流,中文作者直接调用这些具名函数。独立校验、离线表单渲染与直接提交仍使用英文文件对象的 validate、render、submit,不把页面引用当成直接写入工具。字段与规则同属一个原生表单资源,页面只安放引用,服务入口显式挂载它。构造、字段更新、校验与提交需要 plugin;引用是纯计算。以下示例只构造引用,不打开数据库或提交记录。
        +
        +```sh
        +marqdo call ext/data/表单.mq.md 引用 '标识="article"' --json
        +```
        +
        +准备真实表单时按构造、字段、规则、文案的顺序保留每次返回的新资源,再挂载到已准备的应用。实际处理请求的是 /_form/标识 系统地址。只保护展示页面不能保护提交入口;私有表单应给挂载指定角色,并另行配置鉴权。
        +
        +## 构造
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 表 | text | 必填 | 已存在的数据库业务表名 |
        +| 动作 | text | "insert" | 原生提交动作,例如 insert 或 update |
        +| 标识 | any | None | update 使用的记录标识;插入通常不指定 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| 结果 | any | 尚未提交的原生表单资源 |
        +
        +输入`表`、`动作`="insert"与`标识`=None,调用需要 plugin。这里只创建表单资源,不建表、不插入记录,也不验证一次用户请求。继续调用字段与规则保留完整定义;实际数据库来自服务入口的应用资源。缺少原生插件或不支持的动作应保留真实诊断。
        +
        +构造完成后返回 *[创建指定业务表的原生表单](form.form(table=`表`, action=`动作`, id=`标识`))*。
        +
        +## 字段
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 资源 | any | 必填 | 构造返回的实际表单资源 |
        +| 定义 | any | 必填 | name、label、type、required 等字段记录表 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| 结果 | any | 带字段定义的新表单资源 |
        +
        +输入`资源`和`定义`。name 应对应业务表字段;label 是展示文案,type 选择原生输入类型,required 使用布尔值。记录表用 @ 首列保持逐行结构。更新需要 plugin,返回值供规则或挂载继续使用;不提交用户输入,也不改变数据库结构。
        +
        +完成定义后返回 *[将字段绑定到同一个表单](> `资源`.fields fields=`定义`)*。
        +
        +## 规则
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 资源 | any | 必填 | 已有字段定义的实际表单资源 |
        +| 定义 | any | 必填 | field、rule、message 记录;例如 required 与 max:120 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| 结果 | any | 带原生校验规则的新表单资源 |
        +
        +输入`资源`和`定义`。规则按字段名关联,message 是拒绝输入时显示的原因。服务端仍执行相同规则,不能只依赖浏览器必填属性。此步需要 plugin,但不会尝试插入或更新记录。保留返回值,避免挂载未携带新规则的旧资源。
        +
        +规则明确后返回 *[绑定实际提交使用的校验规则](> `资源`.rules rules=`定义`)*。
        +
        +## 文案
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 资源 | any | 必填 | 保留字段和规则的实际表单资源 |
        +| 提交 | text | "提交" | 提交按钮文字 |
        +| 取消 | text | "取消" | 取消链接文字 |
        +| 返回地址 | text | "" | 取消目标;也是原生成功提交返回地址 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| 结果 | any | 带按钮文字和返回目标的新资源 |
        +
        +输入`资源`、`提交`="提交"、`取消`="取消"和`返回地址`="",调用需要 plugin。文案是纯文本,不承载 HTML。显式返回地址用于成功后的跳转;没有指定时由原生请求返回路径决定。设置按钮文案本身既不授权提交,也不改变字段校验规则。
        +
        +配置后返回 *[保留提交、取消与成功返回目标](> `资源`.labels submit=`提交` cancel=`取消` cancel_href=`返回地址`)*。
        +
        +## 引用
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 标识 | text | 必填 | 服务入口通过挂载显式注册的系统表单标识 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| 结果 | map | 供组件请求资源节点安放的 form_ref 描述 |
        +
        +使用`标识`引用实际挂载的表单。构造无需任何副作用,不加载插件、不注册路由,也不伪造字段或 CSRF。请求时才由原生服务读取当前会话、返回路径和同一份字段规则;未挂载的标识保留错误,不能变成空的成功表单。
        +
        +声明后返回 *[引用请求时的同一个表单](form.reference(id=`标识`))*。
        +
        +## 挂载
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 应用 | any | 必填 | 已准备、保留数据库与路由上下文的应用 |
        +| 标识 | text | 必填 | 页面引用与系统 /_form/ 路径使用的标识 |
        +| 资源 | any | 必填 | 保留字段、规则和文案的实际表单 |
        +| 角色 | any | None | None 保持公开行为;否则保护实际系统表单 GET 与 POST |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| 结果 | any | 挂载资源与可选角色门禁后的新应用 |
        +
        +使用`应用`、`标识`、`资源`与`角色`=None,在监听前授予 plugin 并保留返回的应用。挂载绑定的是明确的系统地址,不暗中注册业务页面。私有表单应指定允许的角色并配置鉴权;仅隐藏控件或保护展示页不足以保护提交。
        +
        +会话存在时提交必须携带真实 CSRF,字段失败的重试页面仍保留该令牌。系统路径可通过网页检视观察,但检视不能证明数据库可写或当前用户获准提交。公开示例可以保持角色为空,生产策略由调用者明确决定。
        +
        +准备就绪后返回 *[绑定实际表单处理器及其访问策略](form.mount(app=`应用`, id=`标识`, form=`资源`, roles=`角色`))*。
        diff --git a/ext/data/视图.mq.md b/ext/data/视图.mq.md
        new file mode 100644
        index 0000000..2dc1b37
        --- /dev/null
        +++ b/ext/data/视图.mq.md
        @@ -0,0 +1,40 @@
        +---
        +markup: occlusion
        +title: 请求期间查询数据库的视图资源
        +---
        +
        +本文件是单文件资源手册。递归页面需要随请求变化的数据库记录时,构造这里的查询资源,再放入组件的资源节点。构造本身是纯计算,不连接数据库,也不生成 HTML;实际查询使用监听应用绑定的数据资源。
        +
        +view: main 仍在启动时装配结构,不能混用自动 data_source 元数据。普通文档可继续使用元数据绑定;显式 View 用本资源表达动态内容。缺少数据库、条件错误或后端故障都保留请求诊断,不伪造空列表。
        +
        +## 查询
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 源 | text | 必填 | 监听应用数据库中已有的业务表 |
        +| 条件 | any | None | 原生条件记录或列表;路径占位来自实际请求参数 |
        +| 排序 | text | "" | 数据库排序,例如 -created_at |
        +| 上限 | number | 50 | 1 至 1000 之间的整数 |
        +| 详情 | bool | False | False 显示卡片,True 显示首条完整文章 |
        +| 链接前缀 | text | "/post/" | 加到短链前的站内路径前缀 |
        +| 租户作用域 | bool | False | 要求显式租户策略及实际租户上下文 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| 结果 | map | 尚未查询的 data_query 资源,可放入资源节点 |
        +
        +使用`源`、`条件`=None、`排序`=""、`上限`=50、`详情`=False、`链接前缀`="/post/"与`租户作用域`=False。服务器先检查资源契约,再在每个请求中查询当前记录。卡片标题与摘要经过转义,完整文章使用已有 Markdown 渲染器;有摘要时,详情仍应显示完整正文,空正文也不会被摘要替换。
        +
        +返回记录沿用文档的数据约定:title、slug 或 href、summary、body 或 content,以及可选的 created_at/meta 与 tag。父组件继续决定布局,本资源只承担一个动态内容区域。它不恢复旧的页面绑定表,也不接受任意页面配置。需要其他领域投影时,应另立职责清楚的资源。
        +
        +每次请求先复制条件,再替换实际路径参数,避免污染启动时保留的定义。路径参数优先于同名查询参数。租户作用域要求已有租户策略和已解析租户;请求中的选择值不证明用户属于该租户,数据过滤也不能替代鉴权。
        +
        +构造不需要副作用权限;服务实际使用插件和监听入口的授权。离线渲染缺少请求上下文时明确报错,不声称已执行查询。阅读源码不会授权数据库访问、写入或启动网络监听。
        +
        +`资源` =
        +
        +| _type | source | where | order | limit | detail | link_prefix | tenant_scope |
        +|---|---|---|---|---|---|---|---|
        +| data_query | `源` | `条件` | `排序` | `上限` | `详情` | `链接前缀` | `租户作用域` |
        +
        +请求行为交代清楚后,返回 *资源*,交给组件资源节点安放。
        diff --git a/ext/engineering/index.mq.md b/ext/engineering/index.mq.md
        new file mode 100644
        index 0000000..f3f73df
        --- /dev/null
        +++ b/ext/engineering/index.mq.md
        @@ -0,0 +1,371 @@
        +---
        +markup: occlusion
        +title: Engineering boundaries for executable handbooks
        +import:
        +  plugin: lib/plugin.mq.md
        +  sys: lib/sys.mq.md
        +  paths: lib/path.mq.md
        +  table: lib/table.mq.md
        +  result: lib/result.mq.md
        +---
        +
        +This extension supplies the small OS and service boundaries used by executable
        +engineering handbooks. File reads/writes, JSON/TOML, data decisions, retries and
        +release ordering remain Marqdo code. The native plugin provides bounded argv
        +process execution, private authenticated GitHub HTTPS, ZIP inspection and R2
        +Signature V4 uploads. No Python interpreter or generated shell program is used.
        +
        +Read the task contract before calling it. Process children and native plugins
        +have the calling OS user's authority; a plugin grant is broader than a native
        +filesystem grant. The root parameter selects a working/artifact directory, not
        +an OS sandbox. Never treat reading this file as authorization to push refs,
        +change a release, upload assets or run arbitrary commands.
        +
        +Build this repository's marqdo_plugin_engineering crate before first use; the
        +development handbook's prepare_engineering task performs that bootstrap through
        +marqdo call. MARQDO_ENGINEERING_PLUGIN may select a locally built library. Installed
        +packs use the same plugin resolver as other official extensions. This boundary
        +is native-only; browser WASM cannot start processes or load this library.
        +
        +The public operation definitions and private request helper below share one
        +implementation. For the complete release workflow, read
        +[the executable release handbook](../../skills/marqdo-release/index.mq.md).
        +Normal filesystem work uses [the native file tools](../../skills/marqdo-dev/files.mq.md);
        +this extension is not an alternate file-write API.
        +
        +## _load
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | any | Load the installed or locally built engineering plugin |
        +
        +Resolve the library through the existing extension resolver so an installed
        +pack and a development build share the same public calls. A missing library
        +produces the normal plugin diagnostic; build or install it rather than hiding
        +the failure behind a fixed success result. Repeated loads use the host loader's
        +existing ownership rules. This private boundary requires plugin effects and
        +never guesses a Python replacement or invents an external interpreter.
        +
        +We **path = [Resolve the engineering native library](plugin.native_path(name="engineering"))**.
        +After locating it we return *[Load the bounded engineering operations](plugin.load(path=`path`))*.
        +
        +## request
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| operation | text | required | command, git_inspect, github, archive, analyze, gzip_text or r2_put |
        +| payload | map | required | Operation-specific ordinary data; never credential values |
        +| root | text | "." | Existing working/artifact root for this operation |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Result.ok/value/error from the selected boundary |
        +
        +Use `operation`, `payload` and `root`="." only at a documented native boundary.
        +Inputs travel as structured plugin values, not strings containing a generated
        +program. Failed process setup, HTTP, archive validation or signing remains a
        +failed Result. A successful command request still requires checking value.code
        +and value.timed_out. No private credential becomes a tool argument or result;
        +authentication is resolved inside the plugin from existing stores.
        +
        +We **loaded = [Load this package's native boundary](_load())** and
        +**base = [Read the granted runtime working root](sys.cwd())** and **resolved_root = root**.
        +1. not [The requested root is already absolute](paths.is_absolute(path=`root`))
        +  We **resolved_root = base + "/" + root** so process and native filesystem locations agree.
        +
        +`request_data` =
        +
        +| operation | payload | root |
        +|---|---|---|
        +| `operation` | `payload` | `resolved_root` |
        +
        +Return *[Perform the explicit native boundary operation](engineering_request(request=`request_data`))*.
        +
        +## run
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| argv | list | required | Executable followed by individual text arguments |
        +| cwd | text | "." | Existing directory inside root |
        +| timeout_ms | number | 120000 | Positive limit through 3600000 milliseconds |
        +| max_output | number | 262144 | Per-stream capture limit through 16777216 bytes |
        +| stdin | any | None | Optional text sent to child stdin, then closed |
        +| env | any | None | Optional child-only text environment values |
        +| root | text | "." | Root used to resolve cwd and local Git identity |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Result containing code/stdout/stderr/timed_out/truncated |
        +
        +Use `argv`, `cwd`=".", `timeout_ms`=120000, `max_output`=262144, `stdin`=None,
        +`env`=None and `root`="." to invoke an existing OS tool. Arguments are passed
        +individually even when they contain quotes, spaces or shell metacharacters.
        +Inline shell programs, forced Git updates and hook bypass are rejected; a
        +checked-in packaging script remains a normal explicit external-tool invocation.
        +
        +The return distinguishes transport completion from child success. Inspect code
        +and timed_out before consuming stdout. Output is drained concurrently and kept
        +within the requested cap so noisy children cannot deadlock their own pipes.
        +On Unix, timeout kills the child process group; Windows attempts taskkill's tree
        +termination. Output retained by surviving descendants cannot cause unbounded
        +waiting. A process environment is child-local and does not mutate the parent.
        +
        +`payload` =
        +
        +| argv | cwd | timeout_ms | max_output | stdin | env |
        +|---|---|---|---|---|---|
        +| `argv` | `cwd` | `timeout_ms` | `max_output` | `stdin` | `env` |
        +
        +Return *[Execute the explicit argument vector with bounded capture](request(operation="command", payload=`payload`, root=`root`))*.
        +
        +## github
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| path | text | required | API path under /repos/cflmy/marqdo/ |
        +| method | text | "GET" | GET, PATCH or POST; mutations need the user's task instruction |
        +| data | any | None | JSON body; no authentication data |
        +| missing | bool | False | Treat GET 404 as a successful None |
        +| root | text | "." | Checkout used by credential helpers |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Result containing service JSON, None or a redacted transport error |
        +
        +Use `path`, `method`="GET", `data`=None, `missing`=False and `root`=".".
        +The plugin resolves GH_TOKEN/GITHUB_TOKEN, Git's configured credential helper or
        +the checkout owner's existing gh store privately. It tries the configured
        +GitHub proxy before direct HTTPS. An uncertain POST is not replayed; a caller
        +must observe whether publication occurred before deciding to retry a mutation.
        +
        +Only this repository's API paths are accepted. HTTP errors report their status
        +without reflecting credentials, signed URLs or arbitrary response bodies.
        +Missing evidence stays missing; a network failure is not a synthetic empty
        +release. Test endpoint overrides are explicit environment configuration and
        +belong only in isolated fixture runs.
        +
        +`payload` =
        +
        +| path | method | data | missing |
        +|---|---|---|---|
        +| `path` | `method` | `data` | `missing` |
        +
        +Return *[Request private-authenticated repository service JSON](request(operation="github", payload=`payload`, root=`root`))*.
        +
        +## inspect_zip
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| path | text | required | Existing ZIP or VSIX inside root |
        +| root | text | "." | Artifact root; symlink escapes are refused |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Result with entries and selected UTF-8 package metadata |
        +
        +Use `path` and `root`="." to inspect a binary format without extraction.
        +The plugin caps entry count and total expanded size, rejects escaping paths and
        +symlinks, and reads every entry to validate its content/CRC. It retains only
        +bounded VERSION, Cargo and VSIX metadata text for Marqdo's role-specific checks.
        +Hashing the archive itself remains lib/fs.file_hash, not an alternate Python IO
        +path. ZIP metadata cannot prove plugin ABI compatibility or execute a program.
        +
        +We **payload = [Name the one archive path field](table.put(in=None, at="path", value=`path`))**.
        +
        +Return *[Inspect the archive format without writing extracted files](request(operation="archive", payload=`payload`, root=`root`))*.
        +
        +## put_file
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| path | text | required | Verified upload file inside root |
        +| key | text | required | Explicit R2 key such as vX.Y.Z/filename.zip |
        +| sha256 | text | required | Previously verified SHA256; changed bytes are rejected |
        +| root | text | "." | Root containing the local upload file |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Result with written key, SHA256 and byte count |
        +
        +Use `path`, `key`, `sha256` and `root`="." for an authorized publication.
        +The plugin transfers this bounded file across the authenticated service boundary
        +and rechecks its digest before signing; Marqdo decides which files and keys are
        +required. Credentials stay in existing R2 environment settings or ~/.marqdo/r2.env.
        +A configured credential home can select the maintainer's store when running under
        +another OS identity. Key material is never a parameter, result or command argument.
        +
        +This is an external write. Successful PUT is evidence for that key only; public
        +CDN parity is checked separately. The release handbook uploads every pack before
        +writing VERSION pointers and never sweeps unrelated files from dist. A timeout
        +remains uncertain publication, so inspect the public object before retrying.
        +
        +`payload` =
        +
        +| path | key | sha256 |
        +|---|---|---|
        +| `path` | `key` | `sha256` |
        +
        +Return *[Upload exactly the verified artifact with private R2 signing](request(operation="r2_put", payload=`payload`, root=`root`))*.
        +
        +## put_text
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| key | text | required | Explicit VERSION key selected by the release workflow |
        +| text | text | required | Small UTF-8 pointer body with its intended trailing newline |
        +| root | text | "." | Checkout used to locate existing credential stores |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Result with written key, SHA256 and byte count |
        +
        +Use `key`, `text` and `root`="." only after all required publication bytes are
        +verified. This operation signs a small UTF-8 service body; it does not write a
        +local file or infer which version should become latest. The calling Marqdo
        +workflow owns that decision and its ordering. Keys remain explicit so a replay
        +cannot silently publish a different version from environment state.
        +As with put_file, service completion does not substitute for reading the public
        +pointer and checking the associated download hashes.
        +
        +`payload` =
        +
        +| key | text |
        +|---|---|
        +| `key` | `text` |
        +
        +Return *[Write the explicitly selected publication pointer](request(operation="r2_put", payload=`payload`, root=`root`))*.
        +## analyze
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| source | text | required | Exact source text already read through lib/fs |
        +| include_body | bool | False | Include compiler AST debug evidence for migration review |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Result with compiler functions, contracts, diagnostics and narrative ratios |
        +
        +Use `source` and `include_body`=False to inspect an authored document
        +without executing it. File access belongs to the caller's native filesystem
        +step; this operation receives text and uses the actual Marqdo parser and checker.
        +It does not invent a regular-expression grammar, load imports, run main, open
        +network resources or infer permission from prose. Full dependency checks still
        +use marqdo check on the real file.
        +
        +The returned parameter names, defaults, heading spans and contracts support
        +editing without guessing the syntax. Narrative ratios come from the same
        +implementation used by the repository gate. AST debug evidence is optional
        +because it is large and intended for mechanical migration comparisons, while
        +the normal result remains a compact source description.
        +
        +`payload` =
        +
        +| source | include_body |
        +|---|---|
        +| `source` | `include_body` |
        +
        +Return *[Inspect this text with the real compiler](request(operation="analyze", payload=`payload`))*.
        +
        +
        +## gzip_text
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| data | map | required | Portable bytes returned by net.get(response="bytes") |
        +| max_bytes | number | 16777216 | Positive expanded UTF-8 limit, at most 64 MiB |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Result containing decoded UTF-8 text or bounded format failure |
        +
        +Use `data` and `max_bytes`=16777216 at a compressed data boundary.
        +Native net.get owns the network read and returns portable bytes; this operation
        +only interprets their gzip format. It accepts concatenated gzip members, validates
        +their checksums, caps compressed input and expanded output, and rejects non-UTF-8
        +text. No temporary file, shell pipeline or Python process is involved.
        +
        +This is useful for a published apt Packages.gz index. A successful HTTP response
        +alone cannot establish its package version; decode and inspect its real stanzas.
        +Malformed data or an expansion beyond the cap remains an error. Binary payloads
        +are outside this text contract. Calling requires plugin, while the caller's
        +earlier download independently requires network.read.
        +
        +`payload` =
        +
        +| data | max_bytes |
        +|---|---|
        +| `data` | `max_bytes` |
        +
        +Return *[Decode the bounded compressed text format](request(operation="gzip_text", payload=`payload`))*.
        +
        +
        +## check_exit
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| outcome | map | required | Actual Result returned by engineering.run or its command boundary |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Observed process Result; failure retains its complete bounded execution evidence |
        +
        +Use `outcome` from an actual process call. Starting a process successfully is
        +different from that process succeeding: command transport can return ok=true
        +with a nonzero child code. This pure adapter requires code zero and no timeout.
        +It never starts or retries a process, changes a command or discards failed output.
        +
        +A setup/transport failure is retained unchanged. A nonzero exit or timeout becomes
        +a failed Result with the original execution record in value, including stdout,
        +stderr and truncation flags. This makes --require-ok useful for a complete
        +callable workflow without treating CLI transport success as a passed build.
        +Bounded output can be truncated even when the command succeeds; inspect that
        +flag before describing it as a full log.
        +
        +This function only classifies supplied observations. It cannot prove that an
        +arbitrary caller-provided map came from a real command. Development tasks call
        +run and then this adapter in the same source flow, retaining their actual argv
        +and result. Release ordering and retry policy remain the caller's responsibility.
        +
        +1. not access(`outcome`, "ok")
        +  Return *outcome* with its original native setup failure.
        +We **execution = [Read the actual bounded process observation](access(outcome, "value"))**.
        +1. access(`execution`, "code") != 0 or access(`execution`, "timed_out")
        +  We **failed = [Distinguish child failure from successful transport](result.error(code="engineering.process_failed", message="nonzero exit or timeout; inspect the actual execution in value", operation="check_exit"))**.
        +  Return *[Keep all observed process evidence on failure](table.put(in=`failed`, at="value", value=`execution`))*.
        +Return *outcome* after the observed child exits successfully.
        +
        +
        +## checked
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| argv | list | required | Existing executable and individual text arguments |
        +| cwd | text |  "."  | Existing working directory within root |
        +| timeout_ms | number | 120000 | Positive child duration limit up to one hour |
        +| max_output | number | 262144 | Bounded bytes retained per stdout/stderr stream |
        +| stdin | any | None | Optional text sent to child standard input |
        +| env | any | None | Optional child-only text environment record |
        +| root | text |  "."  | Working root matching the intended checkout |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Result requiring a zero child exit; actual execution evidence is retained |
        +
        +Use `argv`, `cwd`=".", `timeout_ms`=120000, `max_output`=262144,
        +`stdin`=None, `env`=None and `root`="." to execute one existing tool and require
        +its success in the same callable workflow. It composes run and check_exit rather
        +than regenerating process management, credential handling or a shell program.
        +The parameter vector, directory and resource limits keep their existing meaning.
        +
        +A setup failure, nonzero exit or timeout returns ok=false. Its actual stdout,
        +stderr and truncation state remain available for diagnosis. A successful result
        +means the observed child exited successfully; interpreting its business output
        +still belongs to the caller. Use --require-ok when this single call controls a
        +dependent external automation. No retry or publication is implied.
        +
        +This operation requires plugin. Its child retains normal OS authority, and the
        +native boundary keeps its existing argv guards and private credential rules.
        +For example, a unit-test task can pass cargo, test, --lib and --offline as four
        +separate text elements without needing a new generated command script.
        +
        +After the bounded execution we return *[Require the actual child outcome and preserve all evidence](check_exit(outcome=run(argv=`argv`, cwd=`cwd`, timeout_ms=`timeout_ms`, max_output=`max_output`, stdin=`stdin`, env=`env`, root=`root`)))*.
        diff --git a/ext/engineering/索引.mq.md b/ext/engineering/索引.mq.md
        new file mode 100644
        index 0000000..2123b3a
        --- /dev/null
        +++ b/ext/engineering/索引.mq.md
        @@ -0,0 +1,182 @@
        +---
        +markup: occlusion
        +title: 工程拓展:让开发与发版操作成为可调用手册
        +import:
        +  工程: ./index.mq.md
        +---
        +
        +本文件是 [英文工程入口](index.mq.md) 的中文门面,复用同一个原生插件与行为。开发中的文件读取、撰写、哈希与数据处理应先使用标准库;本拓展只补齐进程、私密认证与压缩格式边界。任务的条件、重试和步骤顺序写在 mq.md 中,不再生成 Python 编排器。
        +
        +首次使用前通过 skills/marqdo-dev/index.mq.md 的 prepare_engineering 构建本机开发解释器和插件。读取库文档不代表授权发布;推送、修改发布说明和上传对象必须属于用户已授权的任务。结果沿用 ok/value/error 字段,进程结果还要检查 code 和 timed_out,不能只根据请求成功就继续依赖步骤。
        +
        +可在仓库根目录运行 marqdo call ext/engineering/索引.mq.md 运行 '参数=["git","--version"]' --effects plugin --fs-root . --json。完整发版流程位于 skills/marqdo-release/index.mq.md;普通文件操作位于开发目录的 files.mq.md。本地原生插件与子进程具有当前系统用户的权限,浏览器 WASM 不支持这些边界。
        +
        +## 运行
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 参数 | list | required | 程序名与逐项文本参数,不是 shell 源码 |
        +| 目录 | text | "." | 根目录内的实际工作目录 |
        +| 超时毫秒 | number | 120000 | 1 到 3600000 毫秒 |
        +| 输出上限 | number | 262144 | 每个输出流的字节上限,最多 16 MiB |
        +| 输入 | any | None | 写入子进程标准输入后关闭;None 表示无输入 |
        +| 环境 | any | None | 仅影响子进程的文本环境映射 |
        +| 根目录 | text | "." | 与 --fs-root 一致的工程根目录;插件不提供操作系统沙箱 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Result:包含 code、stdout、stderr、timed_out 与 truncated |
        +
        +使用`参数`,工作`目录`=".",`超时毫秒`=120000,`输出上限`=262144,`输入`=None,`环境`=None,`根目录`="."。参数逐项传递,空格、美元符号和引号不会被再次当作 shell 程序求值。命令入口拒绝内联 shell、强推和跳过钩子。
        +
        +进程启动成功与命令执行成功是两个状态:必须检查 value.code 为零且 timed_out 为 False。输出并发读取并有界保存,避免大量日志堵住子进程。超时会尝试终止进程树,诊断信息保留已知凭据脱敏后的文本。调用需要 plugin;外部工具自己的文件和网络权限仍由操作系统决定。
        +
        +完成该边界调用后返回*[按明确参数执行维护中的工具](工程.run(argv=`参数`, cwd=`目录`, timeout_ms=`超时毫秒`, max_output=`输出上限`, stdin=`输入`, env=`环境`, root=`根目录`))*。
        +
        +## 分析源码
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 源码 | text | required | 已经通过固有文件库读取的完整源码 |
        +| 包含正文 | bool | False | 是否附带大体积 AST 调试证据 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Result:真实编译器的函数、契约、诊断和叙述比例 |
        +
        +接收`源码`和`包含正文`=False,仅分析传入文本,不替调用者读取文件。这里复用解释器的真实解析与检查实现,不建立一套正则表达式语法。分析不会加载导入文件、执行 main 或请求外部服务。
        +
        +参数顺序、默认值和源位置可以支持审阅式迁移;叙述比例采用仓库检查器的相同规则。附加正文仅适合需要逐语句核对的迁移诊断,普通使用先读契约与简要诊断。完整依赖正确性仍需对实际文件执行 marqdo check。调用需要 plugin,并不因源码描述了某个操作就授权执行该操作。
        +
        +读到分析结果后返回*[用真实编译器检查这段文本](工程.analyze(source=`源码`, include_body=`包含正文`))*。
        +
        +## 检查压缩包
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 路径 | text | required | 根目录内实际存在的 ZIP 或 VSIX |
        +| 根目录 | text | "." | 与 --fs-root 一致的工程根目录;插件不提供操作系统沙箱 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Result:包内条目与有界保存的版本元数据 |
        +
        +使用`路径`与`根目录`=".",读取格式并校验每个条目的 CRC,整个过程不解压、不执行文件。插件拒绝越界路径、重复名称、软链接和超限展开量;标准库负责压缩包本身的大小与 SHA256。
        +
        +检查格式通过不代表版本正确、插件 ABI 匹配或业务测试通过。调用者应继续核对具体产物角色、所需条目及 GitHub 提供的摘要。元数据文本有体积与 UTF-8 限制,缺失内容不能被当作已经验证。调用需要 plugin;根目录是工作位置,不能据此推断插件具有文件沙箱。
        +
        +完成格式校验后返回*[检查真实压缩条目及其 CRC](工程.inspect_zip(path=`路径`, root=`根目录`))*。
        +
        +## 解码gzip文本
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 数据 | map | required | 固有网络库返回的 portable bytes |
        +| 上限 | number | 16777216 | 展开后 UTF-8 字节上限,最多 64 MiB |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Result:解码文本或真实格式、编码、体积错误 |
        +
        +输入`数据`,设置`上限`=16777216。此任务只解释已经读取的 gzip 字节格式,不下载、不创建临时文件。它支持连接的 gzip 成员、校验校验和,并同时限制压缩输入与展开结果;非 UTF-8 数据也会返回失败。
        +
        +Ubuntu 的 Packages.gz 就需要这一格式边界。HTTP 请求成功后仍要解码实际索引并查找目标包,不能把 200 状态直接当作可安装证据。文件与网络读取仍由固有库完成,压缩格式缺口由拓展承接;调用需要 plugin,不需要 Python 或 shell 解压流水线。
        +
        +解码完成后返回*[有界解码已经读取的压缩文本](工程.gzip_text(data=`数据`, max_bytes=`上限`))*。
        +
        +## GitHub请求
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 路径 | text | required | 本项目 /repos/cflmy/marqdo/ 下的 API 路径 |
        +| 方法 | text | "GET" | GET 只读;PATCH 与 POST 属于外部写入 |
        +| 数据 | any | None | 结构化 JSON 请求体,不包含凭据 |
        +| 允许缺失 | bool | False | GET 的 404 是否表示成功的 None |
        +| 根目录 | text | "." | 与 --fs-root 一致的工程根目录;插件不提供操作系统沙箱 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Result:服务 JSON、允许的 None 或脱敏后的失败 |
        +
        +使用`路径`,`方法`="GET",`数据`=None,`允许缺失`=False,`根目录`="."。原生边界私密读取现有 GitHub 认证存储,先尝试已配置代理再直连;凭据不能成为工具参数或返回值。此接口仅用于本项目服务路径。
        +
        +POST 的不确定响应不会自动重放,避免重复发布。调用者需要先观察远端是否已经出现目标资源,再决定恢复操作。网络错误保留错误,只有明确允许的 GET 404 才变成 None。调用需要 plugin;读取本手册本身不授权 PATCH 或 POST,具体写入必须来自用户当前任务。
        +
        +服务请求完成后返回*[通过私密认证边界请求项目服务](工程.github(path=`路径`, method=`方法`, data=`数据`, missing=`允许缺失`, root=`根目录`))*。
        +
        +## 上传文件
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 路径 | text | required | 根目录内已经验证的上传文件 |
        +| 对象名 | text | required | 明确的 R2 对象名 |
        +| 摘要 | text | required | 预先通过固有文件库计算的 SHA256 |
        +| 根目录 | text | "." | 与 --fs-root 一致的工程根目录;插件不提供操作系统沙箱 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Result:已写对象、SHA256 与字节数 |
        +
        +使用`路径`、`对象名`、`摘要`及`根目录`=".",只上传用户已授权发布的具体文件。插件在签名前再次检查摘要,防止校验后文件已经改变。R2 密钥留在既有环境与私密配置中,不传给模型、不写入源码。
        +
        +此任务只证明这个对象的上传状态,不决定 latest,也不更新 VERSION。发布流程应先验证全部压缩包并上传,再写指针,最后读取公共 CDN 对比实际摘要。超时表示状态不确定,应观察对象而非立即假设没有上传。调用需要 plugin,原生文件整理与摘要计算仍由固有库完成。
        +
        +完成明确对象的上传后返回*[上传仍与预验摘要一致的文件](工程.put_file(path=`路径`, key=`对象名`, sha256=`摘要`, root=`根目录`))*。
        +
        +## 上传文本
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 对象名 | text | required | 发布流程明确选择的 VERSION 对象名 |
        +| 正文 | text | required | 包含预期换行的小体积 UTF-8 指针文本 |
        +| 根目录 | text | "." | 与 --fs-root 一致的工程根目录;插件不提供操作系统沙箱 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Result:已写对象、SHA256 与字节数 |
        +
        +使用`对象名`、`正文`和`根目录`=".",在全部相关压缩包已经验证并上传后更新指定指针。此任务不选择版本,也不判断是否应该成为 latest;这些顺序和决策在发版 mq.md 中公开表达。
        +
        +凭据仍由私密认证边界处理,正文不是本地文件写入的替代接口。请求成功之后还要读取公共指针及其对应压缩包,缓存延迟必须保持未完成状态,不能把另一次上传当作验证。调用需要 plugin,并且必须属于用户授权的发布任务;单纯阅读文档不能触发对象写入。
        +
        +完成该指针写入后返回*[写入流程已经确定的发布指针](工程.put_text(key=`对象名`, text=`正文`, root=`根目录`))*。
        +
        +
        +## 检查退出
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 结果 | map | required | 运行任务返回的真实 Result 与子进程观察 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Result:只接受零退出且未超时的观察,失败仍保留输出 |
        +
        +接收`结果`之后,按工程边界已有规则检查退出码和超时状态。进程成功启动不代表编译或测试通过,因此这里把非零退出转成失败 Result,标准输出、错误输出和截断标记仍保留在 value 中。启动失败则沿用原来的诊断。
        +
        +这个纯函数不再执行、重试或发布任何东西,也不能证明任意传入记录来自真实命令。需要完整的一次调用流程时,使用下方运行并检查,由它在同一份源码里连接真实执行与状态判断。
        +
        +检查结束后返回*[按实际子进程结果保留成功或失败证据](工程.check_exit(outcome=`结果`))*。
        +
        +
        +## 运行并检查
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 参数 | list | required | 已维护程序名及逐项文本参数 |
        +| 目录 | text | "." | 根目录内的实际工作目录 |
        +| 超时毫秒 | number | 120000 | 正数,最多 3600000 毫秒 |
        +| 输出上限 | number | 262144 | 每个输出流的有界字节数,最多 16 MiB |
        +| 输入 | any | None | 可选标准输入文本,发送后关闭 |
        +| 环境 | any | None | 仅影响子进程的文本环境记录 |
        +| 根目录 | text | "." | 实际工作根目录;不是操作系统沙箱 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Result:要求真实子进程成功,失败保留 code/stdout/stderr 等观察 |
        +
        +使用`参数`,工作`目录`=".",`超时毫秒`=120000,`输出上限`=262144,`输入`=None,`环境`=None,`根目录`="."。这里复用运行与检查退出两个已经实现的步骤,不再让智能体撰写另一份命令脚本。参数、私密凭据、进程树超时和输出上限都沿用已有原生边界。
        +
        +调用需要 plugin。启动失败、非零退出或超时返回 ok=False;配合 --require-ok 可以阻止后续自动化继续。成功只表示这次子进程按零退出结束,具体业务结果仍由调用者判断。子进程拥有正常操作系统权限,不能把根目录参数当作沙箱,也不能把阅读本文当作发布授权。
        +
        +执行结束后返回*[运行维护中的工具并检查其真实结果](工程.checked(argv=`参数`, cwd=`目录`, timeout_ms=`超时毫秒`, max_output=`输出上限`, stdin=`输入`, env=`环境`, root=`根目录`))*。
        diff --git a/ext/net/http.mq.md b/ext/net/http.mq.md
        index d2d5c74..bc005ff 100644
        --- a/ext/net/http.mq.md
        +++ b/ext/net/http.mq.md
        @@ -7,7 +7,7 @@ import:
           sys: lib/sys.mq.md
         ---
         
        -This file constructs the application Result record only; it does not implement an HTTP transport. For real HTTP requests, response limits and downloads, import lib/net.mq.md. The [network entry](index.mq.md) distinguishes pure URL transformations from native WebSocket exchanges. Keep these responsibilities explicit when extending the package so a readable tool name never implies a missing capability.
        +This file constructs application Result records and binds explicit server redirects; it does not implement an HTTP client. For real HTTP requests, response limits and downloads, import lib/net.mq.md. The [network entry](index.mq.md) distinguishes pure URL transformations from native WebSocket exchanges. Keep these responsibilities explicit when extending the package so a readable tool name never implies a missing capability.
         
         ## _load
         
        @@ -48,3 +48,21 @@ Unified Result map `{ok, value, error}`.
         | `ok` | `value` | `error` |
         
         Return *out*.
        +
        +## redirect
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| app | any | required | Prepared web application |
        +| from | text | required | Explicit source route |
        +| to | text | required | Redirect destination |
        +| permanent | bool | False | False uses a temporary redirect; True uses the native permanent status |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Updated app with the declared server redirect |
        +
        +Use `app`, `from`, `to` and `permanent`=False before web.listen. This is a server route policy owned by the network resource, not a client-side history operation. Keep the returned app because binding produces a new value. Redirecting a legacy entry path can coexist with Document and Endpoint discovery without rebuilding the application through removed configure methods. The native runtime validates declared source paths. No listener starts here, and constructing a redirect does not verify that its destination page exists.
        +
        +We **[Load the existing native HTTP runtime](_load())**.
        +Return *[Bind this declared HTTP redirect](web_app_redirect(app=`app`, from=`from`, to=`to`, permanent=`permanent`))*.
        diff --git a/ext/net/index.mq.md b/ext/net/index.mq.md
        index 1f90120..9f4f306 100644
        --- a/ext/net/index.mq.md
        +++ b/ext/net/index.mq.md
        @@ -10,6 +10,7 @@ This package provides [URL encoding](url.mq.md), the small [HTTP result construc
         and a native [WebSocket request/response resource](websocket.mq.md). For HTTP clients with
         status, timeout, response limits and downloads, read the standard library net.mq.md directly.
         The HTTP leaf here constructs a result record; its name does not imply an implemented HTTP client.
        +绑定服务端运输使用 websocket.route;中文入口是[实时绑定](实时.mq.md),它与一次客户端 exchange 的生命周期不同。
         
         URL encoding is pure and needs no plugin. This command is ready to run from the repository root:
         
        diff --git a/ext/net/websocket.mq.md b/ext/net/websocket.mq.md
        index 413058f..d8790a2 100644
        --- a/ext/net/websocket.mq.md
        +++ b/ext/net/websocket.mq.md
        @@ -26,6 +26,28 @@ We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="
           We **[End this run with the selected exit status](sys.exit(code=1))**.
         Return *None*.
         
        +## route
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| app | any | required | Prepared application returned by web.prepare |
        +| path | text | required | Declared WebSocket path, including optional path captures |
        +| mode | text | "echo" | echo, drain, broadcast or room |
        +| room_key | text | "" | Room template required by room mode |
        +| presence | bool | False | Publish native room presence messages |
        +| require_auth | any | None | None keeps private broadcast/room defaults; False explicitly opens a local demo |
        +| on_message | text | "" | Optional declared Marqdo callback member |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Updated app with this explicitly declared WebSocket route |
        +
        +Use `app`, `path`, `mode`="echo", `room_key`="", `presence`=False, `require_auth`=None and `on_message`="" to bind a server transport before web.listen. This function belongs to the network resource; it does not change Document layout or start a socket. Retain the returned app because native resource updates produce a new value. Room mode requires a room_key template; captures such as {id} select the room at request time. Broadcast and room routes require login unless the caller explicitly opts out. Public local demos should say why require_auth=False is intentional. Presence and callbacks retain the native transport's bounded message handling; they are not a client subscription object.
        +
        +We **[Load the native transport implementation](_load())**.
        +Return *[Register this declared WebSocket transport](web_app_route_ws(app=`app`, path=`path`, echo=None, mode=`mode`, room_key=`room_key`, on_message=`on_message`, presence=`presence`, require_auth=`require_auth`))*.
        +
        +
         # ws
         
         | 参数 | 类型 | 默认 | 说明 |
        diff --git a/ext/net/实时.mq.md b/ext/net/实时.mq.md
        new file mode 100644
        index 0000000..294d43c
        --- /dev/null
        +++ b/ext/net/实时.mq.md
        @@ -0,0 +1,30 @@
        +---
        +markup: occlusion
        +title: 服务端 WebSocket 实时资源
        +import:
        +  socket: ext/net/websocket.mq.md
        +---
        +
        +本文件提供 websocket.mq.md 的路由绑定中文入口。客户端持续连接由浏览器标准库负责,服务器只在准备好的应用上声明运输资源。独立的一次连接/响应测试仍使用英文文件的 ws 与 connect,不把两种生命周期混为一谈。
        +
        +## 绑定
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 应用 | any | 必填 | 准备站点返回并保留其他资源的应用 |
        +| 路径 | text | 必填 | 明确声明的套接字路径,可含路径捕获 |
        +| 模式 | text | "echo" | echo、drain、broadcast 或 room |
        +| 房间键 | text | "" | room 模式的房间模板,例如文档路径捕获 |
        +| 在线通知 | bool | False | 是否发布原生在线人数消息 |
        +| 需要登录 | any | None | None 保留广播/房间私有默认;False 明确公开 |
        +| 消息回调 | text | "" | 可选已声明 Marqdo 回调成员 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| 结果 | map | 附加明确 WebSocket 路由的新应用,尚未监听 |
        +
        +使用`应用`、`路径`、`模式`="echo"、`房间键`=""、`在线通知`=False、`需要登录`=None、`消息回调`=""。授权 plugin,在监听前保留返回的新应用。构造不会连接浏览器、修改 Document 布局或创建后台线程。
        +
        +room 模式需要房间键,模板在实际请求中代入路径捕获。广播与房间默认要求登录;本地回显示例显式 False,只用于回环地址的公开演示。隐藏导航不能保护连接,身份策略仍由服务器执行。回调与消息上限沿用原生运输,连接错误不能当作空的成功回复。
        +
        +绑定完成后返回 *[登记同一个应用的实时运输资源](socket.route(app=`应用`, path=`路径`, mode=`模式`, room_key=`房间键`, presence=`在线通知`, require_auth=`需要登录`, on_message=`消息回调`))*。
        diff --git a/ext/security/auth.mq.md b/ext/security/auth.mq.md
        index 19b0025..46ff7cb 100644
        --- a/ext/security/auth.mq.md
        +++ b/ext/security/auth.mq.md
        @@ -26,6 +26,56 @@ We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="
           We **[End this run with the selected exit status](sys.exit(code=1))**.
         Return *None*.
         
        +## attach
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| app | any | required | Prepared web application |
        +| users | any | required | Credential table or native database-backed user configuration |
        +| session_ttl | number | 3600 | Session lifetime in seconds |
        +| admin_prefix | text | "/admin" | Native administration prefix |
        +| login_path | text | "/login" | Declared login route |
        +| login_redirect | text | "" | Optional successful login destination |
        +| logout_redirect | text | "" | Optional logout destination |
        +| register | bool | False | Explicitly enable user registration |
        +| register_path | text | "/register" | Registration route when enabled |
        +| default_role | text | "user" | Role assigned to a registered user |
        +| session_url | text | "" | Optional session backend URL |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Updated app with native login/session policy |
        +
        +Use `app`, `users`, `session_ttl`=3600, `admin_prefix`="/admin", `login_path`="/login", `login_redirect`="", `logout_redirect`="", `register`=False, `register_path`="/register", `default_role`="user" and `session_url`="" before web.listen. This resource owns the login/session policy, while Endpoint auth metadata and explicit gates decide which requests need a session or role. Retain the returned app; construction does not authenticate a request or start a server. Credential tables in local examples are fixtures; real user stores should contain the hashes produced by hash_password. Registration is off until deliberately enabled. Session lifetime is in seconds, and external session backends require their own connection configuration.
        +
        +We **[Load the native authentication implementation](plugin.load(path=plugin.native_path(name="web")))**.
        +Return *[Bind the selected login and session policy](web_app_auth(app=`app`, users=`users`, session_ttl=`session_ttl`, admin_prefix=`admin_prefix`, login_redirect=`login_redirect`, logout_redirect=`logout_redirect`, login_path=`login_path`, register=`register`, register_path=`register_path`, default_role=`default_role`, session_url=`session_url`))*.
        +
        +
        +## gate
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| app | any | required | Prepared application retaining its actual resources |
        +| path | text | required | Explicit URL path to protect |
        +| roles | any | "admin" | Allowed role CSV or list |
        +| permissions | text | "" | Optional permission CSV; native any-match policy |
        +| match | text | "prefix" | prefix or exact path matching |
        +| on_deny | text | "forbid" | forbid or redirect anonymous requests to login |
        +| exclude | any | None | Explicit path exclusions; native login/logout exclusions remain |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Updated app with a server-enforced gate; no listener starts |
        +
        +Use `app`, `path`, `roles`="admin", `permissions`="", `match`="prefix", `on_deny`="forbid" and `exclude`=None before listening, with plugin permission. Retain the returned app. This security-owned operation protects real requests; hiding a navigation link does not do that. It reuses the existing native gate and does not mutate Document content or invent routes.
        +
        +Prefix matching includes the selected path and its slash descendants. The runtime keeps login and logout available to avoid authentication loops. When permissions are supplied, native permission matching applies instead of the role list; any required permission may match. Redirect applies to anonymous denial, while a signed-in subject without access receives forbidden. Test both direct denied requests and authenticated access, and gate the actual form/API endpoint separately if its data is private.
        +
        +We **[Load the native access-policy implementation](_load())**.
        +Return *[Bind the explicit server access rule](web_app_gate(app=`app`, path=`path`, roles=`roles`, permissions=`permissions`, match=`match`, on_deny=`on_deny`, exclude=`exclude`))*.
        +
        +
         # auth
         
         | 参数 | 类型 | 默认 | 说明 |
        @@ -35,14 +85,14 @@ Return *None*.
         
         | 返回 | 类型 | 说明 |
         |---|---|---|
        -| result | any | Session/auth helper. Constructs a config object; `login` validates against the users table. To gate `/admin` on this app, use `app.auth users=…` instead. |
        +| result | any | Session/auth helper. Constructs a config object; `login` validates against the users table. To bind native login and protect `/admin`, call attach and gate before listening. |
         
         Use `users`, `session_ttl`=3600 as the inputs for this operation.
         
        -Session/auth helper. Constructs a config object; `login` validates against the users table. To gate `/admin` on this app, use `app.auth users=…` instead.
        +Session/auth helper. Constructs a config object; `login` validates against the users table. To bind native login and protect `/admin`, call attach and gate before listening.
         
         We **[Load the native plugin required by this operation](_load())**.
        -Return *[Session/auth helper. Constructs a config object; login validates against the users table. To gate /admin on this app, use app.auth users=… instead.](web_auth_new(users=`users`, session_ttl=`session_ttl`))*.
        +Return *[Session/auth helper. Constructs a config object; login validates against the users table. To bind server login and gates, use this module's attach function before web.listen.](web_auth_new(users=`users`, session_ttl=`session_ttl`))*.
         
         ## login
         
        diff --git a/ext/security/index.mq.md b/ext/security/index.mq.md
        index fa36b07..46c3484 100644
        --- a/ext/security/index.mq.md
        +++ b/ext/security/index.mq.md
        @@ -7,6 +7,9 @@ import:
         
         Use [auth](auth.mq.md) for credential/session operations, [rbac](rbac.mq.md) for role permissions,
         and [OIDC](oidc.mq.md) for attaching an external identity provider to an existing web app.
        +[Tenant selection](tenant.mq.md) supplies explicit request context for scoped data queries;
        +it does not authenticate a subject or prove tenant membership.
        +中文服务工作流使用[鉴权绑定](鉴权.mq.md),与 auth.attach 保持相同策略及默认值。
         Endpoint authorization remains explicit in the web artifact metadata; a script permission check
         does not automatically protect an HTTP route.
         
        diff --git a/ext/security/tenant.mq.md b/ext/security/tenant.mq.md
        new file mode 100644
        index 0000000..4df9786
        --- /dev/null
        +++ b/ext/security/tenant.mq.md
        @@ -0,0 +1,31 @@
        +---
        +markup: occlusion
        +title: Request tenant selection for database-backed web resources
        +import:
        +  plugin: lib/plugin.mq.md
        +---
        +
        +Tenant selection identifies a request context; authentication and membership are separate decisions. Pair this leaf with explicit scoped routes in ext/data/api.mq.md. Use it before listening and retain the returned application after every binding. The implementation reuses the existing native tenant resolver.
        +
        +## attach
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| app | any | required | Prepared application to receive tenant context |
        +| mode | text | "path" | path, subdomain or header |
        +| param | text | "t" | Path capture/query key or header name; use X-Tenant-Id explicitly for header mode |
        +| column | text | "tenant_id" | Database column used by scoped queries |
        +| default_scope | bool | False | Native default scoping for supported database-backed request handlers |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | any | Updated application with native request tenant resolution |
        +
        +Use `app`, `mode`="path", `param`="t", `column`="tenant_id" and `default_scope`=False. Path mode first resolves the named route capture, then its query key, then the documented path segments. Subdomain mode uses the first label of a host with at least three labels. Header mode reads the selected header. The native resolver lowercases and keeps ASCII letters, digits, underscores and hyphens; it is not a general tenant-name codec.
        +
        +Grant plugin and keep the returned application. A later scoped JSON route rejects a missing resolved tenant and adds the tenant-column filter. The default flag applies only to native handlers that support it; ordinary direct database calls do not gain automatic request context. Tenant ids arriving from query parameters, headers or hostnames must be checked against authenticated membership by the application's actual policy.
        +
        +The local two-tenant example intentionally allows anonymous selection to demonstrate filtering. That behavior cannot establish production access isolation between users. No database row is changed and no socket opens in this binding. Develop resolver behavior in the native tenant package, and verify both selected tenants plus a request without a selector.
        +
        +We **native = [Resolve the maintained tenant implementation](plugin.native_path(name="web"))** and **[Load the existing request-context boundary](plugin.load(path=`native`))**.
        +Return *[Attach the explicit request tenant policy](web_app_tenant(app=`app`, mode=`mode`, param=`param`, column=`column`, default_scope=`default_scope`))*.
        diff --git a/ext/security/鉴权.mq.md b/ext/security/鉴权.mq.md
        new file mode 100644
        index 0000000..816a65f
        --- /dev/null
        +++ b/ext/security/鉴权.mq.md
        @@ -0,0 +1,57 @@
        +---
        +markup: occlusion
        +title: 为准备好的应用绑定鉴权
        +import:
        +  auth: ext/security/auth.mq.md
        +---
        +
        +本文件提供 auth.mq.md 的服务端绑定中文入口。凭据验证、会话和路径门禁是不同责任:本入口配置登录会话,业务端点与表单仍需显式访问策略。它不会把隐藏链接当作授权。账户表中的明文密码只适合本地夹具;真实用户应使用英文资源的 hash_password 生成受支持的口令散列,避免记录秘密。
        +
        +## 绑定
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 应用 | any | 必填 | 已准备并按需启用原生后台的应用 |
        +| 用户 | any | 必填 | username、password、role 凭据表,或原生用户库配置 |
        +| 会话时长 | number | 3600 | 会话寿命,单位为秒 |
        +| 后台前缀 | text | "/admin" | 启用原生后台时安装默认门禁的路径前缀 |
        +| 登录路径 | text | "/login" | 实际 GET 与 POST 登录地址 |
        +| 登录返回 | text | "" | 成功登录后的可选目标 |
        +| 退出返回 | text | "" | 退出后的可选目标 |
        +| 注册 | bool | False | 明确启用用户注册;默认关闭 |
        +| 注册路径 | text | "/register" | 启用注册后的系统地址 |
        +| 默认角色 | text | "user" | 新注册用户的角色 |
        +| 会话地址 | text | "" | 可选外部会话存储 URI |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| 结果 | map | 保留原有资源、附加登录和会话策略的新应用 |
        +
        +使用`应用`、`用户`、`会话时长`=3600、`后台前缀`="/admin"、`登录路径`="/login"、`登录返回`=""、`退出返回`=""、`注册`=False、`注册路径`="/register"、`默认角色`="user"及`会话地址`=""。在监听前授权 plugin 并保留新应用。这里不认证某一次请求,也不启动监听。
        +
        +原生后台应先启用再绑定鉴权,业务接口的 Endpoint 元数据或显式门禁继续决定所需的身份和角色。注册必须明确启用,外部会话后端另需可用连接。配置成功不能替代拒绝与接受凭据的真实验收;用户数据与口令不要写入检视结果或日志。
        +
        +绑定完成后返回 *[配置原生登录与会话策略](auth.attach(app=`应用`, users=`用户`, session_ttl=`会话时长`, admin_prefix=`后台前缀`, login_path=`登录路径`, login_redirect=`登录返回`, logout_redirect=`退出返回`, register=`注册`, register_path=`注册路径`, default_role=`默认角色`, session_url=`会话地址`))*。
        +
        +
        +## 门禁
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 应用 | any | 必填 | 已准备且保留实际资源的应用 |
        +| 路径 | text | 必填 | 需实际保护的服务器路径 |
        +| 角色 | any | "admin" | 允许的角色逗号文本或列表 |
        +| 权限 | text | "" | 可选权限逗号文本,沿用原生任一匹配 |
        +| 匹配 | text | "prefix" | prefix 前缀或 exact 精确匹配 |
        +| 拒绝 | text | "forbid" | forbid 禁止或 redirect 让匿名访问转登录 |
        +| 排除 | any | None | 可选路径排除;原生登录和退出仍保持可用 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | 附加实际服务器访问策略的新应用,尚未监听 |
        +
        +使用`应用`、`路径`、`角色`="admin"、`权限`=""、`匹配`="prefix"、`拒绝`="forbid"及`排除`=None,在监听前授权 plugin 并保留返回值。本安全资源保护实际请求,不因导航隐藏链接就认定地址安全。前缀覆盖本路径及其斜杠子路径,登录和退出按原生规则排除,避免鉴权循环。
        +
        +给出权限时采用原生权限匹配,而不是角色清单;任一所需权限命中即可。redirect 只让匿名拒绝转向登录,已登录但不足权限仍收到禁止。表单与 API 还应按实际数据策略保护自己的提交路径;不能只给展示页面加门禁就宣称所有写入已私有化。
        +
        +绑定完成后返回 *[将明确的访问规则交给安全资源](auth.gate(app=`应用`, path=`路径`, roles=`角色`, permissions=`权限`, match=`匹配`, on_deny=`拒绝`, exclude=`排除`))*。
        diff --git a/ext/web/client/index.mq.md b/ext/web/client/index.mq.md
        index 0a4ae3e..bdc1838 100644
        --- a/ext/web/client/index.mq.md
        +++ b/ext/web/client/index.mq.md
        @@ -5,6 +5,8 @@ description: Browser Runtime helpers (WASM bridge). Prefer lib/browser for effec
         import:
           cap: ext/web/_capability/index.mq.md
           table: lib/table.mq.md
        +  component: ext/web/component/index.mq.md
        +  html: lib/html.mq.md
         ---
         
         Browser helpers describe the official Marqdo WASM bridge and small effects.
        @@ -44,6 +46,7 @@ HTML snippet that loads the official browser Marqdo bridge (route C/D). Defaults
         `source`="", `boot`=True . With boot and non-empty source, auto-mounts. No author
         JS. Not a substitute for file-partitioned Document layout.
         
        +We **bridge = [Escape the bridge URL as an attribute value](html.escape(text=`bridge`))** and **wasm = [Escape the WASM URL as an attribute value](html.escape(text=`wasm`))** and **source = [Escape the client source URL as an attribute value](html.escape(text=`source`))**.
         1. `boot`
             1. `source` != ""
                 Return *""*.
        @@ -101,3 +104,30 @@ We retain **`spec` = [Set the html field in the new record](table.put(in=None, a
           **_ = 1**
         We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`spec`))**.
         Return *[Set the dom field in the new record](table.put(in=None, at="dom", value=`m`))*.
        +
        +## nodes
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| bridge | text | "/static/marqdo-bridge.js" | URL of the official browser bridge |
        +| wasm | text | "/static/marqdo_wasm.wasm" | URL of the built WASM artifact |
        +| source | text | "" | Optional Marqdo client program URL |
        +| boot | bool | True | Whether the bridge automatically mounts the client |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | list | Structured script Resource rows for a component Document |
        +
        +Use `bridge`="/static/marqdo-bridge.js", `wasm`="/static/marqdo_wasm.wasm", `source`="" and `boot`=True in a component tree. The resource references the official bridge as a module and retains the WASM and source addresses as typed attributes. Boot with a nonempty source mounts that Marqdo program; boot=False declares the bridge without automatic mounting. This pure tool creates no server, downloads nothing and writes no JavaScript or HTML. Build the current WASM artifact and mount the actual static directory before serving the page. Prefer these rows to embed when a Document already returns View nodes; embed remains a compatibility string adapter.
        +
        +`attributes` =
        +
        +| type | data-mq-wasm |
        +|---|---|
        +| module | `wasm` |
        +
        +1. `boot` and `source` != ""
        +  We **attributes = [Declare the client program to mount](table.put(in=`attributes`, at="data-mq-source-url", value=`source`))**.
        +1. not `boot`
        +  We **attributes = [Keep automatic mounting disabled](table.put(in=`attributes`, at="data-mq-no-boot", value="1"))**.
        +Return *[Declare the official bridge as a structured resource](component.asset(url=`bridge`, attrs=`attributes`, slot="marqdo-runtime"))*.
        diff --git a/ext/web/component/index.mq.md b/ext/web/component/index.mq.md
        index 347dc55..ee062cd 100644
        --- a/ext/web/component/index.mq.md
        +++ b/ext/web/component/index.mq.md
        @@ -103,15 +103,16 @@ Return *nodes*.
         | kind | text | "column" | Container kind |
         | slot | text | "" | Stable region name |
         | style | text | "" | Optional class name |
        +| attrs | any | None | Attribute record for the container, such as id or hidden |
         
         | 返回 | 类型 | 说明 |
         |------|------|------|
         | result | list | One parent containing its child rows |
         
        -Use `children`, `kind`="column", `slot`="", `style`="" as the inputs for this operation.
        +Use `children`, `kind`="column", `slot`="", `style`="", `attrs`=None as the inputs for this operation.
         
         Wrap `children` in one structural row. Default `kind`="column", `slot`=""
        -and `style`="" . Use row or column for geometry, nav/header/footer/section/aside
        +and `style`="" . Use row or column for geometry, nav/header/footer/section/aside; form/list/item/select preserve native controls
         for a semantic region. The value cell holds the child list itself, not rendered
         HTML. The native renderer diagnoses unknown child shapes at the render boundary;
         this pure constructor does not claim to validate a full site.
        @@ -120,6 +121,104 @@ this pure constructor does not claim to validate a full site.
         
         | @ | type | slot | value | attrs | style |
         |---|------|------|-------|-------|-------|
        -| 1 | `kind` | `slot` | `children` | "" | `style` |
        +| 1 | `kind` | `slot` | `children` | `attrs` | `style` |
         
         Return *nodes*.
        +
        +## element
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| kind | text | required | Native leaf kind: input, button, textarea, label, pre, option, text or link |
        +| value | text | "" | Plain control text or initial input value |
        +| attrs | any | None | Typed attribute record; legacy text href also works for links |
        +| slot | text | "" | Stable layout slot |
        +| style | text | "" | Optional CSS class names |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | list | One leaf in the existing five-column View schema |
        +
        +Use `kind`, `value`="", `attrs`=None, `slot`="" and `style`="" when Markdown cannot express a native input or client event target. Supply ids and field names as a record, boolean flags as booleans, and labels as plain text. The renderer escapes values and attribute content; value is never interpreted as HTML. For forms, lists and semantic regions, use wrap with child rows. The constructor is pure; supported kinds, scalar attribute values and forbidden event/style attributes are checked when rendering. Client state belongs in data/aria attributes, while style names reference the page's stylesheet. This keeps controls inspectable without embedding a complete page as HTML.
        +
        +`nodes` =
        +
        +| @ | type | slot | value | attrs | style |
        +|---|---|---|---|---|---|
        +| 1 | `kind` | `slot` | `value` | `attrs` | `style` |
        +
        +After describing this control we return *nodes*.
        +
        +
        +
        +## asset
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| url | text | required | Explicit script or stylesheet URL served by the application |
        +| kind | text | "script" | script or stylesheet |
        +| attrs | any | None | Typed attributes such as module type, integrity or data-mq options |
        +| slot | text | "" | Optional stable resource slot |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | list | One structured resource leaf in the same five-column View schema |
        +
        +Use `url`, `kind`="script", `attrs`=None and `slot`="" for an existing resource that the browser must load. A script leaf carries only a URL, never inline author JavaScript; a stylesheet leaf references a separate CSS artifact. Its address stays in value, while attrs holds scalar metadata. The native renderer escapes the URL and attributes, forbids duplicate src/href/rel attributes and rejects script-protocol URLs. Construction is pure and fetches nothing. Keep resource declarations beside the Document component that needs them, after layout and content have been split. The browser loads the actual files when that Document is opened; a node record is not proof that the resource exists.
        +
        +`nodes` =
        +
        +| @ | type | slot | value | attrs | style |
        +|---|---|---|---|---|---|
        +| 1 | `kind` | `slot` | `url` | `attrs` | "" |
        +
        +After declaring this resource we return *nodes*.
        +
        +
        +
        +## resource
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| value | map | required | Typed data_query, form_ref, view_navigation or pure document_head Resource |
        +| slot | text | "" | Stable component slot for this dynamic region |
        +| style | text | "" | Optional wrapper class names |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | list | One resource node in the existing five-column View schema |
        +
        +Use `value`, `slot`="" and `style`="" to place a resource supplied by its responsible module. Database query resources come from ext/data/view.mq.md; form references from ext/data/form.mq.md; navigation uses the helper below; pure head declarations come from ext/web/head.mq.md. The resource remains a typed value in the value cell, preserving readable composition and its actual input contract.
        +
        +Construction is pure and does not query data, load a plugin or submit a form. Serving resolves the resource after preparing request parameters, session state and CSRF. Unknown resources fail before listening; missing runtime resources remain request errors. Offline rendering without a request resolver reports missing context for query, form and session navigation. Pure document_head resources are supported by offline preview and collected into the actual head, never shown as body content.
        +
        +`nodes` =
        +
        +| @ | type | slot | value | attrs | style |
        +|---|---|---|---|---|---|
        +| 1 | resource | `slot` | `value` | None | `style` |
        +
        +Return *nodes* for the parent layout to place alongside static Markdown and controls.
        +
        +## navigation
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| items | any | required | Link records with label, href and optional when, class or media |
        +| region | text | "nav" | nav, sidebar or footer |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Pure navigation Resource, to be placed with component.resource |
        +
        +Use `items` and `region`="nav" for session-aware link presentation. Link rows describe destinations; when=guest or auth uses the request's actual session. Empty conditions keep links visible. The native navigation renderer retains its existing classes and conditional visibility, while the recursive parent component still owns placement and geometry.
        +
        +This constructor does not authenticate a user or register a route. Hiding a link cannot protect its destination from direct access. The server must separately attach actual authentication and authorization gates. Reading or constructing navigation never logs in or out; that behavior belongs to the destination's explicit resource and route.
        +
        +`resource` =
        +
        +| _type | items | region |
        +|---|---|---|
        +| view_navigation | `items` | `region` |
        +
        +Return *resource* for explicit placement in the same five-column View.
        diff --git a/ext/web/head.mq.md b/ext/web/head.mq.md
        new file mode 100644
        index 0000000..5968bbf
        --- /dev/null
        +++ b/ext/web/head.mq.md
        @@ -0,0 +1,37 @@
        +---
        +markup: occlusion
        +title: Document head Resource — SEO, fonts and resource links
        +---
        +
        +Use this single-file resource inside the existing five-column View schema. It preserves metadata and native head links when a structured Document owns the page body. Place its returned value through component.resource alongside the layout. The renderer collects it into the actual head, leaving no visible placeholder in body or fragment responses. No new Markdown mark, frontmatter dialect or page mutation chain is involved.
        +
        +Construction is pure. Rendering validates the closed contract, escapes metadata and uses the same head-link renderer as ordinary Documents. It does not fetch a font, execute a script or prove an external resource exists. Browsers load the declared URLs only when they open the real page. A local pure construction example is ready from the checkout:
        +
        +```sh
        +marqdo call ext/web/head.mq.md resource 'meta=[{"key":"description","value":"A readable site"}]' --json
        +```
        +
        +## resource
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| meta | any | None | key/value records or a GFM column table; scalar SEO values |
        +| links | any | None | Native rel/href link records, including optional type, media, crossorigin, defer and async |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Pure document_head descriptor for component.resource; no IO |
        +
        +Use `meta`=None and `links`=None to declare only what this Document needs. Metadata includes description, og: names and other native SEO names. Native title overrides and canonical/icon link keys retain ordinary Document behavior. Charset, viewport and csrf-token remain owned by the runtime and cannot be redeclared here. An empty descriptor contributes no metadata rather than fabricating a page result.
        +
        +Links reuse the existing native field aliases, with rel selecting stylesheet, preconnect, preload, icon, script or module behavior. URLs must start with / for site resources or use http(s); protocol-relative URLs, active data schemes and malformed cells fail. Use the official client nodes for the browser bridge rather than inlining business JavaScript. A link does not mount a file or register a server route.
        +
        +Nested layout modules can contribute head resources. Equal link declarations are deduplicated; conflicting values for the same metadata key are diagnostics rather than silently replacing each other. Fragments omit these declarations because they update an existing Document, while offline preview supports this pure resource without inventing a request session. Request-dependent data, form and navigation resources still require their actual request renderer.
        +
        +`head` =
        +
        +| _type | meta | links |
        +|---|---|---|
        +| document_head | `meta` | `links` |
        +
        +After describing the actual metadata and resource addresses, return *head* for explicit placement by the parent component.
        diff --git a/ext/web/index.mq.md b/ext/web/index.mq.md
        index a32fb09..8bec5cb 100644
        --- a/ext/web/index.mq.md
        +++ b/ext/web/index.mq.md
        @@ -70,9 +70,8 @@ uses the same representation and renderer. Preview from the repo root, then
         change into the site directory to start the process:
         
         ```text
        -marqdo run examples/web-layout-handbook/preview.mq.md
        -cd examples/web-layout-handbook
        -marqdo run serve.mq.md
        +marqdo call examples/web-layout-handbook/preview.mq.md main --effects plugin,fs.read,output.write --fs-root examples/web-layout-handbook --json
        +marqdo call ext/web/web.mq.md serve 'root="examples/web-layout-handbook"' --effects plugin,fs.read,network.write --fs-root examples/web-layout-handbook --json
         ```
         
         Check /, /about and /api/ping. The first is a genuinely nested layout, the second
        @@ -117,7 +116,7 @@ Document, Endpoint and lifecycle boundaries
         
         Ordinary Documents declare type: web, route and title around Markdown body,
         retaining the existing Markdown/data-source path. A composed Document also
        -declares view: main: its # main returns View rows. serve executes that assembly
        +declares view: main: its ordinary main function returns View rows. serve executes that assembly
         once at startup and uses the same renderer as offline preview. Restart after
         content changes. Automatic data_source binding uses ordinary Documents and
         cannot be mixed with startup assembly. Assembly returns structure; it must not render again or launch
        @@ -125,9 +124,17 @@ a server. Request-time interaction belongs in Endpoints with type, path, method,
         request and response metadata. Startup assembly is not an automatic request-time
         template/data-binding system.
         
        -serve is a blocking lifecycle operation for a launcher run with marqdo run.
        -call is for pure construction, previews and inspection; --effects plugin does
        -not grant network or filesystem writes, so call serve is not a launch workflow.
        +serve is a blocking lifecycle operation callable with marqdo call. Grant
        +plugin,fs.read,network.write for a site that reads Markdown and listens. For
        +additional resources, compose web.prepare, resource-owned bindings and
        +web.listen in an ordinary callable launcher. Keep each returned app value.
        +For current database rows, forms and session-aware navigation, place the typed resources from
        +ext/data and component.navigation inside the same View tree. Pure document_head resources
        +preserve SEO and font links in previews as well as responses; they never become body content.
        +See [the request-resource design](../../doc/design/web-view-resources.md) and the real
        +[network site](../../examples/web-net-site/index.mq.md).
        +The network library owns WebSocket routes; the security library owns login
        +and session policy. Preparing a site opens no listener.
         inspect with root scans disk declarations without listening; an empty app in a
         fresh process cannot inspect another process's private state.
         
        @@ -142,7 +149,8 @@ Open the module for the next responsibility
         [page](page/index.mq.md) supplies handles and offline render;
         [route](route/index.mq.md) is for explicit advanced registration, while whole
         sites normally use Metadata. [dom](dom/index.mq.md) converts content, retaining
        -raw HTML only at a compatibility boundary. [client](client/index.mq.md) loads
        +raw HTML only at a compatibility boundary. [head](head.mq.md) contributes pure SEO/font/resource declarations to the real document head;
        +[client](client/index.mq.md) loads
         the official Marqdo WASM bridge; business effects stay in lib/browser.
         [_capability](_capability/index.mq.md) diagnoses loading. The [facade](web.mq.md)
         keeps serve/render/inspect and the app API. Data, auth and HTTP clients belong
        @@ -159,9 +167,8 @@ Update src/ext_cli.rs if adding package files. Preserve ordinary Documents and
         Endpoints when changing startup assembly.
         
         ```text
        -cargo test --locked --test web_handbook
        -cargo test --locked --test call_cli web_
        -cargo test --locked --test gold ext_web -- --test-threads=1
        +marqdo call skills/marqdo-dev/index.mq.md test 'targets=["web_handbook"]' --effects plugin,process.exec --require-ok --json
        +marqdo call skills/marqdo-dev/index.mq.md test 'targets=["call_cli","gold"]' 'filter="web"' --effects plugin,process.exec --require-ok --json
         ```
         
         Handbook tests execute the bilingual sh fences and author examples directly,
        @@ -194,7 +201,7 @@ The returned rows are a planning aid, not a generated site or a validation certi
         | step_C | declare home Document and view main for composed structure |
         | step_D | declare more Documents with their own routes |
         | step_E | declare Endpoint handlers for request-time work |
        -| step_F | run serve.mq.md from the site directory |
        +| step_F | call the blocking serve function with explicit site root and effects |
         | step_G | compare preview and live output; test routes and browser geometry |
         | stopping_rule | one Markdown responsibility and no internal layout |
         
        diff --git a/ext/web/web.mq.md b/ext/web/web.mq.md
        index 1a2605b..d759d9e 100644
        --- a/ext/web/web.mq.md
        +++ b/ext/web/web.mq.md
        @@ -25,8 +25,8 @@ marqdo call ext/web/web.mq.md inspect 'root="examples/web-layout-handbook"' --ef
         
         inspect with root scans declared metadata without starting a server. To inspect
         an in-memory app, pass its actual handle; an empty fresh process cannot inspect
        -another process. serve is a blocking lifecycle operation: write a launcher and
        -use marqdo run, not call. Explicit view: main Documents assemble once at startup
        +another process. serve is a blocking lifecycle operation. Call it directly with explicit effects,
        +or compose prepare, resource bindings and listen in an ordinary callable launcher. Explicit view: main Documents assemble once at startup
         through normal functions and imports. Restart after changing their content.
         
         Develop layout structure in layout/component and the Go artifact renderer;
        @@ -149,23 +149,21 @@ Return *[Attach first-class middleware to app](web_app_use(app=`app`, middleware
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| app | any | None | app or None |
        -| root | text | "" | Site directory to inspect without listening |
        +| app | any | None | Current prepared application after all explicit Resource bindings |
        +| root | text | "" | Optional metadata-only scan directory; takes precedence over app |
         
         | 返回 | 类型 | 说明 |
        -|------|------|------|
        -| result | any | {declared, system} |
        +|---|---|---|
        +| result | map | scope, declared and system; registered reports actual configured handlers, metadata reports file declarations and runtime templates |
         
        -Use `app`=None, `root`="" as the inputs for this operation.
        +Use `app`=None and `root`="" deliberately. After prepare and Resource bindings, pass the retained app before listen to inspect its current routes. The registrar is shared with the actual HTTP server, so later WebSocket, JSON query, form, login, administration and static bindings appear without using a stale startup snapshot. Duplicate or conflicting registrations retain their native diagnostic.
         
        -Return declared versus system route tables for introspection. System routes such
        -as /_part and /_form must appear here. Use this to verify a site after serve or
        -manual registration. Optional `app`=None selects which application to inspect.
        +Supplying root scans Artifact metadata only. It does not execute the launcher or Documents, so it cannot observe Resource bindings performed by those functions. scope=metadata makes that limitation explicit; scope=registered reports the handler registrations of the supplied app. Neither scope proves that a server is listening, a database is available or authentication succeeds.
         
        -Optional `root`="" scans a site directory when supplied; it does not start a server.
        +The operation needs plugin. It does not invoke request handlers, create sessions, reset runtime state, open a database or start a listener. Credentials and unrelated app fields are not returned. System routes include the actual configured parameterized form/part paths and session paths; declared routes retain their source identity when available.
         
        -We **[Load the native plugin required by this operation](cap.load())**.
        -Return *[Return declared versus system route tables for introspection](web_inspect(app=`app`, root=`root`))*.
        +We **[Load the maintained native inspection boundary](cap.load())**.
        +Return *[Observe the current declarations and registered runtime handlers](web_inspect(app=`app`, root=`root`))*.
         
         ## serve
         
        @@ -191,7 +189,7 @@ simple). Optional `db`=None, `static_dir`="", and `middleware`=None bind
         resources without stuffing them into this facade as author APIs.
         
         We **[Load the native plugin required by this operation](cap.load())**.
        -Return *[Scan root="](web_serve_root(root=`root`, host=`host`, port=`port`, db=`db`, static_dir=`static_dir`, middleware=`middleware`))*.
        +Return *[Discover the site and listen on its configured address](web_serve_root(root=`root`, host=`host`, port=`port`, db=`db`, static_dir=`static_dir`, middleware=`middleware`))*.
         
         ## client_embed
         
        @@ -318,6 +316,43 @@ head needs as data rather than injecting opaque HTML head strings.
         We **[Load the native plugin required by this operation](cap.load())**.
         Return *[Build head resource rows (link, script, icon) from a table. Prefer declaring head needs as data rather than injecting opaque HTML head strings.](web_head(table=`table`))*.
         
        +## prepare
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| root | text | "." | Site directory containing declared Documents and Endpoints |
        +| host | text | "127.0.0.1" | Explicit listen address retained for later listen |
        +| port | number | 18081 | Port retained for later listen |
        +| db | any | None | Existing database Resource or None |
        +| static_dir | text | "" | Optional static directory resolved under the site |
        +| middleware | any | None | Optional security header table |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Prepared app resource; no socket is opened |
        +
        +Use `root`=".", `host`="127.0.0.1", `port`=18081, `db`=None, `static_dir`="" and `middleware`=None to discover the same Documents and Endpoints as serve. Startup View assembly runs once here. Bind additional resources to the returned app, retaining each returned app value, before calling listen. The original absolute site root travels with the app so relative endpoint callbacks and static files keep their site context. This is a lifecycle boundary, not an alternative routing language. Reading metadata or evaluating a Document can fail before any listener starts.
        +
        +We **[Load the existing native web implementation](cap.load())**.
        +Return *[Discover routes without starting a listener](web_prepare_root(root=`root`, host=`host`, port=`port`, db=`db`, static_dir=`static_dir`, middleware=`middleware`))*.
        +
        +
        +## listen
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| app | any | required | Prepared app after explicit resource bindings |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Blocking native listener result |
        +
        +Use `app` after prepare and the resource-owned binding functions. This call opens the configured host and port and blocks for the server lifetime. It works in an ordinary callable launcher reached by marqdo call; grant plugin, filesystem and network effects required by that launcher. Returning a resource description does not start the server. A separate terminal or supervised test process owns shutdown; call does not turn this listener into a background daemon. Relative paths use the site root retained by prepare.
        +
        +We **[Load the existing native web implementation](cap.load())**.
        +Return *[Serve the prepared site with its bound resources](web_listen(app=`app`))*.
        +
        +
         # app
         
         | 参数 | 类型 | 默认 | 说明 |
        diff --git a/ext/web/网页.mq.md b/ext/web/网页.mq.md
        index d7de8fb..a345e64 100644
        --- a/ext/web/网页.mq.md
        +++ b/ext/web/网页.mq.md
        @@ -19,7 +19,7 @@ marqdo call ext/web/网页.mq.md 检视 '根="examples/web-layout-handbook"' --e
         ```
         
         页面结构用五列 View 记录,父值保留子表。纯布局、DOM 构造和客户端描述无需插件。
        -整站服务通过 launcher 的 marqdo run 启动;检视磁盘站点请给出根目录,不能从新进程
        +整站服务可通过 marqdo call 直接调用服务函数,也可在普通启动函数中组合准备、资源绑定与监听;检视磁盘站点请给出根目录,不能从新进程
         读取另一个进程的私有应用。结构化 Document 使用 视图: main,在启动时执行布局装配。
         
         开发时先复用组件和布局模块,再改对应领域实现;保持中英入口与真实契约一致。
        @@ -131,20 +131,20 @@ Artifact,由 `服务` 发现;本工具供预览或程序化构造。节点
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| 应用 | any | None | 应用或 None |
        -| 根 | text | "" | 离线扫描的站点目录 |
        +| 应用 | any | None | 完成显式资源绑定后保留的当前应用 |
        +| 根 | text | "" | 可选的元数据扫描目录;给出时优先于应用 |
         
         | 返回 | 类型 | 说明 |
        -|------|------|------|
        -| result | any | 路由检视 |
        +|---|---|---|
        +| 结果 | map | scope、declared 与 system;区分文件声明和当前应用的实际处理器注册 |
         
        -这里使用`应用`=None、`根`=""。
        +使用`应用`=None、`根`="",应明确选择观察范围。准备应用并绑定资源后,把保留的应用交给检视,再开始监听。清单复用真实服务的路由注册流程,后加的 WebSocket、JSON 查询、表单、登录、后台和静态挂载都会出现,不读取已经过期的启动快照;冲突注册保留原生诊断。
         
        -返回 `{declared, system}` 路由表;可选 `应用`=None。
        +给出根目录时只扫描 Artifact 元数据,不执行启动函数或页面,因此不能观察这些函数运行后才绑定的资源。scope 为 metadata 表示文件声明与运行时模板,为 registered 表示传入应用的实际处理器注册。它们都不能证明已经监听、数据库可用或登录成功。
         
        -可选 `根`="",给出时扫描站点目录,不启动服务器。
        +需要 plugin。此操作不调用请求处理器、不创建或重置会话、不打开数据库、不启动监听,也不返回凭据和无关应用字段。系统清单包含实际配置的表单、片段及会话路径;已有来源信息的声明仍保留文件身份,便于继续阅读实现。
         
        -完成后返回*[调用 inspect](web.inspect(app=`应用`, root=`根`))*。
        +完成后返回 *[观察当前声明及运行时注册](web.inspect(app=`应用`, root=`根`))*。
         
         ## 服务
         
        @@ -189,3 +189,56 @@ Artifact,由 `服务` 发现;本工具供预览或程序化构造。节点
         `源`=""、`启动`=True。不是用 HTML 字符串拼整页的借口。
         
         完成后返回*[调用 client embed](web.client_embed(bridge=`桥`, wasm=`wasm`, source=`源`, boot=`启动`))*。
        +
        +## 准备站点
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 根 | text | "." | 含网页与端点声明的站点目录 |
        +| 主机 | text | "127.0.0.1" | 监听地址;准备阶段不开启端口 |
        +| 端口 | number | 18081 | 交给稍后监听阶段使用的端口 |
        +| 数据库 | any | None | 已有数据库资源 |
        +| 静态目录 | text | "" | 站点内的可选静态资源目录 |
        +| 中间件 | any | None | 可选安全响应头表 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | 已发现路由并完成启动布局装配的应用资源 |
        +
        +这里使用`根`="."、`主机`="127.0.0.1"、`端口`=18081、`数据库`=None、`静态目录`=""和`中间件`=None。准备阶段发现 Document 与 Endpoint,执行一次启动布局,但不启动监听。随后把应用交给网络、鉴权等资源的绑定函数,并保留每次返回的新应用,最后调用监听。原始站点的绝对根目录随应用保留,因此端点回调和静态资源的相对路径仍按站点解析。目录读取和布局执行可能在打开端口之前失败,应保留原始诊断。
        +
        +完成准备后返回*[发现站点并保留其资源上下文](web.prepare(root=`根`, host=`主机`, port=`端口`, db=`数据库`, static_dir=`静态目录`, middleware=`中间件`))*.
        +
        +
        +## 监听
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 应用 | any | 必填 | 准备站点后已完成资源绑定的应用 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | 阻塞的原生监听结果 |
        +
        +输入`应用`后才启动已配置的主机和端口。可以在普通可调用启动函数中按顺序准备站点、绑定资源、监听,再通过 marqdo call 执行该函数。监听持续占用当前进程,由调用者或测试监督进程负责停止。显式授予启动流程所需的插件、文件读取与网络写入权限;返回一个应用描述本身不会启动后台服务。
        +
        +最后返回*[在保留的站点根目录中启动服务](web.listen(app=`应用`))*.
        +
        +
        +
        +## 编译样式
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 名称 | text | 必填 | 原生类选择器名,可含后代选择器尾部 |
        +| 属性 | any | 必填 | 属性、值两列的声明式主题表 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| 结果 | text | 原生样式编译器输出的 CSS 文本 |
        +
        +使用`名称`与`属性`,授权 plugin。该入口对应英文 make_style,把可读属性表交给已有原生编译器;不接收整页 HTML,也不创造另一套布局语言。名称应由作者控制,对应 View 的样式类与原生内容结构。返回文本不会自动写入或挂载文件,调用者需显式选择生成路径并以原生文件能力保存。
        +
        +纯属性构造不需要插件,真正编译才在这里加载原生实现。属性值的格式或选择器错误保留真实诊断,不能替换为旧产物继续声称已构建。动态业务数据不应该用来拼接选择器;测试应比较实际编译结果并查看对应区域的渲染效果。
        +
        +完成编译后返回 *[使用已有主题编译器处理声明](web.make_style(name=`名称`, table=`属性`))*。
        diff --git a/ext/web/网页/客户端/索引.mq.md b/ext/web/网页/客户端/索引.mq.md
        index 7e8ca05..9cbe645 100644
        --- a/ext/web/网页/客户端/索引.mq.md
        +++ b/ext/web/网页/客户端/索引.mq.md
        @@ -16,7 +16,7 @@ marqdo call ext/web/网页/客户端/索引.mq.md 文本补丁 '选择器="#stat
         ```
         
         页面结构用五列 View 记录,父值保留子表。纯布局、DOM 构造和客户端描述无需插件。
        -整站服务通过 launcher 的 marqdo run 启动;检视磁盘站点请给出根目录,不能从新进程
        +整站服务通过网页.服务或工程入口的 serve 函数用 marqdo call 启动;检视磁盘站点请给出根目录,不能从新进程
         读取另一个进程的私有应用。结构化 Document 使用 视图: main,在启动时执行布局装配。
         
         开发时先复用组件和布局模块,再改对应领域实现;保持中英入口与真实契约一致。
        @@ -79,3 +79,20 @@ marqdo call ext/web/网页/客户端/索引.mq.md 文本补丁 '选择器="#stat
         为选择器 `选择器` 构造 `dom` 效果表。可选 `html`=""、`属性`=None、`移除`=False。
         
         完成后返回*[调用 dom patch](client.dom_patch(sel=`选择器`, html=`html`, attrs=`属性`, remove=`移除`))*。
        +
        +## 挂载节点
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 桥 | text | "/static/marqdo-bridge.js" | 官方浏览器桥地址 |
        +| wasm | text | "/static/marqdo_wasm.wasm" | 当前构建的 WASM 产物地址 |
        +| 源 | text | "" | 可选客户端 Marqdo 程序地址 |
        +| 启动 | bool | True | 是否自动挂载客户端程序 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | list | 组件 Document 可直接组合的脚本资源节点 |
        +
        +这里使用`桥`="/static/marqdo-bridge.js"、`wasm`="/static/marqdo_wasm.wasm"、`源`=""和`启动`=True。节点引用官方模块资源,把 WASM 和程序地址保留为属性数据。启动关闭时只声明桥,不自动执行客户端。构造无需插件,不访问网络,也不生成业务 HTML;浏览器打开页面后才加载实际文件。应先构建当前 WASM 并挂载静态目录,再把这些节点与内容组件组合。旧的字符串挂载工具保留兼容用途。
        +
        +完成后返回*[将官方运行时作为结构资源声明](client.nodes(bridge=`桥`, wasm=`wasm`, source=`源`, boot=`启动`))*.
        diff --git a/ext/web/网页/文档对象模型/索引.mq.md b/ext/web/网页/文档对象模型/索引.mq.md
        index 98a42d3..857bfd9 100644
        --- a/ext/web/网页/文档对象模型/索引.mq.md
        +++ b/ext/web/网页/文档对象模型/索引.mq.md
        @@ -16,7 +16,7 @@ marqdo call ext/web/网页/文档对象模型/索引.mq.md 渲染 'dom=$body' --
         ```
         
         页面结构用五列 View 记录,父值保留子表。纯布局、DOM 构造和客户端描述无需插件。
        -整站服务通过 launcher 的 marqdo run 启动;检视磁盘站点请给出根目录,不能从新进程
        +整站服务通过网页.服务或工程入口的 serve 函数用 marqdo call 启动;检视磁盘站点请给出根目录,不能从新进程
         读取另一个进程的私有应用。结构化 Document 使用 视图: main,在启动时执行布局装配。
         
         开发时先复用组件和布局模块,再改对应领域实现;保持中英入口与真实契约一致。
        diff --git a/ext/web/网页/索引.mq.md b/ext/web/网页/索引.mq.md
        index 4db3eca..51741de 100644
        --- a/ext/web/网页/索引.mq.md
        +++ b/ext/web/网页/索引.mq.md
        @@ -65,9 +65,8 @@ site/
         先从仓库根生成预览,再从站点目录运行服务:
         
         ```text
        -marqdo run examples/web-layout-handbook-zh/preview.mq.md
        -cd examples/web-layout-handbook-zh
        -marqdo run serve.mq.md
        +marqdo call examples/web-layout-handbook-zh/preview.mq.md main --effects plugin,fs.read,output.write --fs-root examples/web-layout-handbook-zh --json
        +marqdo call ext/web/网页.mq.md 服务 '根="examples/web-layout-handbook-zh"' --effects plugin,fs.read,network.write --fs-root examples/web-layout-handbook-zh --json
         ```
         
         检查 / 首页、/about 普通文档、/api/ping JSON。首页应真的出现父子嵌套与两个页脚区域,
        @@ -106,14 +105,15 @@ markup: occlusion
         Document、Endpoint 与运行边界
         
         普通 Document 用 类型: 网页、路由、标题和 Markdown 正文,保留原来的静态/数据源路径。
        -组件 Document 另外声明 视图: main,其 # main 返回节点列表;服务在启动时执行装配一次,
        +组件 Document 另外声明 视图: main,其普通 main 函数返回节点列表;服务在启动时执行装配一次,
         通过同一渲染器生成 HTML。改内容后重启。自动数据源绑定使用普通 Document,不与此启动装配混用。不要在这个装配函数里再启动服务器或调用渲染;
         它返回结构即可。请求期互动放在 Endpoint,声明 类型: 端点、路径、方法、请求、响应,
         主程序返回响应值。不要把启动时装配误解为自动的请求期模板绑定。
         
        -serve 是长时间运行的生命周期操作,用 launcher 的 marqdo run 启动。
        -call 适合纯构造、离线预览与检视;--effects plugin 不授予网络或文件写入权限,
        -不能把 call 服务当成起站方式。网页检视给出根目录时可离线扫描声明;新进程中的空应用
        +服务是长时间阻塞的生命周期操作,可用 marqdo call 直接调用,并显式授予
        +plugin、fs.read、network.write。需要更多资源时,在普通启动函数中顺序组合准备站点、
        +各资源的绑定工具与监听,并保留每次更新后的应用。网络库负责 WebSocket,安全库负责
        +登录与会话;准备阶段不会打开端口。网页检视给出根目录时可离线扫描声明;新进程中的空应用
         不能检视另一个进程的私有路由状态。
         
         ```sh
        @@ -129,6 +129,7 @@ Markdown 叶子与语义包裹;[页面](页面/索引.mq.md)负责句柄与离
         [客户端](客户端/索引.mq.md)挂载 Marqdo WASM,业务交互继续使用 lib/browser;
         [能力](能力/索引.mq.md)只诊断原生加载。[门面](../网页.mq.md)保留服务、渲染、检视和应用 API。
         数据库、鉴权、HTTP 客户端分别去 ext/data、ext/security、ext/net。
        +[页头资源](../页头.mq.md)保留真实 SEO、字体与资源声明,能用于离线预览;它不会成为正文或片段占位。数据查询、表单引用和会话导航仍在真实请求中解析,继续沿用五列 View。完整中文实践见 [网络站点入口](../../../examples/web-net-site-zh/index.mq.md)。
         
         开发路线与验收
         
        @@ -138,9 +139,9 @@ Markdown 叶子与语义包裹;[页面](页面/索引.mq.md)负责句柄与离
         新增文件时更新 src/ext_cli.rs 安装清单。修改 Document 启动装配要保留普通文档与 API 的行为。
         
         ```text
        -cargo test --locked --test web_handbook
        -cargo test --locked --test call_cli web_
        -cargo test --locked --test gold ext_web -- --test-threads=1
        +marqdo call skills/marqdo-dev/index.mq.md test 'targets=["web_handbook"]' --effects plugin --fs-root . --require-ok --json
        +marqdo call skills/marqdo-dev/index.mq.md test 'targets=["call_cli"]' 'filter="web_"' --effects plugin --fs-root . --require-ok --json
        +marqdo call skills/marqdo-dev/index.mq.md test 'targets=["gold"]' 'filter="ext_web"' --effects plugin --fs-root . --require-ok --json
         ```
         
         手册门禁直接执行本包双语 sh 围栏与作者程序,另外预览并启动参考工程,核对路由、
        diff --git a/ext/web/网页/组件/索引.mq.md b/ext/web/网页/组件/索引.mq.md
        index 63cdd3f..33cda06 100644
        --- a/ext/web/网页/组件/索引.mq.md
        +++ b/ext/web/网页/组件/索引.mq.md
        @@ -16,6 +16,7 @@ import:
         marqdo call ext/web/网页/组件/索引.mq.md 正文 '文本="## 可读的叶子"' '槽="介绍"' --json
         marqdo call ext/web/网页/组件/索引.mq.md 包裹 '子节点=[{"type":"markdown","value":"左"},{"type":"markdown","value":"右"}]' '种类="row"' --json
         marqdo call ext/web/网页/组件/索引.mq.md 合并 '甲=[{"type":"text","value":"前"}]' '乙=[{"type":"text","value":"后"}]' --json
        +marqdo call ext/web/网页/组件/索引.mq.md 资源 '地址="/static/generated/theme.css"' '种类="stylesheet"' --json
         ```
         
         复用组件使用 @ 记录表,合并只确定兄弟顺序,不会自动产生双栏。布局请转到
        @@ -86,15 +87,102 @@ marqdo call ext/web/网页/组件/索引.mq.md 合并 '甲=[{"type":"text","valu
         | 种类 | text | "column" | 容器类型 |
         | 槽 | text | "" | 区域名 |
         | 样式 | text | "" | 可选类名 |
        +| 属性 | any | None | 容器属性记录,例如 id 与 hidden |
         
         | 返回 | 类型 | 说明 |
         |------|------|------|
         | result | list | 包含子节点的父块 |
         
        -这里使用`子节点`、`种类`="column"、`槽`=""、`样式`=""。
        +这里使用`子节点`、`种类`="column"、`槽`=""、`样式`=""、`属性`=None。
         
         将 `子节点` 放进一层父容器,默认 `种类`="column"、`槽`=""、`样式`=""。
         几何类型为 row、column;语义类型包括 nav、header、footer、section、aside。
         值单元格保留子表,不承载拼好的 HTML;构造器只生成结构,实际形状由渲染器检查。
         
        -完成后返回*[调用 wrap](component.wrap(children=`子节点`, kind=`种类`, slot=`槽`, style=`样式`))*。
        +完成后返回*[调用 wrap](component.wrap(children=`子节点`, kind=`种类`, slot=`槽`, style=`样式`, attrs=`属性`))*。
        +
        +## 控件
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 种类 | text | 必填 | input、button、textarea、label、pre、option、text 或 link |
        +| 值 | text | "" | 控件文字或输入框初值 |
        +| 属性 | any | None | id、name、布尔标志等属性记录 |
        +| 槽 | text | "" | 布局区域名 |
        +| 样式 | text | "" | 可选样式类名 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | list | 现有五列 View 结构中的单个控件叶子 |
        +
        +这里使用`种类`、`值`=""、`属性`=None、`槽`=""和`样式`=""。当普通 Markdown 无法表示编辑框或客户端事件目标时,才使用原生控件。属性记录中的 required、hidden 等必须是布尔值;控件文字按文本转义,不解释为 HTML。表单、列表和语义区域仍用包裹函数保存子节点关系。构造器本身是纯函数,实际渲染阶段检查类型与属性;事件处理器和内联样式不能混入属性表。客户端状态可用 data 与 aria 属性,外观通过类名引用站点样式表。
        +
        +完成描述后返回*[构造可检查的原生控件](component.element(kind=`种类`, value=`值`, attrs=`属性`, slot=`槽`, style=`样式`))*.
        +
        +
        +
        +## 资源
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 地址 | text | 必填 | 应用提供的脚本或样式表 URL |
        +| 种类 | text | "script" | script 或 stylesheet |
        +| 属性 | any | None | 模块类型、完整性或 data-mq 等属性记录 |
        +| 槽 | text | "" | 可选资源区域名 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | list | 现有五列 View 结构中的单个资源叶子 |
        +
        +这里使用`地址`、`种类`="script"、`属性`=None、`槽`=""。脚本节点只引用资源地址,不承载内联业务 JavaScript;样式节点引用独立 CSS 文件。地址保留在值列,其余信息保留在属性记录。构造本身不访问网络,也不验证文件存在;原生渲染器负责转义和属性检查,浏览器打开页面后才加载资源。这样运行时桥和主题可以独立组织,不需要把整个页面写成 HTML 字符串。
        +
        +完成后返回*[声明浏览器需要的独立资源](component.asset(url=`地址`, kind=`种类`, attrs=`属性`, slot=`槽`))*.
        +
        +
        +
        +## 请求资源
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 值 | map | 必填 | 数据查询、表单引用、导航或纯页头声明的具型资源 |
        +| 槽 | text | "" | 动态内容区域的稳定名称 |
        +| 样式 | text | "" | 资源外层的可选类名 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| 结果 | list | 五列 View 中的一个资源节点 |
        +
        +使用`值`、`槽`=""与`样式`="",把职责模块提供的资源放进布局。查询来自数据视图模块,表单由表单模块显式挂载,导航由下方工具构造,纯页头来自 ext/web/页头.mq.md。值单元格保留资源本身,父组件不先把子内容渲染成 HTML。
        +
        +构造是纯计算,不查询数据库、不提交表单,也不加载插件。服务器准备请求参数、会话与 CSRF 后才解析资源。未知种类在监听前失败,缺失运行资源保留实际请求诊断。离线渲染不能伪造请求上下文或返回固定成功;纯页头声明可以离线预览,并收集进真正的 head,不作为正文占位。
        +
        +`节点` =
        +
        +| @ | 类型 | 槽 | 值 | 属性 | 样式 |
        +|---|---|---|---|---|---|
        +| 1 | resource | `槽` | `值` | None | `样式` |
        +
        +父布局确定位置后,返回 *节点*,与静态 Markdown 和控件继续组合。
        +
        +## 导航资源
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 项 | any | 必填 | 含 label、href 及可选 when、class、media 的链接记录 |
        +| 区域 | text | "nav" | nav、sidebar 或 footer |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| 结果 | map | 由实际会话决定链接可见性的纯导航资源 |
        +
        +使用`项`与`区域`="nav"声明链接目的地。when 为 guest 或 auth 时根据当前请求会话筛选;空条件始终显示。父组件仍决定布局,原生导航渲染器保留已有类名和条件显示能力,不在作者源码中拼写整段 HTML。
        +
        +隐藏链接不能保护目标地址。鉴权与角色门禁仍须由服务端资源显式绑定,构造导航不注册隐式路由,也不执行登录或退出。把返回值放入资源节点后,监听期间才读取真实会话;离线读取不会伪造某个用户的登录状态。
        +
        +`资源` =
        +
        +| _type | items | region |
        +|---|---|---|
        +| view_navigation | `项` | `区域` |
        +
        +声明完可见性与目的地后,返回 *资源*,交给相同的五列 View 组合。
        diff --git a/ext/web/网页/能力/索引.mq.md b/ext/web/网页/能力/索引.mq.md
        index 8c4c083..b3c44d5 100644
        --- a/ext/web/网页/能力/索引.mq.md
        +++ b/ext/web/网页/能力/索引.mq.md
        @@ -15,7 +15,7 @@ marqdo call ext/web/网页/能力/索引.mq.md 加载 --effects plugin --json
         ```
         
         页面结构用五列 View 记录,父值保留子表。纯布局、DOM 构造和客户端描述无需插件。
        -整站服务通过 launcher 的 marqdo run 启动;检视磁盘站点请给出根目录,不能从新进程
        +整站服务通过网页.服务或工程入口的 serve 函数用 marqdo call 启动;检视磁盘站点请给出根目录,不能从新进程
         读取另一个进程的私有应用。结构化 Document 使用 视图: main,在启动时执行布局装配。
         
         开发时先复用组件和布局模块,再改对应领域实现;保持中英入口与真实契约一致。
        diff --git a/ext/web/网页/路由/索引.mq.md b/ext/web/网页/路由/索引.mq.md
        index 84844c6..4769097 100644
        --- a/ext/web/网页/路由/索引.mq.md
        +++ b/ext/web/网页/路由/索引.mq.md
        @@ -16,7 +16,7 @@ marqdo call ext/web/网页/路由/索引.mq.md 注册 '路由=$route' --effects
         ```
         
         页面结构用五列 View 记录,父值保留子表。纯布局、DOM 构造和客户端描述无需插件。
        -整站服务通过 launcher 的 marqdo run 启动;检视磁盘站点请给出根目录,不能从新进程
        +整站服务通过网页.服务或工程入口的 serve 函数用 marqdo call 启动;检视磁盘站点请给出根目录,不能从新进程
         读取另一个进程的私有应用。结构化 Document 使用 视图: main,在启动时执行布局装配。
         
         开发时先复用组件和布局模块,再改对应领域实现;保持中英入口与真实契约一致。
        diff --git a/ext/web/网页/页面/索引.mq.md b/ext/web/网页/页面/索引.mq.md
        index d33d229..72c60bb 100644
        --- a/ext/web/网页/页面/索引.mq.md
        +++ b/ext/web/网页/页面/索引.mq.md
        @@ -16,7 +16,7 @@ marqdo call ext/web/网页/页面/索引.mq.md 渲染 '页面=$pg' --effects plu
         ```
         
         页面结构用五列 View 记录,父值保留子表。纯布局、DOM 构造和客户端描述无需插件。
        -整站服务通过 launcher 的 marqdo run 启动;检视磁盘站点请给出根目录,不能从新进程
        +整站服务通过网页.服务或工程入口的 serve 函数用 marqdo call 启动;检视磁盘站点请给出根目录,不能从新进程
         读取另一个进程的私有应用。结构化 Document 使用 视图: main,在启动时执行布局装配。
         
         开发时先复用组件和布局模块,再改对应领域实现;保持中英入口与真实契约一致。
        diff --git a/ext/web/页头.mq.md b/ext/web/页头.mq.md
        new file mode 100644
        index 0000000..4166da5
        --- /dev/null
        +++ b/ext/web/页头.mq.md
        @@ -0,0 +1,31 @@
        +---
        +markup: occlusion
        +title: 文档页头资源:SEO、字体与资源链接
        +import:
        +  head: ext/web/head.mq.md
        +---
        +
        +本文件对应 head.mq.md。结构化页面将本资源交给组件的请求资源节点,服务器与离线预览都把它收集到真正的 head,不在正文或片段中留下占位。沿用现有五列 View,不增加新标记、嵌套元数据或页面变异链。
        +
        +```sh
        +marqdo call ext/web/页头.mq.md 声明 '元数据=[{"key":"description","value":"可读的站点"}]' --json
        +```
        +
        +## 声明
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 元数据 | any | None | key/value 行记录或 GFM 列式表,值为原生标量 |
        +| 链接 | any | None | rel/href 原生资源记录,支持媒体、跨域及脚本标志 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| 结果 | map | 供组件安放的纯 document_head 描述 |
        +
        +使用`元数据`=None、`链接`=None,构造不需要任何副作用。元数据保留 description、og: 等 SEO 名称,title、canonical、icon 等沿用普通文档约定;charset、viewport 和 csrf-token 归运行时所有,不在这里重声明。
        +
        +链接复用原生 rel/href 表与中文字段别名,可声明字体预连接、样式、图标或显式脚本资源。地址只允许 / 开头的站内路径与 http(s),不接受活动数据方案或协议相对地址。这里不下载字体、不执行脚本、不挂载静态文件;浏览器打开实际页面后才请求地址。官方桥仍用客户端挂载节点,不在资源里写业务 JavaScript。
        +
        +多个子组件可以贡献资源,相同链接去重,同名元数据有不同值时保留诊断,不静默覆盖。片段不会重复输出页头;离线预览能处理本纯资源,但查询、表单与会话导航仍需真实请求上下文。缺失文件、网络可用性和页面视觉效果须另做实际验证,构造描述不能证明这些条件。
        +
        +声明完成后返回 *[复用同一个文档页头契约](head.resource(meta=`元数据`, links=`链接`))*。
        diff --git a/lib/browser.mq.md b/lib/browser.mq.md
        index 3fcf92d..a4c0c1c 100644
        --- a/lib/browser.mq.md
        +++ b/lib/browser.mq.md
        @@ -702,3 +702,34 @@ Build the download effect record. The browser bridge consumes this record; this
         | `body` | `filename` | `mime` |
         
         Return *[Set the download field in the new record](table.put(in=None, at="download", value=`spec`))*.
        +
        +## render_list
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| sel | text | required | CSS selector of the existing list container |
        +| items | list | required | Literal text or records with tag, text or children, class and attrs |
        +| tag | text | "li" | Element name consumed by the official bridge, normally li |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | Pure render_list instruction for the official browser bridge |
        +
        +Use `sel`, `items` and `tag`="li" to replace one dynamic list while preserving its parent layout. Each record can keep plain text and a data-id attribute for delegated events. The official bridge already supports this effect and escapes ordinary text, so a title containing quotes or angle brackets need not become an HTML string. Constructing this instruction does not update a DOM or prove that the selector exists. Only pass application-owned element names and attribute keys; the underlying bridge also accepts an explicit html escape hatch for specialized integrations. Initial page structure still belongs in the Document's component tree, and incoming business values should remain text records.
        +
        +Records also accept tag and children, a list of the same text/control records. A li can retain a span label beside a button with data-id, so delegated deletion needs no author HTML. Do not combine children with text or html. Nesting is limited to 32 levels and 10000 records; element/attribute names are checked and event attributes or active URL schemes are rejected. Keep business values in text; the existing html field remains an explicit compatibility escape hatch.
        +
        +For a row with a delete action, pass children as structured data. This pure call returns the instruction without loading a server plugin or performing browser IO; the real example uses the same shape in [browser-app](../examples/browser-app/static/app.mq.md). Arbitrary attributes, element names and legacy html remain author-controlled capabilities, so application data belongs only in text or scalar values. The renderer's structural checks do not turn explicit raw HTML into untrusted-content sanitization.
        +
        +```sh
        +marqdo call lib/browser.mq.md render_list 'sel="#items"' 'items=[{"tag":"li","children":[{"tag":"span","text":"A  & literal"},{"tag":"button","text":"Delete","attrs":{"type":"button","data-id":"1"}}]}]' --effects none --json
        +```
        +
        +`spec` =
        +
        +| tag | items |
        +|---|---|
        +| `tag` | `items` |
        +
        +We **targets = [Select the existing list container](table.put(in=None, at=`sel`, value=`spec`))**.
        +Return *[Describe the native bridge list update](table.put(in=None, at="render_list", value=`targets`))*.
        diff --git a/lib/document.mq.md b/lib/document.mq.md
        index 88f48b6..68c3cd4 100644
        --- a/lib/document.mq.md
        +++ b/lib/document.mq.md
        @@ -1,8 +1,10 @@
         ---
         markup: occlusion
        +import:
        +  fs: lib/fs.mq.md
         ---
         
        -Inert document operations share the renderer Markdown parser. Every function is pure.
        +Document transforms share the renderer Markdown parser. read_table composes explicit native filesystem reading with literal data selection.
         
         Inspect and transform Markdown without executing its contents.
         
        @@ -153,3 +155,39 @@ Effects: pure.
         List code fence language and literal source with byte spans; never run foreign or Marqdo code.
         
         Return *[List code fence language and literal source with byte spans; never run foreign or Marqdo code](> host_document_code_blocks text=`text`)*.
        +
        +## table
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| text | text | required | Markdown containing the literal GFM data table |
        +| title | any | None | Exact unique section title, or None for the whole document |
        +| index | number | 0 | Zero-based table index within the selected section |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | any | Native literal table value, preserving the source language's record/list/column shape |
        +
        +Use `text`, `title`=None and `index`=0 to obtain actual data from a Markdown resource. The existing tables function supplies inert headers and cell text for document inspection; this operation reads the selected table with the same literal cell and shape rules as Marqdo source. Booleans, numbers, None and quoted text therefore retain their types. An @, 行 or row marker selects record rows, one-column tables become lists, and ordinary multi-column tables retain their native map shape.
        +
        +The renderer's parser locates real tables and skips fenced examples. Duplicate section titles, missing tables, duplicate headers and row-width mismatches produce diagnostics. Variables, interpolated values and executable expressions are rejected; surrounding prose, imports and code fences are never executed. This keeps large schemas, seed rows and style declarations readable as Markdown data leaves while small callable functions explain their use. Construction is pure and performs no file, process, plugin or network operation.
        +
        +Return *[Read the selected literal table with the native language rules](host_document_table(text=`text`, title=`title`, index=`index`))*.
        +
        +
        +## read_table
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| path | text | required | UTF-8 Markdown data path under --fs-root |
        +| title | any | None | Exact unique section title, or None for the whole document |
        +| index | number | 0 | Zero-based table index within the selected section |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | any | Actual literal table value loaded through native fs.read |
        +
        +Use `path`, `title`=None and `index`=0 for a separate Markdown data leaf. The filesystem reader validates the granted root and UTF-8; table then selects one real data table and preserves its native types and shape. Requires fs.read. A resource file can explain its schema and examples beside the data without being loaded as a program. Missing paths, ambiguous headings, invalid cells and structural mismatches remain diagnostics. This function writes nothing and executes no imports, bold statements or foreign fences from the file.
        +
        +We **source = [Read this selected Markdown resource natively](fs.read_text(path=`path`))**.
        +Return *[Obtain its literal data without running the document](table(text=`source`, title=`title`, index=`index`))*.
        diff --git a/lib/foreign.mq.md b/lib/foreign.mq.md
        index 0f8f95f..97f64de 100644
        --- a/lib/foreign.mq.md
        +++ b/lib/foreign.mq.md
        @@ -22,7 +22,7 @@ For development, keep EN/ZH behavior aligned and compose public libraries first.
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| lang | text | required | Registered interpreter language identifier, such as python |
        +| lang | text | required | Registered interpreter language identifier, such as node |
         | cmd | any | required | Executable command or interpreter override |
         | args | any | None | Argument list passed to the called command or function |
         
        @@ -286,31 +286,44 @@ Return *[Apply one code/function to each input in parallel; returns parsed JSON
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| kernels | any | None | Kernel/session specifications for persistent interpreters |
        -| cells | any | None | Code cells to evaluate in a persistent interpreter |
        -| values | any | None | Variable/value record to inject into a session |
        -| inputs | any | None | Input values for the batched calls |
        +| kernels | any | None | Kernel rows: name/language and optional command/environment settings |
        +| cells | any | None | Cell-to-kernel routing rows; referenced code fences belong to the document |
        +| values | any | None | Rows naming a kernel, variable name and native value to copy |
        +| inputs | any | None | Optional declared per-cell input values |
         
         | 返回 | 类型 | 说明 |
         |---|---|---|
        -| result | any | Declare a document view session |
        +| result | map | Plain view plan with kind, kernels, cells, values and inputs |
         
        -Use `kernels`=None, `cells`=None, `values`=None, `inputs`=None as the inputs for this operation.
        +Use `kernels`=None, `cells`=None, `values`=None and `inputs`=None to
        +declare a view session from ordinary data tables. The returned map has
        +kind="foreign-session" and the four supplied specifications. This pure task
        +does not launch an interpreter, create a live kernel or read another file.
        +View later consumes the plan and the document's bound code fences. Bind the plan
        +to `会话` in the entry procedure: View uses this documented binding to distinguish
        +a declared plan from ordinary maps and low-level live session handles. A normal
        +`## main` function can be called directly and indexed by View; the separate native
        +report example shows the complete declarations.
         
        -Effects: pure.
        +Kernel rows identify languages explicitly; the native-first public workflow
        +uses Node only for Intl formatting after Marqdo has computed its data. A values
        +row copies a JSON-safe native value into a named kernel variable. Cells in the
        +same kernel share state, while separate kernel rows preserve isolation.
        +Missing or invalid runtime declarations remain the View/session diagnostic.
         
        -Declare a document view session. `kernels` and `cells` are ordinary tables:
        -kernels are `|名称|语言|命令|` (ZH or EN), cells are `|单元|内核|`.
        -Returns a foreign session handle consumed by `view`; without this handle the
        -view has no persistent kernel state.
        +This result is a serializable plan, so it can be returned by marqdo call.
        +A live session_open handle is a different resource and cannot be reconstructed
        +from a JSON string. For a low-level multi-evaluation task, open, use and close
        +that handle within one callable workflow; format_summary in the native report
        +example demonstrates that lifetime and its real failure exits.
         
        -We retain **`p` = [Empty map](table.empty_map())**.
        -We retain **`p` = [Set the kind field in the new record](table.put(in=`p`, at="kind", value="foreign-session"))**.
        -We retain **`p` = [Set the kernels field in the new record](table.put(in=`p`, at="kernels", value=`kernels`))**.
        -We retain **`p` = [Set the cells field in the new record](table.put(in=`p`, at="cells", value=`cells`))**.
        -We retain **`p` = [Set the values field in the new record](table.put(in=`p`, at="values", value=`values`))**.
        -We retain **`p` = [Set the inputs field in the new record](table.put(in=`p`, at="inputs", value=`inputs`))**.
        -Return *p*.
        +`plan` =
        +
        +| kind | kernels | cells | values | inputs |
        +|---|---|---|---|---|
        +| "foreign-session" | `kernels` | `cells` | `values` | `inputs` |
        +
        +After declaring the explicit view inputs we return *plan*.
         
         ## session_open
         
        @@ -340,7 +353,7 @@ Return *[Start a persistent Python/Node kernel; returns an opaque handle value](
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| id | any | required | Identifier returned by the corresponding create/spawn operation |
        +| id | any | required | Opaque session_open handle retained in this process; never rebuild it from id text |
         | code | any | None | Bound code-fence value; supply lang and source for inline text |
         | source | any | None | Source text to run with the selected interpreter |
         | input | any | None | Structured value JSON-encoded on stdin; cannot combine with stdin |
        @@ -349,15 +362,23 @@ Return *[Start a persistent Python/Node kernel; returns an opaque handle value](
         
         | 返回 | 类型 | 说明 |
         |---|---|---|
        -| result | any | Evaluate code (a code value) or source text in session id; returns a record with id/alive |
        +| result | any | Evaluation record: ok/code/result/stdout/stderr/alive/timed_out/ms and diagnostic metadata |
         
         Use `id`, `code`=None, `source`=None, `input`=None, `stdin`=None, `timeout`=None as the inputs for this operation.
         
         Effects: process.exec.
         
         Evaluate code (a code value) or source text in session id; returns a record
        -with id/alive. `input` is JSON-encoded for the kernel; `stdin` is raw program
        -stdin for this evaluation.
        +with ok/code/result/stdout/stderr/alive/timed_out/ms. Inspect ok before result:
        +code is zero on success and -1 on a kernel failure. stdout and stderr preserve
        +captured text; error explains a failed evaluation. alive says whether the kernel
        +can still be used. An ordinary language exception can leave it alive; process
        +death or timeout may retire it. Close only the live original handle. The record's
        +text id is diagnostic identity and cannot replace that opaque handle.
        +
        +`input` is JSON-encoded for the kernel; `stdin` is raw program stdin for this
        +evaluation. JSON-unsafe values remain diagnostics, never guessed text. Effects
        +require process.exec, and the timeout is seconds while ms reports elapsed time.
         
         Return *[Evaluate code (a code value) or source text in session id; returns a record with id/alive](> host_foreign_session_eval id=`id` code=`code` source=`source` input=`input` stdin=`stdin` timeout=`timeout`)*.
         
        @@ -365,7 +386,7 @@ Return *[Evaluate code (a code value) or source text in session id; returns a re
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| id | any | required | Identifier returned by the corresponding create/spawn operation |
        +| id | any | required | Opaque session_open handle retained in this process; never rebuild it from id text |
         | name | text | required | Name to resolve, register or look up |
         | value | any | required | Value to transform or store, without mutating the input |
         
        @@ -385,7 +406,7 @@ Return *[Set one kernel variable from a Marqdo value (JSON copy)](> host_foreign
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| id | any | required | Identifier returned by the corresponding create/spawn operation |
        +| id | any | required | Opaque session_open handle retained in this process; never rebuild it from id text |
         | name | text | required | Name to resolve, register or look up |
         
         | 返回 | 类型 | 说明 |
        @@ -404,7 +425,7 @@ Return *[Read one kernel variable as a Marqdo value](> host_foreign_session_get
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| id | any | required | Identifier returned by the corresponding create/spawn operation |
        +| id | any | required | Opaque session_open handle retained in this process; never rebuild it from id text |
         
         | 返回 | 类型 | 说明 |
         |---|---|---|
        @@ -422,7 +443,7 @@ Return *[List kernel variable names](> host_foreign_session_names id=`id`)*.
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| id | any | required | Identifier returned by the corresponding create/spawn operation |
        +| id | any | required | Opaque session_open handle retained in this process; never rebuild it from id text |
         
         | 返回 | 类型 | 说明 |
         |---|---|---|
        @@ -442,7 +463,7 @@ Return *[Consume (affine close) a live session handle: kill and remove it](> hos
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| id | any | required | Identifier returned by the corresponding create/spawn operation |
        +| id | any | required | Opaque session_open handle retained in this process; never rebuild it from id text |
         
         | 返回 | 类型 | 说明 |
         |---|---|---|
        diff --git a/lib/fs.mq.md b/lib/fs.mq.md
        index 0022fa9..17a9d37 100644
        --- a/lib/fs.mq.md
        +++ b/lib/fs.mq.md
        @@ -617,7 +617,7 @@ Return *[Compute SHA-256 with a 64 KiB read buffer; supports binary and large fi
         | pattern | text | "**" | Relative path glob supporting *, ** and ? |
         | exclude | any | None | Glob pattern list pruned during traversal; None excludes nothing |
         | max_depth | number | 64 | Maximum traversal depth |
        -| kind | text | "file" | Entry kind filter: file, dir or any |
        +| kind | text | "file" | Entry kind filter: file, dir or all (files and directories) |
         
         | 返回 | 类型 | 说明 |
         |------|------|------|
        @@ -771,3 +771,17 @@ Serialize then atomically replace the file; formatting and comments are not pres
         
         We retain **`body` = [Stringify](csv.stringify(rows=`value`))**.
         Return *[Atomic write](atomic_write(path=`path`, text=`body`))*.
        +
        +## resolve
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| path | text | required | Path relative to the granted filesystem root, or an absolute path inside it |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | text | Normalized absolute logical path after the native root and symlink checks |
        +
        +Use `path` to obtain an absolute address before giving a local file to another resource, such as a SQLite URL. The host resolves it using the same filesystem context as read_text and temp_dir, so a different process working directory does not change the selected root. The destination may not exist yet; its nearest existing ancestor still undergoes the native root and symlink checks. Requires fs.read and creates no file. The returned path remains logical, including permitted links; external plugins and processes retain their own operating-system authority.
        +
        +Return *[Resolve the path through the native filesystem context](host_fs_resolve(path=`path`))*.
        diff --git a/lib/外联.mq.md b/lib/外联.mq.md
        index f01ffb3..3425bee 100644
        --- a/lib/外联.mq.md
        +++ b/lib/外联.mq.md
        @@ -22,7 +22,7 @@ import:
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| 语言 | any | 必填 | 已注册的解释器语言标识,例如 python |
        +| 语言 | any | 必填 | 已注册的解释器语言标识,例如 node |
         | 命令 | any | 必填 | 可执行命令或解释器覆盖配置 |
         | 参数 | any | None | 传给命令或函数的实参列表 |
         
        @@ -69,7 +69,7 @@ import:
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| 语言 | any | 必填 | 已注册的解释器语言标识,例如 python |
        +| 语言 | any | 必填 | 已注册的解释器语言标识,例如 node |
         | 源码 | any | 必填 | 交给指定解释器执行的源文本 |
         | 标准输入 | any | None | 写入子进程标准输入的文本 |
         | 环境 | any | None | 传给子进程的环境变量与值记录 |
        @@ -95,7 +95,7 @@ import:
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
         | 代码 | any | None | 已绑定的代码围栏值;内联文本请使用语言与源码参数 |
        -| 语言 | any | None | 已注册的解释器语言标识,例如 python |
        +| 语言 | any | None | 已注册的解释器语言标识,例如 node |
         | 源码 | any | None | 交给指定解释器执行的源文本 |
         | 标准输入 | any | None | 写入子进程标准输入的文本 |
         | 输入 | any | None | 编码为 JSON 后写入标准输入的结构化值;不能与标准输入文本同时使用 |
        @@ -129,7 +129,7 @@ auto | text | json | lines。`命令` 仅本次覆盖解释器。
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| 语言 | any | None | 已注册的解释器语言标识,例如 python |
        +| 语言 | any | None | 已注册的解释器语言标识,例如 node |
         
         | 返回 | 类型 | 说明 |
         |---|---|---|
        @@ -148,7 +148,7 @@ auto | text | json | lines。`命令` 仅本次覆盖解释器。
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| 语言 | any | 必填 | 已注册的解释器语言标识,例如 python |
        +| 语言 | any | 必填 | 已注册的解释器语言标识,例如 node |
         | 命令 | any | None | 可执行命令或解释器覆盖配置 |
         | 参数 | any | None | 传给命令或函数的实参列表 |
         | 模板 | any | None | 解释器启动模板 |
        @@ -173,7 +173,7 @@ auto | text | json | lines。`命令` 仅本次覆盖解释器。
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| 语言 | any | 必填 | 已注册的解释器语言标识,例如 python |
        +| 语言 | any | 必填 | 已注册的解释器语言标识,例如 node |
         
         | 返回 | 类型 | 说明 |
         |---|---|---|
        @@ -210,7 +210,7 @@ auto | text | json | lines。`命令` 仅本次覆盖解释器。
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
         | 代码 | any | None | 已绑定的代码围栏值;内联文本请使用语言与源码参数 |
        -| 语言 | any | None | 已注册的解释器语言标识,例如 python |
        +| 语言 | any | None | 已注册的解释器语言标识,例如 node |
         | 源码 | any | None | 交给指定解释器执行的源文本 |
         | 输入 | any | None | 编码为 JSON 后写入标准输入的结构化值;不能与标准输入文本同时使用 |
         | 标准输入 | any | None | 写入子进程标准输入的文本 |
        @@ -257,7 +257,7 @@ JSON 进 / JSON 出:把 `输入` 编码到 stdin,解析 stdout JSON 返回
         |---|---|---|---|
         | 输入表 | any | 必填 | 批量调用所用的输入值 |
         | 代码 | any | None | 已绑定的代码围栏值;内联文本请使用语言与源码参数 |
        -| 语言 | any | None | 已注册的解释器语言标识,例如 python |
        +| 语言 | any | None | 已注册的解释器语言标识,例如 node |
         | 源码 | any | None | 交给指定解释器执行的源文本 |
         | 命令 | any | None | 可执行命令或解释器覆盖配置 |
         | 环境 | any | None | 传给子进程的环境变量与值记录 |
        @@ -284,35 +284,37 @@ JSON 进 / JSON 出:把 `输入` 编码到 stdin,解析 stdout JSON 返回
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| 内核表 | any | None | 持久解释器的内核或会话规格 |
        -| 单元表 | any | None | 在持久解释器中求值的代码单元 |
        -| 值表 | any | None | 注入会话的变量与值记录 |
        -| 输入表 | any | None | 批量调用所用的输入值 |
        +| 内核表 | any | None | 声明内核名称、语言及可选运行设置的普通表格 |
        +| 单元表 | any | None | 把文档中绑定的代码单元路由到明确内核 |
        +| 值表 | any | None | 内核、变量名与原生值组成的行记录 |
        +| 输入表 | any | None | 可选的逐单元输入值 |
         
         | 返回 | 类型 | 说明 |
         |---|---|---|
        -| result | any | 声明文档视图会话 |
        +| result | map | 普通视图计划,含 kind/kernels/cells/values/inputs 五个字段 |
         
        -这里使用`内核表`=None、`单元表`=None、`值表`=None、`输入表`=None。
        +View 约定把声明计划绑定到入口中的 `会话`,以区分普通记录和低层会话句柄。
        +普通 `## main` 函数可同时被 call 调用和 View 索引;完整声明可参照原生报表示例。
         
        -调用效应:pure。
        +这里使用`内核表`=None、`单元表`=None、`值表`=None、`输入表`=None,声明后续 View 使用的普通数据。返回记录的 kind 是 foreign-session,另外四个字段保留传入规格。这个纯函数不会启动解释器、创建活内核或读取另一个文件;实际执行由 View 消费计划与绑定代码围栏时发生。
         
        -声明文档视图会话。内核表和单元表都是普通表格;返回一个 foreign 会话句柄,
        -供 view 消费。没有这个句柄时,view 的 cells 是无状态的。
        +内核行显式指定语言。推荐工作流先用 Marqdo 固有库完成计算,再只把真正缺失的本地化展示交给 Node Intl。值表把 JSON 安全的数据拷贝送入命名变量,同一内核中的单元共享状态,不同内核保持隔离。缺失或错误的运行规格仍由实际视图会话给出诊断,不能被一份声明记录证明为已执行成功。
         
        -得到**`p` = [调用 empty map](table.empty_map())**。
        -得到**`p` = [在新记录中设置 kind 字段](table.put(in=`p`, at="kind", value="foreign-session"))**。
        -得到**`p` = [在新记录中设置 kernels 字段](table.put(in=`p`, at="kernels", value=`内核表`))**。
        -得到**`p` = [在新记录中设置 cells 字段](table.put(in=`p`, at="cells", value=`单元表`))**。
        -得到**`p` = [在新记录中设置 values 字段](table.put(in=`p`, at="values", value=`值表`))**。
        -得到**`p` = [在新记录中设置 inputs 字段](table.put(in=`p`, at="inputs", value=`输入表`))**。
        -完成后返回*p*。
        +返回的是可以被 marqdo call 序列化的计划。会话开启得到的活资源则需要在同一个可调用流程内完成借用和关闭,不能根据字符串标识重建句柄。原生报告例程中的 format_summary 展示了两次持久求值、真实错误出口和关闭责任。
        +
        +`计划` =
        +
        +| kind | kernels | cells | values | inputs |
        +|---|---|---|---|---|
        +| "foreign-session" | `内核表` | `单元表` | `值表` | `输入表` |
        +
        +明确这些视图输入后,我们返回*计划*。
         
         ## 会话开启
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| 语言 | any | 必填 | 已注册的解释器语言标识,例如 python |
        +| 语言 | any | 必填 | 已注册的解释器语言标识,例如 node |
         | 命令 | any | None | 可执行命令或解释器覆盖配置 |
         | 环境 | any | None | 传给子进程的环境变量与值记录 |
         | 工作目录 | any | None | 子进程工作目录 |
        @@ -320,21 +322,21 @@ JSON 进 / JSON 出:把 `输入` 编码到 stdin,解析 stdout JSON 返回
         
         | 返回 | 类型 | 说明 |
         |---|---|---|
        -| result | any | 启动一个持久的 Python / Node 内核;返回会话 id |
        +| result | any | 启动持久的 Python / Node 内核,返回不能跨 JSON 重建的不透明句柄 |
         
         这里使用`语言`、`命令`=None、`环境`=None、`工作目录`=None、`超时`=None。
         
         调用效应:process.exec。
         
        -启动一个持久的 Python / Node 内核;返回会话 id。`超时` 是每次求值的默认超时。
        +启动持久的 Python / Node 内核,返回不能跨 JSON 重建的不透明句柄。`超时` 是每次求值的默认超时。
         
        -完成后返回*[启动一个持久的 Python / Node 内核;返回会话 id](> host_foreign_session_open lang=`语言` cmd=`命令` env=`环境` cwd=`工作目录` timeout=`超时`)*。
        +完成后返回*[启动持久的 Python / Node 内核,返回不能跨 JSON 重建的不透明句柄](> host_foreign_session_open lang=`语言` cmd=`命令` env=`环境` cwd=`工作目录` timeout=`超时`)*。
         
         ## 会话求值
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| 标识 | any | 必填 | 对应创建或启动操作返回的标识 |
        +| 标识 | any | 必填 | 会话开启返回并保留在本进程内的原始不透明句柄 |
         | 代码 | any | None | 已绑定的代码围栏值;内联文本请使用语言与源码参数 |
         | 源码 | any | None | 交给指定解释器执行的源文本 |
         | 输入 | any | None | 编码为 JSON 后写入标准输入的结构化值;不能与标准输入文本同时使用 |
        @@ -343,22 +345,22 @@ JSON 进 / JSON 出:把 `输入` 编码到 stdin,解析 stdout JSON 返回
         
         | 返回 | 类型 | 说明 |
         |---|---|---|
        -| result | any | 在会话中求值代码(code 值)或源码文本;返回带 id/alive 的记录 |
        +| result | any | 求值状态记录,含 ok/code/result/stdout/stderr/alive/timed_out/ms |
         
         这里使用`标识`、`代码`=None、`源码`=None、`输入`=None、`标准输入`=None、`超时`=None。
         
         调用效应:process.exec。
         
        -在会话中求值代码(code 值)或源码文本;返回带 id/alive 的记录。
        +求值状态记录,含 ok/code/result/stdout/stderr/alive/timed_out/ms。
         `输入` 会编码为 JSON 交给内核。
         
        -完成后返回*[在会话中求值代码(code 值)或源码文本;返回带 id/alive 的记录](> host_foreign_session_eval id=`标识` code=`代码` source=`源码` input=`输入` stdin=`标准输入` timeout=`超时`)*。
        +完成后返回*[求值状态记录,含 ok/code/result/stdout/stderr/alive/timed_out/ms](> host_foreign_session_eval id=`标识` code=`代码` source=`源码` input=`输入` stdin=`标准输入` timeout=`超时`)*。
         
         ## 会话设值
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| 标识 | any | 必填 | 对应创建或启动操作返回的标识 |
        +| 标识 | any | 必填 | 会话开启返回并保留在本进程内的原始不透明句柄 |
         | 名称 | any | 必填 | 要解析、注册或查找的名称 |
         | 值 | any | 必填 | 待转换或保存的值;不会就地修改输入 |
         
        @@ -378,7 +380,7 @@ JSON 进 / JSON 出:把 `输入` 编码到 stdin,解析 stdout JSON 返回
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| 标识 | any | 必填 | 对应创建或启动操作返回的标识 |
        +| 标识 | any | 必填 | 会话开启返回并保留在本进程内的原始不透明句柄 |
         | 名称 | any | 必填 | 要解析、注册或查找的名称 |
         
         | 返回 | 类型 | 说明 |
        @@ -397,7 +399,7 @@ JSON 进 / JSON 出:把 `输入` 编码到 stdin,解析 stdout JSON 返回
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| 标识 | any | 必填 | 对应创建或启动操作返回的标识 |
        +| 标识 | any | 必填 | 会话开启返回并保留在本进程内的原始不透明句柄 |
         
         | 返回 | 类型 | 说明 |
         |---|---|---|
        @@ -415,7 +417,7 @@ JSON 进 / JSON 出:把 `输入` 编码到 stdin,解析 stdout JSON 返回
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| 标识 | any | 必填 | 对应创建或启动操作返回的标识 |
        +| 标识 | any | 必填 | 会话开启返回并保留在本进程内的原始不透明句柄 |
         
         | 返回 | 类型 | 说明 |
         |---|---|---|
        @@ -433,7 +435,7 @@ JSON 进 / JSON 出:把 `输入` 编码到 stdin,解析 stdout JSON 返回
         
         | 参数 | 类型 | 默认 | 说明 |
         |---|---|---|---|
        -| 标识 | any | 必填 | 对应创建或启动操作返回的标识 |
        +| 标识 | any | 必填 | 会话开启返回并保留在本进程内的原始不透明句柄 |
         
         | 返回 | 类型 | 说明 |
         |---|---|---|
        diff --git a/lib/文件.mq.md b/lib/文件.mq.md
        index 7f4758b..0f57b89 100644
        --- a/lib/文件.mq.md
        +++ b/lib/文件.mq.md
        @@ -615,7 +615,7 @@ marqdo call lib/文件.mq.md 尝试读文本 '路径="lib/fs.mq.md"' --effects f
         | 模式 | text | "**" | 相对路径 glob,支持 *、** 与 ? |
         | 排除 | any | None | 遍历时剪枝的 glob 模式列表;None 表示不排除 |
         | 深度上限 | number | 64 | 最大遍历深度 |
        -| 类型 | text | "file" | 条目类型过滤:file、dir 或 any |
        +| 类型 | text | "file" | 条目类型过滤:file、dir 或 all;all 同时包含文件和目录 |
         
         | 返回 | 类型 | 说明 |
         |------|------|------|
        @@ -769,3 +769,17 @@ marqdo call lib/文件.mq.md 尝试读文本 '路径="lib/fs.mq.md"' --effects f
         
         得到**`body` = [调用 stringify](csv.stringify(rows=`数据`))**。
         完成后返回*[将准备好的文本写入指定文件](原子写文本(路径=`路径`, 内容=`body`))*。
        +
        +## 解析路径
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 路径 | text | 必填 | 相对已授予文件根的路径,或根内的绝对路径 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | text | 经过原生根目录与符号链接检查的绝对逻辑路径 |
        +
        +输入`路径`,在授权 fs.read 后解析绝对地址。它使用读文本与临时目录相同的文件上下文,因此进程工作目录与 --fs-root 不同时也能正确组合本地资源 URI。目标可以尚未创建,最近的已有祖先仍经过根目录和符号链接检查。解析只返回地址,不创建文件;结果保留逻辑路径,外部插件和进程继续按各自操作系统权限执行。
        +
        +完成后返回*[通过原生文件上下文解析实际地址](host_fs_resolve(path=`路径`))*.
        diff --git a/lib/文档.mq.md b/lib/文档.mq.md
        index b963d81..8e34760 100644
        --- a/lib/文档.mq.md
        +++ b/lib/文档.mq.md
        @@ -1,8 +1,10 @@
         ---
         markup: occlusion
        +import:
        +  document: lib/document.mq.md
         ---
         
        -通过渲染器共用的 Markdown 解析器读取文档结构。全部接口均为纯函数。
        +通过渲染器共用的 Markdown 解析器读取文档结构。结构变换为纯函数,读取表值通过原生文件能力加载指定数据。
         
         不执行内容地读取与变换 Markdown 结构。
         
        @@ -153,3 +155,36 @@ marqdo call lib/文档.mq.md 章节列表 '内容="# Notes"' --effects none --js
         列出代码块语言、字面源码和字节区间;不运行其中的外联或 Marqdo 代码。
         
         完成后返回*[列出代码块语言、字面源码和字节区间;不运行其中的外联或 Marqdo 代码](> host_document_code_blocks text=`内容`)*。
        +
        +## 表值
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 内容 | text | 必填 | 含字面 GFM 数据表的 Markdown |
        +| 标题 | any | None | 精确且唯一的章节名;None 表示整篇 |
        +| 索引 | number | 0 | 所选章节中从零开始的表格序号 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | any | 与 Marqdo 字面表相同形态和类型的实际数据 |
        +
        +这里使用`内容`、`标题`=None和`索引`=0。常量表中的布尔、数值、空值和引号文本保留原生类型;@、行或 row 首列产生记录列表,单列产生普通列表,其余表保留原有映射形态。定位使用渲染器共用的 Markdown 解析器,会跳过围栏内示例。重复标题、表头冲突、列数不齐和非法索引会给出诊断。变量引用、插值和可执行表达式不能作为数据读取;正文、导入和外联围栏也不会执行。这样可以把模式、种子和样式常量拆成 Markdown 数据叶子,同时让调用函数说明实际用途。
        +
        +完成后返回*[按原生字面规则读取表值](document.table(text=`内容`, title=`标题`, index=`索引`))*.
        +
        +
        +## 读取表值
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 路径 | text | 必填 | 文件根内的 UTF-8 Markdown 数据文件 |
        +| 标题 | any | None | 精确且唯一的章节名;None 表示整篇 |
        +| 索引 | number | 0 | 所选章节中从零开始的表格序号 |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | any | 通过原生 fs.read 加载的字面表数据 |
        +
        +这里使用`路径`、`标题`=None和`索引`=0,授权 fs.read 后读取数据叶子。文件读取检查根目录与 UTF-8,表值选择保留字面类型及实际结构。文件可以把字段说明、示例和数据写在一起,读取过程不会运行其中的语句、导入或其他语言围栏。文件缺失、标题重复、单元格动态引用和列数不齐均保留诊断。此函数只读,调用者再按数据库、样式或其他领域的真实契约使用返回值。
        +
        +完成后返回*[原生读取并选择 Markdown 数据](document.read_table(path=`路径`, title=`标题`, index=`索引`))*.
        diff --git a/lib/浏览器.mq.md b/lib/浏览器.mq.md
        index 9747b7d..8605a19 100644
        --- a/lib/浏览器.mq.md
        +++ b/lib/浏览器.mq.md
        @@ -5,6 +5,7 @@ description: >-
           浏览器效应助手(WASM 客户端)。优先 GFM 表格 + 本库;勿用 json.set 链拼效应。
         import:
           table: lib/table.mq.md
        +  browser: lib/browser.mq.md
         ---
         
         浏览器效应助手(WASM 客户端)。优先 GFM 表格 + 本库;勿用 json.set 链拼效应。
        @@ -691,3 +692,27 @@ SPA 导航(bridge `navigate`)。
         | `正文` | `文件名` | `mime` |
         
         完成后返回*[在新记录中设置 download 字段](table.put(in=None, at="download", value=`spec`))*。
        +
        +## 渲染列表
        +
        +| 参数 | 类型 | 默认 | 说明 |
        +|---|---|---|---|
        +| 选择器 | text | 必填 | 已有列表容器的 CSS 选择器 |
        +| 条目 | list | 必填 | 字面文字或含 tag、text 或 children、class、attrs 的记录列表 |
        +| 标签 | text | "li" | 官方桥使用的元素名,通常为 li |
        +
        +| 返回 | 类型 | 说明 |
        +|---|---|---|
        +| result | map | 交给官方浏览器桥执行的纯列表更新指令 |
        +
        +这里使用`选择器`、`条目`和`标签`="li"。动态数据按记录传入,文字放在 text,委托事件需要的标识放在 attrs 的 data-id;无需手动拼接列表 HTML。官方桥会转义普通文字,但构造指令不表示已经更新页面,也不验证选择器确实存在。标签与属性名由应用决定,业务输入应保留为文字。页面最初的容器布局仍由 Document 组件负责,这个工具只替换已存在列表的条目。
        +
        +记录还可包含 tag 与 children,children 是同样结构的文本/控件记录列表。例如一条 li 内先放 span 文本,再放带 data-id 的 button,删除交互就不需要拼 HTML。text、html 与 children 不混用;嵌套最多 32 层,总记录最多 10000。元素名和属性名经过结构检查,事件属性与活动 URL 被拒绝。用户内容放 text,原有 html 只保留明确的兼容出口。
        +
        +下例直接返回组合指令,不加载服务器插件,也不执行浏览器 IO;真实的 [浏览器工程](../examples/browser-app/static/app.mq.md) 使用同一结构。元素、属性名与兼容 html 都属于作者决定的能力,外部业务值应只进入 text 或标量属性值。结构检查不能替代对显式原生 HTML 的内容清理。
        +
        +```sh
        +marqdo call lib/浏览器.mq.md 渲染列表 '选择器="#items"' '条目=[{"tag":"li","children":[{"tag":"span","text":"字面 <文字> & 内容"},{"tag":"button","text":"删除","attrs":{"type":"button","data-id":"1"}}]}]' --effects none --json
        +```
        +
        +完成后返回*[描述已有列表的文字更新](browser.render_list(sel=`选择器`, items=`条目`, tag=`标签`))*.
        diff --git a/plugins/engineering/Cargo.toml b/plugins/engineering/Cargo.toml
        new file mode 100644
        index 0000000..4f8142b
        --- /dev/null
        +++ b/plugins/engineering/Cargo.toml
        @@ -0,0 +1,26 @@
        +[package]
        +name = "marqdo_plugin_engineering"
        +version = "0.1.0"
        +edition = "2021"
        +license = "Apache-2.0"
        +description = "OS, authenticated service and archive boundaries for executable Marqdo engineering handbooks"
        +publish = false
        +
        +[lib]
        +name = "engineering"
        +crate-type = ["cdylib", "rlib"]
        +
        +[dependencies]
        +marqdo-plugin-sdk = { path = "../../crates/marqdo-plugin-sdk" }
        +serde_json = "1"
        +ureq = { version = "=2.9.7", default-features = false, features = ["tls", "gzip"] }
        +sha2 = "=0.10.9"
        +hmac = "=0.12.1"
        +chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
        +zip = { version = "=0.6.6", default-features = false, features = ["deflate"] }
        +libc = "0.2"
        +flate2 = "1"
        +base64 = "0.22"
        +
        +# Reuse the real compiler for source analysis; no second syntax recognizer.
        +marqdo = { path = "../.." }
        diff --git a/plugins/engineering/src/lib.rs b/plugins/engineering/src/lib.rs
        new file mode 100644
        index 0000000..6891f01
        --- /dev/null
        +++ b/plugins/engineering/src/lib.rs
        @@ -0,0 +1,611 @@
        +//! Native boundaries for executable engineering documents. Business ordering,
        +//! version decisions and ordinary file reads/writes belong in .mq.md.
        +//! No Python interpreter, generated shell program or secret-valued tool result.
        +use std::{
        +    collections::BTreeMap,
        +    ffi::CStr,
        +    fs::{self, File},
        +    io::{Read, Write},
        +    os::raw::{c_char, c_int},
        +    path::{Component, Path, PathBuf},
        +    process::{Command, Stdio},
        +    sync::mpsc,
        +    thread,
        +    time::{Duration, Instant},
        +};
        +use hmac::{Hmac, Mac};
        +use marqdo_plugin_sdk::*;
        +use sha2::{Digest, Sha256};
        +use serde_json::{json, Value};
        +
        +type Answer = Result;
        +const OUTPUT: usize = 256 * 1024;
        +const HTTP_MAX: u64 = 16 * 1024 * 1024;
        +fn field<'a>(v: &'a Value, key: &str) -> Result<&'a str, String> {
        +    v.get(key).and_then(Value::as_str).ok_or_else(|| format!("missing text field {key}"))
        +}
        +fn hash(b: &[u8]) -> String { hex(&Sha256::digest(b)) }
        +fn hex(b: &[u8]) -> String { b.iter().map(|x| format!("{x:02x}")).collect() }
        +fn read_bounded(mut r: impl Read, max: u64) -> Result, String> {
        +    let mut b = Vec::new();
        +    r.by_ref().take(max + 1).read_to_end(&mut b).map_err(|e| format!("read failed ({:?})",e.kind()))?;
        +    if b.len() as u64 > max { return Err("bounded input limit exceeded".into()); }
        +    Ok(b)
        +}
        +fn scoped(root: &Path, relative: &str) -> Result {
        +    let p = root.join(relative).canonicalize().map_err(|_| "path does not exist")?;
        +    if !p.starts_with(root) { return Err("artifact path escapes the selected root".into()); }
        +    Ok(p)
        +}
        +fn homes(root: &Path) -> Vec {
        +    let mut out = Vec::new();
        +    for key in ["MARQDO_RELEASE_CREDENTIAL_HOME", "USERPROFILE", "HOME"] {
        +        if let Some(s) = std::env::var_os(key) { out.push(PathBuf::from(s)); }
        +    }
        +    #[cfg(unix)]
        +    {
        +        use std::os::unix::fs::MetadataExt;
        +        for p in std::iter::once(root).chain(root.ancestors().skip(1)) {
        +            if p.join(".git").exists() {
        +                if let Ok(m) = p.metadata() {
        +                    unsafe {
        +                        let mut entry: libc::passwd = std::mem::zeroed();
        +                        let mut result = std::ptr::null_mut();
        +                        let mut buf = vec![0u8; 32768];
        +                        if libc::getpwuid_r(m.uid(), &mut entry, buf.as_mut_ptr().cast(), buf.len(), &mut result) == 0
        +                            && !result.is_null() && !entry.pw_dir.is_null() {
        +                            out.push(PathBuf::from(CStr::from_ptr(entry.pw_dir).to_string_lossy().into_owned()));
        +                        }
        +                    }
        +                }
        +            }
        +        }
        +    }
        +    out.dedup();
        +    out
        +}
        +fn redact(mut text: String, private: &[String]) -> String {
        +    for token in private.iter().filter(|s| !s.is_empty()) { text = text.replace(token, ""); }
        +    for (k, v) in std::env::vars() {
        +        if v.len() >= 8 && ["TOKEN", "SECRET", "PASSWORD", "ACCESS_KEY"].iter().any(|x| k.contains(x)) {
        +            text = text.replace(&v, "");
        +        }
        +    }
        +    text
        +}
        +struct Output { code: i32, stdout: String, stderr: String, timed_out: bool, truncated: bool }
        +fn pipe(mut input: impl Read + Send + 'static, limit: usize) -> mpsc::Receiver<(Vec, bool)> {
        +    let (send, recv) = mpsc::channel();
        +    thread::spawn(move || {
        +        let mut buf = Vec::new(); let mut part = [0u8; 8192]; let mut truncated = false;
        +        while let Ok(n) = input.read(&mut part) {
        +            if n == 0 { break; }
        +            let keep = (limit - buf.len()).min(n);
        +            buf.extend_from_slice(&part[..keep]); truncated |= keep < n;
        +        }
        +        let _ = send.send((buf, truncated));
        +    });
        +    recv
        +}
        +fn execute(root: &Path, argv: &[String], input: Option, env: &BTreeMap,
        +           timeout_ms: u64, max_output: usize) -> Result {
        +    if argv.is_empty() || argv[0].is_empty() { return Err("argv must not be empty".into()); }
        +    if !(1..=3_600_000).contains(&timeout_ms) || !(1..=16_777_216).contains(&max_output) {
        +        return Err("timeout/output limit outside supported range".into());
        +    }
        +    let mut cmd = Command::new(&argv[0]);
        +    cmd.args(&argv[1..]).current_dir(root).envs(env)
        +        .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
        +    #[cfg(unix)] {
        +        use std::os::unix::process::CommandExt;
        +        unsafe { cmd.pre_exec(|| {
        +            if libc::setpgid(0, 0) != 0 { return Err(std::io::Error::last_os_error()); }
        +            Ok(())
        +        }); }
        +    }
        +    let mut child = cmd.spawn().map_err(|_| format!("cannot start {}", argv[0]))?;
        +    let stdout = pipe(child.stdout.take().unwrap(), max_output);
        +    let stderr = pipe(child.stderr.take().unwrap(), max_output);
        +    let mut stdin = child.stdin.take().unwrap();
        +    thread::spawn(move || { if let Some(text) = input { let _ = stdin.write_all(text.as_bytes()); } });
        +    let started = Instant::now(); let mut timed_out = false;
        +    let code = loop {
        +        match child.try_wait().map_err(|_| "cannot observe process")? {
        +            Some(status) => break status.code().unwrap_or(1),
        +            None if started.elapsed() >= Duration::from_millis(timeout_ms) => {
        +                timed_out = true;
        +                #[cfg(unix)] unsafe { libc::kill(-(child.id() as i32), libc::SIGKILL); }
        +                #[cfg(windows)] { let _ = Command::new("taskkill").args(["/PID", &child.id().to_string(), "/T", "/F"]).output(); }
        +                let _ = child.kill(); let _ = child.wait(); break 124;
        +            }
        +            None => thread::sleep(Duration::from_millis(10)),
        +        }
        +    };
        +    // Descendants retaining inherited pipes must not prevent a bounded return.
        +    let (out, out_clip) = stdout.recv_timeout(Duration::from_secs(1)).unwrap_or((Vec::new(), true));
        +    let (err, err_clip) = stderr.recv_timeout(Duration::from_secs(1)).unwrap_or((Vec::new(), true));
        +    Ok(Output { code, stdout: String::from_utf8_lossy(&out).into(), stderr: String::from_utf8_lossy(&err).into(),
        +                timed_out, truncated: out_clip || err_clip })
        +}
        +fn github_token(root: &Path) -> Option {
        +    for key in ["GH_TOKEN", "GITHUB_TOKEN"] {
        +        if let Ok(s) = std::env::var(key) { if !s.is_empty() { return Some(s); } }
        +    }
        +    let args = ["git", "-c", &format!("safe.directory={}", root.display()), "credential", "fill"]
        +        .into_iter().map(str::to_string).collect::>();
        +    let env = BTreeMap::from([("GIT_TERMINAL_PROMPT".into(), "0".into())]);
        +    if let Ok(p) = execute(root, &args, Some("protocol=https\nhost=github.com\n\n".into()), &env, 15_000, OUTPUT) {
        +        if let Some(s) = p.stdout.lines().find_map(|s| s.strip_prefix("password=")) { return Some(s.into()); }
        +    }
        +    for home in homes(root) {
        +        if let Ok(text) = fs::read_to_string(home.join(".config/gh/hosts.yml")) {
        +            if let Some(s) = text.lines().find_map(|s| s.trim().strip_prefix("oauth_token:")) {
        +                return Some(s.trim().trim_matches(['"', '\'']).into());
        +            }
        +        }
        +    }
        +    None
        +}
        +
        +fn git_config(env: &mut BTreeMap, key: &str, value: String) {
        +    let start = env.get("GIT_CONFIG_COUNT").cloned().or_else(|| std::env::var("GIT_CONFIG_COUNT").ok())
        +        .and_then(|s| s.parse::().ok()).unwrap_or(0);
        +    env.insert(format!("GIT_CONFIG_KEY_{start}"),key.into());
        +    env.insert(format!("GIT_CONFIG_VALUE_{start}"),value);
        +    env.insert("GIT_CONFIG_COUNT".into(),(start+1).to_string());
        +}
        +
        +fn command(root: &Path, p: &Value) -> Answer {
        +    let mut argv = p.get("argv").and_then(Value::as_array).ok_or("argv must be a list")?
        +        .iter().map(|v| v.as_str().map(str::to_string).ok_or("argv items must be text".to_string()))
        +        .collect::, _>>()?;
        +    let cwd = scoped(root, p.get("cwd").and_then(Value::as_str).unwrap_or("."))?;
        +    let mut env = BTreeMap::new(); let mut private = Vec::new();
        +    // Trust only the explicitly selected workspace, only in this child tree.
        +    // Cargo/Go VCS probes inherit the same scoped Git metadata access.
        +    git_config(&mut env,"safe.directory",root.display().to_string());
        +    let exe = argv.first().and_then(|s| Path::new(s).file_stem()).and_then(|s| s.to_str()).unwrap_or("");
        +    if ["bash", "sh", "pwsh", "powershell"].contains(&exe) && argv.iter().any(|s| ["-c", "-Command", "-EncodedCommand"].contains(&s.as_str())) {
        +        return Err("use argument vectors or maintained external scripts, not generated shell programs".into());
        +    }
        +    if exe == "git" {
        +        if argv.iter().any(|s| ["--force", "-f", "--force-with-lease", "--no-verify"].contains(&s.as_str()) || s.starts_with("--force=")) {
        +            return Err("forced Git updates and hook bypass are forbidden".into());
        +        }
        +        argv.splice(1..1, ["-c".into(), format!("safe.directory={}", cwd.display())]);
        +        env.insert("GIT_TERMINAL_PROMPT".into(), "0".into());
        +        if argv.iter().any(|s| ["fetch", "push", "ls-remote"].contains(&s.as_str())) {
        +            if let Some(token) = github_token(root) {
        +                // URL-scoped headers stay in the child environment, not argv.
        +                let auth = format!("Authorization: Basic {}", base64(format!("x-access-token:{token}").as_bytes()));
        +                for url in ["https://proxy.cflmy.top/github.com/", "https://github.com/"] {
        +                    git_config(&mut env,&format!("http.{url}.extraheader"),auth.clone());
        +                }
        +                private.push(token); private.push(auth);
        +                argv.splice(1..1, ["-c".into(), "http.version=HTTP/1.1".into(), "-c".into(), "http.postBuffer=524288000".into()]);
        +            }
        +        }
        +    }
        +    if let Some(e) = p.get("env").and_then(Value::as_object) {
        +        for (k, v) in e { env.insert(k.clone(), v.as_str().ok_or("env values must be text")?.into()); }
        +    }
        +    // Child Git trace output could expose internally attached authentication.
        +    for key in ["GIT_TRACE", "GIT_TRACE_CURL", "GIT_CURL_VERBOSE"] { env.insert(key.into(), "0".into()); }
        +    let timeout = p.get("timeout_ms").and_then(Value::as_u64)
        +        .unwrap_or_else(|| p.get("timeout").and_then(Value::as_u64).unwrap_or(120) * 1000);
        +    let max = p.get("max_output").and_then(Value::as_u64).unwrap_or(OUTPUT as u64) as usize;
        +    let out = execute(&cwd, &argv, p.get("stdin").and_then(Value::as_str).map(str::to_string), &env, timeout, max)?;
        +    Ok(json!({"code":out.code,"stdout":redact(out.stdout,&private),"stderr":redact(out.stderr,&private),
        +        "timed_out":out.timed_out,"truncated":out.truncated}))
        +}
        +fn http_json(root: &Path, p: &Value) -> Answer {
        +    let path = field(p, "path")?;
        +    if !path.starts_with("/repos/cflmy/marqdo/") || path.contains("..") { return Err("GitHub path is outside the project".into()); }
        +    let method = p.get("method").and_then(Value::as_str).unwrap_or("GET");
        +    if !["GET", "PATCH", "POST"].contains(&method) { return Err("unsupported GitHub method".into()); }
        +    let bases = std::env::var("MARQDO_RELEASE_API_BASE").map(|s| vec![s])
        +        .unwrap_or_else(|_| vec!["https://proxy.cflmy.top/api.github.com".into(), "https://api.github.com".into()]);
        +    let token = github_token(root);
        +    for (i, base) in bases.iter().enumerate() {
        +        let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(35)).build();
        +        let url = format!("{}{path}", base.trim_end_matches('/'));
        +        let mut req = agent.request(method, &url).set("Accept", "application/vnd.github+json")
        +            .set("User-Agent", "marqdo-engineering/1").set("X-GitHub-Api-Version", "2022-11-28");
        +        if let Some(token) = &token { req = req.set("Authorization", &format!("Bearer {token}")); }
        +        let response = if let Some(body) = p.get("data").filter(|v| !v.is_null()) {
        +            req.set("Content-Type", "application/json").send_string(&body.to_string())
        +        } else { req.call() };
        +        match response {
        +            Ok(r) => {
        +                let body = read_bounded(r.into_reader(), HTTP_MAX)
        +                    .and_then(|bytes| serde_json::from_slice(&bytes).map_err(|_| "GitHub response is not JSON".into()));
        +                match body {
        +                    Ok(value) => return Ok(value),
        +                    Err(_) if method != "POST" && i + 1 < bases.len() => continue,
        +                    Err(message) => return Err(message),
        +                }
        +            }
        +            Err(ureq::Error::Status(404,_)) if p.get("missing").and_then(Value::as_bool).unwrap_or(false) => return Ok(Value::Null),
        +            Err(ureq::Error::Status(code,_)) => {
        +                if method == "POST" || i + 1 == bases.len() || ![429,500,502,503,504].contains(&code) {
        +                    return Err(format!("GitHub HTTP {code}"));
        +                }
        +            }
        +            Err(_) if method == "POST" || i + 1 == bases.len() => return Err("GitHub network request failed; uncertain mutations are not replayed".into()),
        +            Err(_) => {}
        +        }
        +    }
        +    Err("GitHub request failed after proxy and direct routes".into())
        +}
        +fn archive(root: &Path, p: &Value) -> Answer {
        +    let path = scoped(root, field(p,"path")?)?;
        +    let file = File::open(path).map_err(|_|"cannot open archive")?;
        +    let mut zip = zip::ZipArchive::new(file).map_err(|_|"invalid ZIP")?;
        +    if zip.len() > 100000 { return Err("ZIP has too many entries".into()); }
        +    let mut seen=std::collections::HashSet::new();
        +    let mut entries = Vec::new(); let mut metadata = serde_json::Map::new(); let mut total = 0u64; let mut actual = 0u64;
        +    for i in 0..zip.len() {
        +        let mut f = zip.by_index(i).map_err(|_|"cannot read ZIP entry")?;
        +        let name = f.name().replace('\\', "/");
        +        if !seen.insert(name.clone()) || name.as_bytes().get(1)==Some(&b':') {return Err("duplicate or drive-qualified ZIP path".into());}
        +        if Path::new(&name).components().any(|c| matches!(c, Component::ParentDir | Component::RootDir | Component::Prefix(_))) {
        +            return Err("unsafe ZIP path".into());
        +        }
        +        if f.unix_mode().is_some_and(|m|m & 0o170000 == 0o120000) { return Err("ZIP symlink is not supported".into()); }
        +        total = total.checked_add(f.size()).ok_or("ZIP expansion overflow")?;
        +        if total > 2 * 1024 * 1024 * 1024 { return Err("ZIP expands beyond 2 GiB".into()); }
        +        let mut selected = Vec::new();
        +        let keep = ["VERSION","ext/VERSION","Cargo.toml","extension/package.json"].contains(&name.as_str());
        +        let mut buf=[0u8;65536];
        +        loop {
        +            let n=f.read(&mut buf).map_err(|_|"ZIP content/CRC validation failed")?;
        +            if n==0 {break;}
        +            actual = actual.checked_add(n as u64).ok_or("ZIP expansion overflow")?;
        +            if actual > 2 * 1024 * 1024 * 1024 { return Err("ZIP expands beyond 2 GiB".into()); }
        +            if keep && selected.len()<16384 {selected.extend_from_slice(&buf[..n.min(16384-selected.len())]);}
        +        }
        +        if keep { metadata.insert(name.clone(),json!(String::from_utf8(selected).map_err(|_|"ZIP metadata is not UTF-8")?)); }
        +        entries.push(name);
        +    }
        +    Ok(json!({"entries":entries,"metadata":metadata}))
        +}
        +fn hmac(key:&[u8], data:&str)->Vec {
        +    let mut mac=Hmac::::new_from_slice(key).expect("HMAC accepts all key lengths");
        +    mac.update(data.as_bytes());mac.finalize().into_bytes().to_vec()
        +}
        +fn r2_settings(root:&Path)->Result,String> {
        +    let mut settings=std::env::vars().filter(|(k,_)|k.starts_with("R2_")).collect::>();
        +    for home in homes(root) {
        +        if let Ok(text)=fs::read_to_string(home.join(".marqdo/r2.env")) {
        +            for line in text.lines().map(str::trim).filter(|s|!s.starts_with('#')) {
        +                if let Some((k,v))=line.split_once('=') {settings.entry(k.trim().into()).or_insert_with(||v.trim().trim_matches(['\'','"']).into());}
        +            }
        +        }
        +    }
        +    for k in ["R2_ENDPOINT","R2_BUCKET","R2_ACCESS_KEY_ID","R2_SECRET_ACCESS_KEY"] {
        +        if settings.get(k).is_none_or(String::is_empty) {return Err(format!("missing {k}; configure ~/.marqdo/r2.env"));}
        +    }
        +    Ok(settings)
        +}
        +fn r2_put(root:&Path,p:&Value)->Answer {
        +    let s=r2_settings(root)?;
        +    let key=field(p,"key")?;
        +    if !key.bytes().all(|b|b.is_ascii_alphanumeric() || b"/.-_".contains(&b)) || key.contains("..") {
        +        return Err("unsafe R2 key".into());
        +    }
        +    let body=if let Some(path)=p.get("path").and_then(Value::as_str) {
        +        read_bounded(File::open(scoped(root,path)?).map_err(|_|"cannot open upload")?,256*1024*1024)?
        +    } else {field(p,"text")?.as_bytes().to_vec()};
        +    let digest=hash(&body);
        +    if let Some(expected)=p.get("sha256").and_then(Value::as_str) {
        +        if digest!=expected {return Err("upload bytes changed after verification".into());}
        +    }
        +    let endpoint=s["R2_ENDPOINT"].trim_end_matches('/');
        +    let host=endpoint.split_once("://").ok_or("R2 endpoint needs a scheme")?.1;
        +    if host.contains('/') || !(endpoint.starts_with("https://") || endpoint.starts_with("http://127.0.0.1:")) {
        +        return Err("R2 endpoint must be HTTPS (loopback HTTP is for isolated tests)".into());
        +    }
        +    let uri=format!("/{}/{key}",s["R2_BUCKET"]);
        +    let date=chrono::Utc::now();let amz=date.format("%Y%m%dT%H%M%SZ").to_string();let day=date.format("%Y%m%d").to_string();
        +    let region=s.get("R2_REGION").map(String::as_str).unwrap_or("auto");
        +    let mime=if key.ends_with("/VERSION"){"text/plain; charset=utf-8"}else{"application/zip"};
        +    let headers=format!("content-type:{mime}\nhost:{host}\nx-amz-content-sha256:{digest}\nx-amz-date:{amz}\n");
        +    let signed="content-type;host;x-amz-content-sha256;x-amz-date";
        +    let canonical=format!("PUT\n{uri}\n\n{headers}\n{signed}\n{digest}");
        +    let scope=format!("{day}/{region}/s3/aws4_request");
        +    let string=format!("AWS4-HMAC-SHA256\n{amz}\n{scope}\n{}",hash(canonical.as_bytes()));
        +    let k=hmac(format!("AWS4{}",s["R2_SECRET_ACCESS_KEY"]).as_bytes(),&day);
        +    let k=hmac(&k,region);let k=hmac(&k,"s3");let k=hmac(&k,"aws4_request");
        +    let auth=format!("AWS4-HMAC-SHA256 Credential={}/{scope}, SignedHeaders={signed}, Signature={}",s["R2_ACCESS_KEY_ID"],hex(&hmac(&k,&string)));
        +    let response=ureq::AgentBuilder::new().timeout(Duration::from_secs(180)).build()
        +        .put(&format!("{endpoint}{uri}")).set("Content-Type",mime).set("x-amz-content-sha256",&digest)
        +        .set("x-amz-date",&amz).set("Authorization",&auth).send_bytes(&body);
        +    match response {
        +        Ok(r) if [200,201].contains(&r.status()) => Ok(json!({"key":key,"sha256":digest,"size":body.len()})),
        +        Ok(r)=>Err(format!("R2 HTTP {}",r.status())),
        +        Err(ureq::Error::Status(code,_))=>Err(format!("R2 HTTP {code}")),
        +        Err(_)=>Err("R2 upload failed or timed out; verify before retrying".into())
        +    }
        +}
        +
        +fn git_inspect(root:&Path)->Answer {
        +    if !root.join(".git").exists() {return Err("inspect requires a Git checkout".into());}
        +    let query=|args:&[&str]|->Result{
        +        let argv=std::iter::once("git").chain(args.iter().copied()).map(|s|json!(s)).collect::>();
        +        let out=command(root,&json!({"argv":argv}))?;
        +        if out["code"]!=0 {return Err("Git metadata query failed".into());}
        +        Ok(out["stdout"].as_str().unwrap_or("").trim().into())
        +    };
        +    Ok(json!({"root":root.display().to_string(),"branch":query(&["branch","--show-current"])?,
        +        "commit":query(&["rev-parse","HEAD"])?,"changes":query(&["status","--porcelain"])?,
        +        "tags":query(&["tag","--list"])?.lines().collect::>(),
        +        "extension_on_main":query(&["ls-files","vscode-extension"])?,
        +        "origin":query(&["remote","get-url","origin"])?}))
        +}
        +fn base64(bytes:&[u8])->String {
        +    const C:&[u8]=b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        +    let mut out=String::new();
        +    for part in bytes.chunks(3) {
        +        let a=part[0] as usize;let b=*part.get(1).unwrap_or(&0) as usize;let c=*part.get(2).unwrap_or(&0) as usize;
        +        out.push(C[a>>2] as char);out.push(C[((a&3)<<4)|(b>>4)] as char);
        +        out.push(if part.len()>1 {C[((b&15)<<2)|(c>>6)] as char}else{'='});
        +        out.push(if part.len()>2 {C[c&63] as char}else{'='});
        +    }
        +    out
        +}
        +
        +
        +
        +fn expression(e:&marqdo::ast::Expr)->Option {
        +    use marqdo::ast::{Expr,Literal,InterpPart,UnaryOp,BinaryOp,IndexKey};
        +    Some(match e {
        +        Expr::Literal(Literal::None)=>"None".into(),
        +        Expr::Literal(Literal::Bool(v))=>if *v{"True".into()}else{"False".into()},
        +        Expr::Literal(Literal::Int(v))=>v.to_string(),
        +        Expr::Literal(Literal::Num(v))=>{let s=v.to_string();if s.contains('.')||s.contains('e')||s.contains('E'){s}else{format!("{s}.0")}},
        +        Expr::Literal(Literal::Text(v))=>{
        +            if v.contains('`'){return None;} serde_json::to_string(v).ok()?
        +        },
        +        Expr::Var(v)=>format!("`{v}`"),
        +        Expr::Interp(parts)=>{
        +            let mut text=String::new();
        +            for p in parts {match p {
        +                InterpPart::Lit(v)=>{if v.contains('`'){return None;}text.push_str(v);},
        +                InterpPart::Var(v)=>text.push_str(&format!("`{v}`")),
        +                _=>return None
        +            }}
        +            serde_json::to_string(&text).ok()?
        +        },
        +        Expr::Unary{op,expr}=>match op {UnaryOp::Neg=>format!("-{}",expression(expr)?),UnaryOp::Not=>format!("(not {})",expression(expr)?)},
        +        Expr::Binary{op,left,right}=>format!("({} {} {})",expression(left)?,match op {
        +            BinaryOp::Add=>"+",BinaryOp::Sub=>"-",BinaryOp::Mul=>"*",BinaryOp::Div=>"/",
        +            BinaryOp::Eq=>"==",BinaryOp::Ne=>"!=",BinaryOp::Lt=>"<",BinaryOp::Le=>"<=",
        +            BinaryOp::Gt=>">",BinaryOp::Ge=>">=",BinaryOp::And=>"and",BinaryOp::Or=>"or"},expression(right)?),
        +        Expr::Call(call)=>call_source(call,false)?,
        +        Expr::List(items)=>format!("[{}]",items.iter().map(expression).collect::>>()?.join(", ")),
        +        // Dynamic map construction is deliberately not emitted as an alternate
        +        // author DSL: keep its real bound GFM table at the structural boundary.
        +        Expr::Map(_)|Expr::Formula(_)|Expr::Code(_)=>return None,
        +        Expr::Index{base,label}=>format!("access({}, {})",expression(base)?,match label {
        +            IndexKey::Lit(v)=>serde_json::to_string(v).ok()?,IndexKey::Var(v)=>format!("`{v}`")}),
        +        Expr::Occluded{label,payload}=>format!("[{}]({})",label,payload.as_deref().map(expression).transpose_option()?),
        +    })
        +}
        +trait OptionalText {fn transpose_option(self)->Option;}
        +impl OptionalText for Option> {
        +    fn transpose_option(self)->Option{match self{None=>Some(String::new()),Some(v)=>v}}
        +}
        +fn call_source(call:&marqdo::ast::CallExpr,statement:bool)->Option {
        +    use marqdo::ast::Arg;
        +    let call=call.with_modifiers_expanded().ok()?;
        +    let target=if let Some(path)=&call.path{path.join(".")}
        +        else if let Some(recv)=&call.receiver{format!("`{recv}`.{}",call.callee)}
        +        else{call.callee.clone()};
        +    let args=call.args.iter().map(|a|match a {
        +        Arg::Named{name,value}=>Some(format!("{name}={}",expression(value)?)),
        +        Arg::Positional(value)=>expression(value)
        +    }).collect::>>()?;
        +    if statement || call.receiver.is_some() {
        +        let target=if target.contains(char::is_whitespace){format!("[{target}]")}else{target};
        +        Some(format!("> {target} {}",args.join(" ")).trim_end().into())
        +    } else {
        +        if target.contains(char::is_whitespace){return None;}
        +        Some(format!("{target}({})",args.join(", ")))
        +    }
        +}
        +fn semantic_expr(e:&marqdo::ast::Expr)->Value {
        +    use marqdo::ast::{Expr,Arg};
        +    match e {
        +        Expr::Occluded{payload,..}=>payload.as_deref().map(semantic_expr).unwrap_or(json!(["none"])),
        +        Expr::Call(c)=>{
        +            let c=c.for_evaluation().unwrap_or_else(|_|c.clone());
        +            json!(["call",c.callee,c.path,c.receiver,c.args.iter().map(|a|match a{
        +                Arg::Named{name,value}=>json!(["named",name,semantic_expr(value)]),
        +                Arg::Positional(v)=>json!(["positional",semantic_expr(v)])
        +            }).collect::>()])
        +        },
        +        Expr::List(v)=>json!(["list",v.iter().map(semantic_expr).collect::>()]),
        +        Expr::Map(v)=>json!(["map",v.iter().map(|(k,v)|json!([k,semantic_expr(v)])).collect::>()]),
        +        Expr::Unary{op,expr}=>json!(["unary",format!("{op:?}"),semantic_expr(expr)]),
        +        Expr::Binary{op,left,right}=>json!(["binary",format!("{op:?}"),semantic_expr(left),semantic_expr(right)]),
        +        _=>json!(format!("{e:?}"))
        +    }
        +}
        +fn semantic_statements(body:&[marqdo::ast::Stmt])->Vec {
        +    use marqdo::ast::{Expr,Stmt};
        +    body.iter().map(|s|match s {
        +        Stmt::Assign{name,value,..}=>json!(["assign",name,semantic_expr(value)]),
        +        Stmt::Return{value,..}=>json!(["return",semantic_expr(value)]),
        +        Stmt::Call{call,..}=>json!(["eval",semantic_expr(&Expr::Call(call.clone()))]),
        +        Stmt::Expr{value,..}=>json!(["eval",semantic_expr(value)]),
        +        Stmt::Branch{arms,..}=>json!(["branch",arms.iter().map(|a|json!([a.condition.as_ref().map(semantic_expr),semantic_statements(&a.body)])).collect::>()]),
        +        Stmt::While{condition,body,..}=>json!(["while",semantic_expr(condition),semantic_statements(body)]),
        +        Stmt::ForEach{item,collection,body,..}=>json!(["foreach",item,collection,semantic_statements(body)])
        +    }).collect()
        +}
        +fn statement_locations(body:&[marqdo::ast::Stmt])->Vec {
        +    use marqdo::ast::Stmt;
        +    let mut out=Vec::new();
        +    for s in body {match s {
        +        Stmt::Assign{name,value,span,end_line}=>out.push(json!({"kind":"assign","name":name,"line":span.line,"end_line":end_line,"rendered":expression(value)})),
        +        Stmt::Return{value,span}=>out.push(json!({"kind":"return","line":span.line,"rendered":expression(value)})),
        +        Stmt::Call{call,span}=>out.push(json!({"kind":"call","line":span.line,"callee":call.path.as_ref().map(|p|p.join(".")).unwrap_or_else(||call.callee.clone()),"rendered":call_source(call,true)})),
        +        Stmt::Expr{value,span}=>out.push(json!({"kind":"eval","line":span.line,"rendered":expression(value)})),
        +        Stmt::Branch{arms,..}=>for arm in arms{out.extend(statement_locations(&arm.body));},
        +        Stmt::While{body,..}|Stmt::ForEach{body,..}=>out.extend(statement_locations(body))
        +    }}
        +    out
        +}
        +
        +fn analyze(p:&Value)->Answer {
        +    use marqdo::ast::{Expr,Function,Literal};
        +    fn default(e:&Expr)->Value {match e {
        +        Expr::Literal(Literal::Text(t))=>json!({"text":t}),
        +        Expr::Literal(Literal::None)=>json!({"source":"None"}),
        +        Expr::Literal(Literal::Bool(v))=>json!({"source":if *v{"True"}else{"False"}}),
        +        Expr::Literal(Literal::Int(v))=>json!({"source":v.to_string()}),
        +        Expr::Literal(Literal::Num(v))=>json!({"source":if v.fract()==0.0 { format!("{v:.1}") } else {v.to_string()}}),
        +        _=>json!({"debug":format!("{e:?}")})
        +    }}
        +    fn units(fs:&[Function],body:bool)->Vec {fs.iter().map(|f|json!({
        +        "name":f.name,"line":f.span.line,"level":f.level,"base":f.base,
        +        "params":f.params.iter().map(|p|json!({"name":p.name,"line":p.span.line,"inferred":p.inferred,"default":p.default.as_ref().map(default)})).collect::>(),
        +        "contract":f.contract.as_ref().map(|c|json!({"params":c.params.iter().map(|p|json!({"name":p.name,"ty":p.ty.name(),"desc":p.desc})).collect::>(),"returns":c.returns.as_ref().map(|r|json!({"ty":r.ty.name(),"desc":r.desc}))})),
        +        "children":units(&f.children,body),"semantic":semantic_statements(&f.body),"statements":statement_locations(&f.body),"body":if body{Some(format!("{:?}",f.body))}else{None}
        +    })).collect()}
        +    let source=field(p,"source")?;
        +    let module=marqdo::parse::parse_source(source).map_err(|e|format!("{e:#}"))?;
        +    let diagnostics=marqdo::check::check_module(&module,None).iter().map(|d|d.to_json()).collect::>();
        +    let ratios=marqdo::narrative_ratio::measure_source_units(source,&module.functions).iter()
        +        .map(|r|json!({"name":r.name,"line":r.line,"narrative":r.narrative,"total":r.total,"ratio":r.ratio})).collect::>();
        +    Ok(json!({"schema_version":1,"functions":units(&module.functions,p.get("include_body").and_then(Value::as_bool).unwrap_or(false)),
        +        "ratios":ratios,"diagnostics":diagnostics}))
        +}
        +
        +
        +fn gzip_text(p: &Value) -> Answer {
        +    use base64::Engine;
        +    let data = p.get("data").ok_or("missing portable bytes")?;
        +    if data.get("_type").and_then(Value::as_str) != Some("bytes") {
        +        return Err("gzip expects portable bytes".into());
        +    }
        +    let encoded = field(data,"base64")?;
        +    if encoded.len() > 24 * 1024 * 1024 { return Err("compressed input exceeds limit".into()); }
        +    let bytes = base64::engine::general_purpose::STANDARD.decode(encoded).map_err(|_| "invalid base64 bytes")?;
        +    let limit = p.get("max_bytes").and_then(Value::as_u64).unwrap_or(16 * 1024 * 1024);
        +    if limit == 0 || limit > 64 * 1024 * 1024 { return Err("invalid gzip output limit".into()); }
        +    let plain = read_bounded(flate2::read::MultiGzDecoder::new(bytes.as_slice()),limit)?;
        +    Ok(json!(String::from_utf8(plain).map_err(|_| "gzip text is not UTF-8")?))
        +}
        +
        +fn dispatch(request:&Value)->Answer {
        +    let root=PathBuf::from(request.get("root").and_then(Value::as_str).unwrap_or(".")).canonicalize().map_err(|_|"root does not exist")?;
        +    let op=field(request,"operation")?;
        +    let empty=json!({});let p=request.get("payload").unwrap_or(&empty);
        +    match op {
        +        "command"=>command(&root,p),
        +        "git_inspect"=>git_inspect(&root),
        +        "github"=>http_json(&root,p),
        +        "archive"=>archive(&root,p),
        +        "gzip_text"=>gzip_text(p),
        +        "analyze"=>analyze(p),
        +        "r2_put"=>r2_put(&root,p),
        +        _=>Err("unknown engineering boundary operation".into())
        +    }
        +}
        +unsafe extern "C" fn engineering_request(args:*const c_char,out:*mut *mut c_char,err:*mut *mut c_char)->c_int {
        +    let args=match parse_args(args){Ok(v)=>v,Err(e)=>{set_err(err,&e);return 1;}};
        +    let request=args.get("request").unwrap_or(&args);
        +    let result=match dispatch(request) {
        +        Ok(value)=>json!({"ok":true,"value":value,"error":null}),
        +        Err(message)=>json!({"ok":false,"value":null,"error":{"code":"engineering.boundary","message":message,"operation":request.get("operation")}})
        +    };
        +    set_out(out,&result.to_string());0
        +}
        +marqdo_plugin!(2,[("engineering_request","request",engineering_request)]);
        +
        +#[cfg(test)]
        +mod tests {
        +    use super::*;
        +    use std::sync::atomic::{AtomicUsize,Ordering};
        +    static NEXT:AtomicUsize=AtomicUsize::new(0);
        +    fn fixture()->PathBuf {
        +        let p=std::env::temp_dir().join(format!("mq-engineering-{}-{}",std::process::id(),NEXT.fetch_add(1,Ordering::Relaxed)));
        +        fs::create_dir_all(&p).unwrap(); p
        +    }
        +    #[cfg(unix)]
        +    #[test]
        +    fn argv_input_is_literal_and_noisy_output_is_bounded() {
        +        let dir=fixture();
        +        let input="quotes \" ' $HOME $(never-run) 😀\n".repeat(1000);
        +        let result=command(&dir,&json!({"argv":["/bin/cat"],"stdin":input})).unwrap();
        +        assert_eq!(result["code"],0);assert_eq!(result["stdout"],input);
        +        let result=command(&dir,&json!({"argv":["/usr/bin/head","-c","65536","/dev/zero"],"max_output":128})).unwrap();
        +        assert_eq!(result["code"],0);assert_eq!(result["stdout"].as_str().unwrap().len(),128);
        +        assert_eq!(result["truncated"],true);
        +        fs::remove_dir_all(dir).unwrap();
        +    }
        +    #[cfg(unix)]
        +    #[test]
        +    fn timeout_and_nonzero_exit_remain_observable() {
        +        let dir=fixture();let started=Instant::now();
        +        let result=command(&dir,&json!({"argv":["/bin/sleep","2"],"timeout_ms":20})).unwrap();
        +        assert_eq!(result["timed_out"],true);assert_eq!(result["code"],124);
        +        assert!(started.elapsed()Vec {
        +            let mut writer=flate2::write::GzEncoder::new(Vec::new(),flate2::Compression::default());
        +            writer.write_all(payload).unwrap();writer.finish().unwrap()
        +        }
        +        let mut bytes=compressed(b"Package: marqdo\n");bytes.extend(compressed(b"Version: 2.6.0\n"));
        +        let data=json!({"_type":"bytes","base64":base64::engine::general_purpose::STANDARD.encode(&bytes)});
        +        assert_eq!(gzip_text(&json!({"data":data})).unwrap(),"Package: marqdo\nVersion: 2.6.0\n");
        +        assert!(gzip_text(&json!({"data":data,"max_bytes":2})).is_err());
        +        assert!(gzip_text(&json!({"data":{"_type":"bytes","base64":"invalid"}})).is_err());
        +        let data=json!({"_type":"bytes","base64":base64::engine::general_purpose::STANDARD.encode(compressed(&[0xff]))});
        +        assert!(gzip_text(&json!({"data":data})).is_err());
        +    }
        +    #[test]
        +    fn analysis_uses_the_real_parser_without_loading_imports() {
        +        let source="---\nmarkup: occlusion\nimport:\n  absent: /does/not/exist.mq.md\n---\n## answer\n\n完成计算后返回*42*。\n";
        +        let result=analyze(&json!({"source":source})).unwrap();
        +        assert_eq!(result["functions"][0]["name"],"answer");
        +        assert!(result["diagnostics"].as_array().unwrap().is_empty());
        +        assert_eq!(result["functions"][0]["semantic"][0][0],"return");
        +    }
        +}
        diff --git a/plugins/web/abi_artifact.go b/plugins/web/abi_artifact.go
        index 9967261..fb77ecc 100644
        --- a/plugins/web/abi_artifact.go
        +++ b/plugins/web/abi_artifact.go
        @@ -35,10 +35,6 @@ func web_render_nodes(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int
         	if err != nil {
         		return replyJSON(outJSON, errMsg, nil, err)
         	}
        -	frag, err := artifact.RenderNodes(args["nodes"])
        -	if err != nil {
        -		return replyJSON(outJSON, errMsg, nil, err)
        -	}
         	pg := asPageMap(args["page"])
         	title := ""
         	if pg != nil {
        @@ -49,7 +45,8 @@ func web_render_nodes(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int
         	if t, ok := argStr(args, "title"); ok && t != "" {
         		title = t
         	}
        -	return replyJSON(outJSON, errMsg, artifact.RenderHTMLPage(title, frag), nil)
        +	html, err := artifact.RenderViewDocument(title, args["nodes"], nil)
        +	return replyJSON(outJSON, errMsg, html, err)
         }
         
         //export web_render_document
        @@ -88,26 +85,23 @@ func web_dom_markdown(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int
         	return replyJSON(outJSON, errMsg, artifact.MarkdownHTML(text), nil)
         }
         
        -//export web_serve_root
        -func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
        -	args, err := parseArgs(argsJSON)
        -	if err != nil {
        -		return replyJSON(outJSON, errMsg, nil, err)
        -	}
        +// prepareArtifactApp shares discovery and startup assembly between direct serving
        +// and resource composition. Listening starts only after resources have been bound.
        +func prepareArtifactApp(args map[string]any) (map[string]any, error) {
         	root, _ := argStr(args, "root")
         	if root == "" {
         		root = "."
         	}
         	abs, err := filepath.Abs(root)
         	if err != nil {
        -		return replyJSON(outJSON, errMsg, nil, err)
        +		return nil, err
         	}
         	if st, err := os.Stat(abs); err != nil || !st.IsDir() {
        -		return replyJSON(outJSON, errMsg, nil, fmt.Errorf("web.serve: root not a directory: %s", abs))
        +		return nil, fmt.Errorf("web.prepare: root not a directory: %s", abs)
         	}
         	files, err := artifact.ScanRoot(abs)
         	if err != nil {
        -		return replyJSON(outJSON, errMsg, nil, err)
        +		return nil, err
         	}
         	host, _ := argStr(args, "host")
         	if host == "" {
        @@ -129,14 +123,23 @@ func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
         		if title == "" {
         			title = f.Meta["标题"]
         		}
        -		body, structured, err := artifact.RenderFile(f, plugin.RunArtifact)
        +		nodes, structured, err := artifact.AssembleView(f, func(path string, args map[string]any) (any, error) {
        +			return plugin.RunArtifactAtRoot(path, args, abs)
        +		})
         		if err != nil {
         			return nil, err
         		}
        -		pg := page.New(map[string]any{"title": title, "intro": body})
        +		pg := page.New(map[string]any{"title": title, "intro": artifact.MarkdownHTML(f.Body)})
         		stampArtifactData(pg, f.Meta)
         		if structured {
        -			pg["artifact_html"] = artifact.RenderHTMLPage(title, body)
        +			// Validate structure and Resource contracts without querying or posting.
        +			if _, err := artifact.CollectDocumentHead(nodes); err != nil {
        +				return nil, fmt.Errorf("%s: %w", f.Rel, err)
        +			}
        +			if _, err := artifact.RenderNodesWithResources(nodes, httpx.ValidateViewResource); err != nil {
        +				return nil, fmt.Errorf("%s: %w", f.Rel, err)
        +			}
        +			pg["artifact_nodes"] = nodes
         		}
         		return pg, nil
         	}
        @@ -145,7 +148,7 @@ func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
         		if f.Kind == "web" && f.Route == "/" {
         			home, err = documentPage(f)
         			if err != nil {
        -				return replyJSON(outJSON, errMsg, nil, err)
        +				return nil, err
         			}
         			break
         		}
        @@ -164,11 +167,11 @@ func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
         			}
         			pg, err := documentPage(f)
         			if err != nil {
        -				return replyJSON(outJSON, errMsg, nil, err)
        +				return nil, err
         			}
         			out, err := app.Route(a, f.Route, pg)
         			if err != nil {
        -				return replyJSON(outJSON, errMsg, nil, err)
        +				return nil, err
         			}
         			a = out
         			continue
        @@ -209,20 +212,49 @@ func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
         	if mw := args["middleware"]; mw != nil {
         		out, err := middleware.Configure(a, map[string]any{"security": mw})
         		if err != nil {
        -			return replyJSON(outJSON, errMsg, nil, err)
        +			return nil, err
         		}
         		a = out
         	}
         	if sd, ok := argStr(args, "static_dir"); ok && sd != "" {
         		out, err := app.Static(a, sd, "/static")
         		if err != nil {
        -			return replyJSON(outJSON, errMsg, nil, err)
        +			return nil, err
         		}
         		a = out
         	}
        +	a["artifact_declared"] = artifact.InspectBag(nil, files)["declared"]
         	a["inspect"] = artifact.InspectBag(a, files)
        -	_, err = httpx.Listen(a, abs)
        -	return replyJSON(outJSON, errMsg, map[string]any{"ok": true, "value": a["inspect"], "error": nil}, err)
        +	a["artifact_root"] = abs
        +	return a, nil
        +}
        +
        +//export web_prepare_root
        +func web_prepare_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
        +	args, err := parseArgs(argsJSON)
        +	if err != nil {
        +		return replyJSON(outJSON, errMsg, nil, err)
        +	}
        +	a, err := prepareArtifactApp(args)
        +	return replyJSON(outJSON, errMsg, a, err)
        +}
        +
        +//export web_serve_root
        +func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
        +	args, err := parseArgs(argsJSON)
        +	if err != nil {
        +		return replyJSON(outJSON, errMsg, nil, err)
        +	}
        +	a, err := prepareArtifactApp(args)
        +	if err != nil {
        +		return replyJSON(outJSON, errMsg, nil, err)
        +	}
        +	inspection, err := httpx.InspectApp(a)
        +	if err != nil {
        +		return replyJSON(outJSON, errMsg, nil, err)
        +	}
        +	_, err = httpx.Listen(a, a["artifact_root"].(string))
        +	return replyJSON(outJSON, errMsg, map[string]any{"ok": true, "value": inspection, "error": nil}, err)
         }
         
         //export web_inspect
        @@ -239,12 +271,11 @@ func web_inspect(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
         		return replyJSON(outJSON, errMsg, artifact.InspectBag(nil, files), nil)
         	}
         	a := asPageMap(args["app"])
        -	if a != nil {
        -		if insp, ok := a["inspect"].(map[string]any); ok {
        -			return replyJSON(outJSON, errMsg, insp, nil)
        -		}
        +	if a == nil {
        +		return replyJSON(outJSON, errMsg, artifact.InspectBag(nil, nil), nil)
         	}
        -	return replyJSON(outJSON, errMsg, artifact.InspectBag(a, nil), nil)
        +	inspection, err := httpx.InspectApp(a)
        +	return replyJSON(outJSON, errMsg, inspection, err)
         }
         
         //export web_app_use
        diff --git a/plugins/web/abi_extra.go b/plugins/web/abi_extra.go
        index 85c191d..d4e4095 100644
        --- a/plugins/web/abi_extra.go
        +++ b/plugins/web/abi_extra.go
        @@ -345,7 +345,14 @@ func web_listen(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
         	if len(appBag) == 0 {
         		appBag = args
         	}
        -	out, err := httpx.Listen(appBag, entryDir())
        +	root := entryDir()
        +	if artifactRoot, ok := appBag["artifact_root"].(string); ok && artifactRoot != "" {
        +		root = artifactRoot
        +	}
        +	if _, err := httpx.InspectApp(appBag); err != nil {
        +		return replyJSON(outJSON, errMsg, nil, err)
        +	}
        +	out, err := httpx.Listen(appBag, root)
         	return replyJSON(outJSON, errMsg, out, err)
         }
         
        diff --git a/plugins/web/internal/apikey/apikey.go b/plugins/web/internal/apikey/apikey.go
        index 65b2c15..3a6b215 100644
        --- a/plugins/web/internal/apikey/apikey.go
        +++ b/plugins/web/internal/apikey/apikey.go
        @@ -1,6 +1,6 @@
         // Package apikey implements Bearer API key verification (G-API1).
         //
        -// Hash formula: sha256 hex of pepper + ":" + key (documented for anlian apikeys).
        +// Hash formula: sha256 hex of pepper + ":" + key.
         package apikey
         
         import (
        diff --git a/plugins/web/internal/artifact/artifact.go b/plugins/web/internal/artifact/artifact.go
        index f26661d..e4f2c46 100644
        --- a/plugins/web/internal/artifact/artifact.go
        +++ b/plugins/web/internal/artifact/artifact.go
        @@ -2,10 +2,12 @@
         package artifact
         
         import (
        +	"encoding/json"
         	"fmt"
         	"html"
         	"os"
         	"path/filepath"
        +	"sort"
         	"strings"
         
         	"github.com/marqdo/marqdo/plugins/web/internal/render"
        @@ -94,9 +96,17 @@ func ParseFrontmatter(src string) (meta map[string]string, body string) {
         // RenderNodes renders the existing five-column View schema recursively. Container
         // value cells hold more View rows; markdown leaves hold ordinary Markdown text.
         func RenderNodes(nodes any) (string, error) {
        +	return RenderNodesWithResources(nodes, nil)
        +}
        +
        +// ResourceRenderer resolves a typed Resource at the request boundary.
        +// Ordinary View construction remains pure; a nil renderer never starts IO.
        +type ResourceRenderer func(map[string]any) (string, error)
        +
        +func RenderNodesWithResources(nodes any, resources ResourceRenderer) (string, error) {
         	var b strings.Builder
         	b.WriteString(`
        `) - if err := renderNodes(&b, nodes, 0); err != nil { + if err := renderNodes(&b, nodes, 0, resources); err != nil { return "", err } b.WriteString(`
        `) @@ -105,7 +115,7 @@ func RenderNodes(nodes any) (string, error) { // Fixed runtime geometry, shared by offline previews and served Documents. // Authors choose row/column instead of embedding CSS or HTML in content cells. -const LayoutCSS = `.mq-view{max-width:72rem;margin:auto;padding:1.5rem;line-height:1.6;font-family:system-ui,sans-serif}.mq-view *{box-sizing:border-box}.mq-view .mq-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,16rem),1fr));gap:1.5rem}.mq-view .mq-column{display:flex;flex-direction:column;gap:1.5rem}.mq-view .mq-node{min-width:0}.mq-view nav,.mq-view footer{padding-block:1rem}.mq-view footer{border-top:1px solid #d5dce5}.mq-view a{color:#2457a7}.mq-view img{max-width:100%;height:auto}.mq-view pre{overflow:auto}` +const LayoutCSS = `.mq-view{max-width:72rem;margin:auto;padding:1.5rem;line-height:1.6;font-family:system-ui,sans-serif}.mq-view *{box-sizing:border-box}.mq-view .mq-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,16rem),1fr));gap:1.5rem}.mq-view .mq-column{display:flex;flex-direction:column;gap:1.5rem}.mq-view .mq-node{min-width:0;overflow-wrap:anywhere}.mq-view nav,.mq-view footer{padding-block:1rem}.mq-view footer{border-top:1px solid #d5dce5}.mq-view a{color:#2457a7}.mq-view img{max-width:100%;height:auto}.mq-view pre{overflow:auto}.mq-view input,.mq-view textarea,.mq-view select{max-width:100%;font:inherit}.mq-view textarea{width:100%}` // Preserve typed value cells when normalizing column tables. General AsRows // treats @ cells as text, which would stringify nested component tables. @@ -148,7 +158,85 @@ func viewRows(nodes any) ([]any, error) { } } -func renderNodes(b *strings.Builder, nodes any, depth int) error { +func containerTag(kind string) (string, string) { + switch kind { + case "row", "横排": + return "div", " mq-row" + case "column", "纵排": + return "div", " mq-column" + case "nav", "导航": + return "nav", "" + case "header", "页头": + return "header", "" + case "footer", "页脚": + return "footer", "" + case "section", "区域": + return "section", "" + case "aside", "侧栏": + return "aside", "" + case "form", "表单": + return "form", "" + case "list", "列表": + return "ul", "" + case "item", "列表项": + return "li", "" + case "select", "选择": + return "select", "" + } + return "", "" +} + +// FindSlot selects one declared View region without resolving any Resources. +// Container traversal is identical to rendering and never descends into a +// Resource's private map as if it were another View table. +func FindSlot(nodes any, slot string) (any, bool, error) { + var selected []any + var walk func(any, int) error + walk = func(nodes any, depth int) error { + if depth > 64 { + return fmt.Errorf("View: nesting exceeds 64 levels") + } + rows, err := viewRows(nodes) + if err != nil { + return err + } + for _, value := range rows { + row, ok := value.(map[string]any) + if !ok { + return fmt.Errorf("View slot: expected a row map") + } + if first(row, "slot", "槽") == slot { + selected = append(selected, row) + } + kind := strings.ToLower(first(row, "type", "类型")) + if tag, _ := containerTag(kind); tag != "" { + children := row["value"] + if children == nil { + children = row["值"] + } + if children == nil { + return fmt.Errorf("View %s: missing child rows", kind) + } + if err := walk(children, depth+1); err != nil { + return err + } + } + } + return nil + } + if err := walk(nodes, 0); err != nil { + return nil, false, err + } + if len(selected) > 1 { + return nil, false, fmt.Errorf("View slot %q is ambiguous", slot) + } + if len(selected) == 0 { + return nil, false, nil + } + return selected, true, nil +} + +func renderNodes(b *strings.Builder, nodes any, depth int, resources ResourceRenderer) error { if depth > 64 { return fmt.Errorf("View: nesting exceeds 64 levels") } @@ -165,6 +253,10 @@ func renderNodes(b *strings.Builder, nodes any, depth int) error { slot := first(row, "slot", "槽") val := first(row, "value", "值") attrs := first(row, "attrs", "属性") + attributes, err := renderAttributes(row) + if err != nil { + return fmt.Errorf("View row %d: %w", i+1, err) + } style := first(row, "style", "样式") class := "mq-node" if style != "" { @@ -173,25 +265,8 @@ func renderNodes(b *strings.Builder, nodes any, depth int) error { if slot != "" { class += " slot-" + html.EscapeString(slot) } - tag := "" - switch ty { - case "row", "横排": - tag = "div" - class += " mq-row" - case "column", "纵排": - tag = "div" - class += " mq-column" - case "nav", "导航": - tag = "nav" - case "header", "页头": - tag = "header" - case "footer", "页脚": - tag = "footer" - case "section", "区域": - tag = "section" - case "aside", "侧栏": - tag = "aside" - } + tag, geometry := containerTag(ty) + class += geometry if tag != "" { children := row["value"] if children == nil { @@ -200,23 +275,72 @@ func renderNodes(b *strings.Builder, nodes any, depth int) error { if children == nil { return fmt.Errorf("View row %d (%s): missing child rows in value", i+1, ty) } - b.WriteString(`<` + tag + ` class="` + class + `">`) - if err := renderNodes(b, children, depth+1); err != nil { + b.WriteString(`<` + tag + ` class="` + class + `"` + attributes + `>`) + if err := renderNodes(b, children, depth+1, resources); err != nil { return fmt.Errorf("View %s/%s: %w", ty, slot, err) } b.WriteString(``) continue } switch ty { + case "resource", "资源": + value := row["value"] + if value == nil { + value = row["值"] + } + resource, ok := value.(map[string]any) + if !ok || first(resource, "_type") == "" { + return fmt.Errorf("View row %d: resource value must be a typed Resource", i+1) + } + if first(resource, "_type") == "document_head" { + if _, err := ParseDocumentHead(resource); err != nil { + return err + } + continue + } + if resources == nil { + return fmt.Errorf("View row %d: resource requires an explicit request renderer", i+1) + } + fragment, err := resources(resource) + if err != nil { + return fmt.Errorf("View resource %s: %w", slot, err) + } + b.WriteString(`
        ` + fragment + `
        `) case "markdown", "正文": - b.WriteString(`
        ` + render.MarkdownToHTML(val) + `
        `) + b.WriteString(`
        ` + render.MarkdownToHTML(val) + `
        `) case "title", "标题": - b.WriteString(`

        ` + inline(val) + `

        `) + b.WriteString(`

        ` + inline(val) + `

        `) case "link", "链接": - if attrs == "" { - attrs = "#" + if !hasAttributeMap(row) { + if attrs == "" { + attrs = "#" + } + attributes = ` href="` + html.EscapeString(attrs) + `"` + } + b.WriteString(`` + inline(val) + ``) + case "input", "输入": + b.WriteString(``) + case "button", "按钮", "textarea", "多行输入", "label", "标签", "pre", "预格式", "option", "选项": + tags := map[string]string{"button": "button", "按钮": "button", "textarea": "textarea", "多行输入": "textarea", "label": "label", "标签": "label", "pre": "pre", "预格式": "pre", "option": "option", "选项": "option"} + tag := tags[ty] + b.WriteString(`<` + tag + ` class="` + class + `"` + attributes + `>` + html.EscapeString(val) + ``) + case "script", "脚本", "stylesheet", "样式表": + url := strings.ToLower(strings.TrimSpace(val)) + if url == "" || strings.ContainsAny(url, "\r\n\t") || strings.HasPrefix(url, "javascript:") || strings.HasPrefix(url, "vbscript:") { + return fmt.Errorf("View row %d: resource requires a nonempty non-script URL", i+1) + } + if attrs, ok := attributeValue(row).(map[string]any); ok { + for _, reserved := range []string{"href", "src", "rel"} { + if _, exists := attrs[reserved]; exists { + return fmt.Errorf("View row %d: resource URL and relation belong to its kind/value, not attrs.%s", i+1, reserved) + } + } + } + if ty == "script" || ty == "脚本" { + b.WriteString(``) + } else { + b.WriteString(``) } - b.WriteString(`` + inline(val) + ``) case "html", "原文": b.WriteString(`
        ` + val + `
        `) default: @@ -228,31 +352,137 @@ func renderNodes(b *strings.Builder, nodes any, depth int) error { case []any, map[string]any: return fmt.Errorf("View row %d: unknown structural type %q", i+1, ty) } - b.WriteString(`

        ` + inline(val) + `

        `) + b.WriteString(`

        ` + inline(val) + `

        `) } } return nil } +// Attribute records keep controls in the same five-column View schema. +// Legacy link rows may still carry a plain href string. Names and scalar values +// are checked before emission; handlers and inline style remain explicit escapes. +func attributeValue(row map[string]any) any { + if value, ok := row["attrs"]; ok && value != nil { + return value + } + return row["属性"] +} + +func hasAttributeMap(row map[string]any) bool { + _, ok := attributeValue(row).(map[string]any) + return ok +} + +func renderAttributes(row map[string]any) (string, error) { + value := attributeValue(row) + if value == nil || value == "" { + return "", nil + } + attrs, ok := value.(map[string]any) + if !ok { + if _, legacy := value.(string); legacy { + return "", nil + } + return "", fmt.Errorf("attrs must be a scalar attribute record or legacy link URL") + } + allowed := map[string]bool{ + "id": true, "title": true, "role": true, "name": true, "type": true, + "href": true, "src": true, "action": true, "method": true, "enctype": true, + "placeholder": true, "for": true, "rows": true, "cols": true, "size": true, + "min": true, "max": true, "step": true, "minlength": true, "maxlength": true, + "pattern": true, "autocomplete": true, "target": true, "rel": true, + "tabindex": true, "download": true, "accept": true, "alt": true, + "integrity": true, "crossorigin": true, "media": true, "referrerpolicy": true, + } + booleans := map[string]bool{"hidden": true, "disabled": true, "required": true, "readonly": true, "checked": true, "selected": true, "multiple": true, "autofocus": true, "async": true, "defer": true, "nomodule": true} + keys := make([]string, 0, len(attrs)) + for name := range attrs { + keys = append(keys, name) + } + sort.Strings(keys) + var out strings.Builder + for _, name := range keys { + if !(allowed[name] || booleans[name] || validCustomAttribute(name)) { + return "", fmt.Errorf("unsupported attribute %q; use attrs data/aria keys for client state", name) + } + v := attrs[name] + if v == nil { + continue + } + if booleans[name] { + flag, ok := v.(bool) + if !ok { + return "", fmt.Errorf("attribute %s requires a boolean", name) + } + if flag { + out.WriteString(" " + name) + } + continue + } + switch v.(type) { + case string, bool, float64, int, int64, json.Number: + default: + return "", fmt.Errorf("attribute %s requires a scalar value", name) + } + text := fmt.Sprint(v) + if name == "href" || name == "src" || name == "action" { + url := strings.ToLower(strings.TrimSpace(text)) + if strings.HasPrefix(url, "javascript:") || strings.HasPrefix(url, "vbscript:") { + return "", fmt.Errorf("attribute %s cannot execute a script URL", name) + } + } + out.WriteString(" " + name + `="` + html.EscapeString(text) + `"`) + } + return out.String(), nil +} + +func validCustomAttribute(name string) bool { + if !(strings.HasPrefix(name, "data-") || strings.HasPrefix(name, "aria-")) { + return false + } + if strings.HasSuffix(name, "-") { + return false + } + for _, char := range name { + if !(char >= 'a' && char <= 'z' || char >= '0' && char <= '9' || char == '-' || char == '_') { + return false + } + } + return true +} + // RenderFile explicitly opts a Document into startup-time component assembly. // Documents without view: main retain their existing Markdown/data-source path. -func RenderFile(f ArtifactFile, run func(string, map[string]any) (any, error)) (string, bool, error) { +// AssembleView runs the existing startup entry once and retains typed rows. +// Request resources are deliberately not resolved during assembly. +func AssembleView(f ArtifactFile, run func(string, map[string]any) (any, error)) (any, bool, error) { view := metaString(f.Meta, "view", "视图") if view == "" { - return MarkdownHTML(f.Body), false, nil + return nil, false, nil } if view != "main" { - return "", false, fmt.Errorf("%s: view/视图 must be main", f.Rel) + return nil, false, fmt.Errorf("%s: view/视图 must be main", f.Rel) } if metaString(f.Meta, "data_source", "数据源") != "" { - return "", false, fmt.Errorf("%s: view main is startup assembly; use an ordinary Document for automatic data_source binding", f.Rel) + return nil, false, fmt.Errorf("%s: view main is startup assembly; use an ordinary Document for automatic data_source binding", f.Rel) } nodes, err := run(f.Path, nil) if err != nil { - return "", false, fmt.Errorf("%s: view main: %w", f.Rel, err) + return nil, false, fmt.Errorf("%s: view main: %w", f.Rel, err) } if nodes == nil { - return "", false, fmt.Errorf("%s: view main must return View rows", f.Rel) + return nil, false, fmt.Errorf("%s: view main must return View rows", f.Rel) + } + return nodes, true, nil +} + +func RenderFile(f ArtifactFile, run func(string, map[string]any) (any, error)) (string, bool, error) { + nodes, structured, err := AssembleView(f, run) + if err != nil { + return "", false, err + } + if !structured { + return MarkdownHTML(f.Body), false, nil } html, err := RenderNodes(nodes) if err != nil { @@ -285,8 +515,12 @@ func RenderHTMLPage(title, innerHTML string) string { if t == "" { t = "Marqdo" } - return "" + t + - "
        " + innerHTML + "
        " + return renderHTMLPageWithHead(""+t+"", innerHTML) +} + +func renderHTMLPageWithHead(head, innerHTML string) string { + return "" + head + + "
        " + innerHTML + "
        " } // MarkdownHTML exposes render helper. @@ -385,6 +619,7 @@ func SystemRoutes() []map[string]any { return []map[string]any{ {"method": "GET", "path": "/_part/*", "kind": "system"}, {"method": "GET|POST", "path": "/_form/*", "kind": "system"}, + {"method": "POST", "path": "/_md", "kind": "system"}, {"method": "POST", "path": "/_runtime/tasks", "kind": "system"}, {"method": "GET", "path": "/_runtime/tasks/{id}", "kind": "system"}, {"method": "POST", "path": "/_runtime/tasks/{id}/cancel", "kind": "system"}, @@ -392,55 +627,85 @@ func SystemRoutes() []map[string]any { } } -// InspectBag builds {declared, system} from an app bag and/or scanned files. +// InspectBag reads declarations only. A prepared app's actual handler inventory +// is generated by httpx.InspectApp through the same registrar as NewHandler. func InspectBag(app map[string]any, declared []ArtifactFile) map[string]any { - var dec []map[string]any - for _, a := range declared { - dec = append(dec, map[string]any{ - "method": a.Method, - "path": a.Route, - "kind": a.Kind, - "file": a.Rel, - }) + entries := map[string]map[string]any{} + add := func(row map[string]any) { + path := first(row, "path") + method := first(row, "method") + if method == "" { + method = "GET" + } + if path == "" { + return + } + key := method + " " + path + if _, exists := entries[key]; !exists { + entries[key] = row + } + } + for _, file := range declared { + add(map[string]any{"method": file.Method, "path": file.Route, "kind": file.Kind, "file": file.Rel}) } if app != nil { + switch rows := app["artifact_declared"].(type) { + case []map[string]any: + for _, row := range rows { + add(row) + } + case []any: + for _, value := range rows { + if row, ok := value.(map[string]any); ok { + add(row) + } + } + } + if app["page"] != nil { + add(map[string]any{"method": "GET", "path": "/", "kind": "document"}) + } if routes, ok := app["routes"].(map[string]any); ok { for path := range routes { - dec = append(dec, map[string]any{"method": "GET", "path": path, "kind": "declared"}) + add(map[string]any{"method": "GET", "path": path, "kind": "document"}) } } - if inv, ok := app["invoke_routes"].(map[string]any); ok { - for key, v := range inv { - row := map[string]any{"path": key, "kind": "endpoint"} - if m, ok := v.(map[string]any); ok { - if c, ok := m["class"].(string); ok && c != "" { - row["class"] = c + for _, group := range []string{"artifact_routes", "invoke_routes"} { + if routes, ok := app[group].(map[string]any); ok { + for key, value := range routes { + spec, _ := value.(map[string]any) + method, path := first(spec, "method"), first(spec, "path") + if parts := strings.SplitN(key, " ", 2); len(parts) == 2 { + if method == "" { + method = parts[0] + } + if path == "" { + path = parts[1] + } + } else if path == "" { + path = key } - if method, ok := m["method"].(string); ok && method != "" { - row["method"] = method + if method == "" { + method = "GET" } - if fn, ok := m["fn"].(string); ok && fn != "" { - row["fn"] = fn + row := map[string]any{"method": method, "path": path, "kind": "endpoint"} + for _, name := range []string{"file", "class", "fn"} { + if value := first(spec, name); value != "" { + row[name] = value + } } + add(row) } - dec = append(dec, row) - } - } - if art, ok := app["artifact_routes"].(map[string]any); ok { - for key, v := range art { - m, _ := v.(map[string]any) - dec = append(dec, map[string]any{ - "path": key, - "kind": "endpoint", - "method": fmt.Sprint(m["method"]), - "file": fmt.Sprint(m["file"]), - }) } } } - return map[string]any{ - "_type": "web_inspection", - "declared": dec, - "system": SystemRoutes(), + keys := make([]string, 0, len(entries)) + for key := range entries { + keys = append(keys, key) } + sort.Strings(keys) + rows := make([]map[string]any, 0, len(keys)) + for _, key := range keys { + rows = append(rows, entries[key]) + } + return map[string]any{"_type": "web_inspection", "scope": "metadata", "declared": rows, "system": SystemRoutes()} } diff --git a/plugins/web/internal/artifact/artifact_test.go b/plugins/web/internal/artifact/artifact_test.go index 4a0e8d7..51d3967 100644 --- a/plugins/web/internal/artifact/artifact_test.go +++ b/plugins/web/internal/artifact/artifact_test.go @@ -142,3 +142,48 @@ func TestViewDocumentRejectsAnEmptyAssemblyAndAutomaticDataSource(t *testing.T) t.Fatalf("data source silently ignored: %v", err) } } + +func TestInteractiveControlsUseTypedAttributesAndEscapedText(t *testing.T) { + nodes := []any{map[string]any{"type":"form", "attrs":map[string]any{"id":"editor", "method":"post", "action":"/save"}, "value":[]any{ + map[string]any{"type":"label", "value":"Title", "attrs":map[string]any{"for":"title"}}, + map[string]any{"type":"input", "value":`">`, "attrs":map[string]any{"id":"title", "name":"title", "required":true, "disabled":false, "maxlength":float64(120)}}, + map[string]any{"type":"textarea", "value":"", "attrs":map[string]any{"id":"doc", "rows":float64(16), "aria-label":"Document"}}, + map[string]any{"type":"button", "value":"Save & return", "attrs":map[string]any{"type":"submit", "data-action":"save"}}, + map[string]any{"类型":"预格式", "值":"", "属性":map[string]any{"id":"log","hidden":false}}, + }}} + got,err := RenderNodes(nodes) + if err != nil { t.Fatal(err) } + for _, expected := range []string{`") || strings.Contains(got," disabled") || strings.Contains(got," hidden") || strings.Contains(got,"map[") { t.Fatalf("control values leaked into markup: %s",got) } +} +func TestAttributeRecordsApplyToContainersAndLinks(t *testing.T) { + got,err:=RenderNodes([]any{map[string]any{"type":"section","attrs":map[string]any{"id":"view-detail","hidden":true},"value":[]any{ + map[string]any{"type":"link","value":"Open","attrs":map[string]any{"href":"/a?x=1&y=2","title":"Detail"}}, + }}}) + if err != nil || !strings.Contains(got,`id="view-detail"`) || !strings.Contains(got," hidden") || !strings.Contains(got,`href="/a?x=1&y=2"`) { t.Fatalf("%v: %s",err,got) } + for _,attrs:=range []map[string]any{ + {"onclick":"alert(1)"},{"style":"position:fixed"},{"data-x\" onload":"x"},{"href":"javascript:alert(1)"},{"required":"true"},{"title":[]any{"nested"}}, + } { + if _,err:=RenderNodes([]any{map[string]any{"type":"button","value":"Run","attrs":attrs}});err==nil { t.Fatalf("accepted invalid attributes: %v",attrs) } + } +} + +func TestResourcesStayStructuredAndEscapeTheirURLs(t *testing.T) { + got,err:=RenderNodes([]any{ + map[string]any{"type":"script","value":"/static/marqdo-bridge.js","attrs":map[string]any{"type":"module","data-mq-wasm":"/static/runtime.wasm","data-mq-source-url":"/static/client.mq.md"}}, + map[string]any{"type":"stylesheet","value":"/static/theme.css?x=1&y=2"}, + }) + if err!=nil {t.Fatal(err)} + for _,want:=range []string{``, + } { + if !strings.Contains(head, want) { + t.Fatalf("missing %s: %s", want, head) + } + } + if strings.Count(head, `href="/theme.css`) != 1 || strings.Count(head, `src="/client.js"`) != 1 { + t.Fatal("duplicate head resource: " + head) + } + if strings.Contains(body, "Actual OG") || strings.Contains(body, "fonts.example") || strings.Contains(body, "slot-head") || !strings.Contains(body, "Actual page") { + t.Fatal(body) + } + calls := 0 + fragment, err := RenderNodesWithResources(nodes, func(map[string]any) (string, error) { calls++; return "unexpected", nil }) + if err != nil || calls != 0 || strings.Contains(fragment, "x"}, + {"_type": "document_head", "body_class": "admin"}, + {"_type": "document_head", "meta": []any{42}}, + {"_type": "document_head", "meta": map[string]any{"key": []any{"a", "b"}, "value": []any{"one"}}}, + {"_type": "document_head", "meta": map[string]any{"key": "description", "value": []any{"nested"}}}, + {"_type": "document_head", "meta": map[string]any{"key": "viewport", "value": "owned"}}, + {"_type": "document_head", "meta": []any{map[string]any{"key": "description", "value": "a"}, map[string]any{"key": "description", "value": "b"}}}, + {"_type": "document_head", "links": []any{map[string]any{"rel": "script", "href": "/a.js", "onclick": "x"}}}, + {"_type": "document_head", "links": []any{map[string]any{"rel": "stylesheet", "href": "/a.css", "media": map[string]any{"x": "nested"}}}}, + {"_type": "document_head", "links": []any{map[string]any{"rel": "stylesheet"}}}, + } { + if _, err := ParseDocumentHead(resource); err == nil { + t.Fatalf("accepted %#v", resource) + } + } + if _, err := ParseDocumentHead(valid); err != nil { + t.Fatal(err) + } + for _, url := range []string{"javascript:alert(1)", "data:text/javascript,x", "//other.test/a", "relative.css", "/\\other.test/a", "https://", "/a\n.js"} { + for _, resource := range []map[string]any{ + {"_type": "document_head", "links": []any{map[string]any{"rel": "script", "href": url}}}, + {"_type": "document_head", "meta": map[string]any{"key": "canonical", "value": url}}, + } { + if _, err := ParseDocumentHead(resource); err == nil { + t.Fatalf("accepted %q", url) + } + } + } + conflict := []any{headNode(map[string]any{"key": "description", "value": "first"}, nil), + map[string]any{"类型": "纵排", "值": []any{headNode(map[string]any{"键": "description", "值": "second"}, nil)}}} + if _, err := CollectDocumentHead(conflict); err == nil { + t.Fatal("nested head conflict silently overwrote metadata") + } + private := []any{map[string]any{"type": "resource", "value": map[string]any{"_type": "data_query", "where": headNode(nil, nil)}}} + head, err := CollectDocumentHead(private) + if err != nil || len(head.Links) != 0 || len(head.Meta) != 0 { + t.Fatalf("walked private Resource: %v %#v", err, head) + } + var deep any = []any{headNode(nil, nil)} + for i := 0; i < 66; i++ { + deep = []any{map[string]any{"type": "row", "value": deep}} + } + if _, err := CollectDocumentHead(deep); err == nil { + t.Fatal("unbounded head traversal") + } +} diff --git a/plugins/web/internal/artifact/slot_test.go b/plugins/web/internal/artifact/slot_test.go new file mode 100644 index 0000000..eae79fb --- /dev/null +++ b/plugins/web/internal/artifact/slot_test.go @@ -0,0 +1,41 @@ +package artifact + +import ( + "strings" + "testing" +) + +func TestFindSlotKeepsNestedTypedResourcesAndRejectsAmbiguity(t *testing.T) { + descriptor := map[string]any{"_type": "data_query", "source": "articles", "slot": "not-a-view-slot"} + nodes := []any{map[string]any{"type": "row", "slot": "layout", "value": []any{ + map[string]any{"类型": "纵排", "槽": "main", "值": []any{ + map[string]any{"type": "resource", "slot": "articles", "value": descriptor}, + }}, + map[string]any{"type": "markdown", "slot": "sidebar", "value": "Separate"}, + }}} + selected, found, err := FindSlot(nodes, "articles") + if err != nil || !found { + t.Fatalf("%v %v", found, err) + } + calls := 0 + html, err := RenderNodesWithResources(selected, func(value map[string]any) (string, error) { + calls++ + if value["source"] != "articles" { + t.Fatal(value) + } + return "

        Actual request value

        ", nil + }) + if err != nil || calls != 1 || !strings.Contains(html, "Actual request value") || strings.Contains(html, "Separate") { + t.Fatalf("%d %v %s", calls, err, html) + } + if _, found, err := FindSlot(nodes, "not-a-view-slot"); err != nil || found { + t.Fatalf("walked Resource internals: %v %v", found, err) + } + duplicate := append(nodes, map[string]any{"type": "text", "slot": "articles", "value": "Ambiguous"}) + if _, _, err := FindSlot(duplicate, "articles"); err == nil { + t.Fatal("duplicate slot accepted") + } + if _, _, err := FindSlot([]any{42}, "articles"); err == nil { + t.Fatal("malformed View accepted") + } +} diff --git a/plugins/web/internal/httpx/auth.go b/plugins/web/internal/httpx/auth.go index 9612fde..98dafd8 100644 --- a/plugins/web/internal/httpx/auth.go +++ b/plugins/web/internal/httpx/auth.go @@ -6,11 +6,13 @@ import ( "io" "net" "net/http" + "net/url" "strconv" "strings" "github.com/marqdo/marqdo/plugins/web/internal/app" "github.com/marqdo/marqdo/plugins/web/internal/auth" + "github.com/marqdo/marqdo/plugins/web/internal/db" "github.com/marqdo/marqdo/plugins/web/internal/password" "github.com/marqdo/marqdo/plugins/web/internal/ratelimit" "github.com/marqdo/marqdo/plugins/web/internal/rbac" @@ -372,7 +374,7 @@ func (st *state) hasPageRoute(path string) bool { return ok } -func (st *state) mountAuthRoutes(mux *http.ServeMux) { +func (st *state) mountAuthRoutes(mux routeRegistrar) { st.mountOIDCRoutes(mux) if st.auth.users == nil && !(st.auth.rbac && st.auth.register) && !st.oidcEnabled() { return @@ -416,6 +418,9 @@ func (st *state) mountAuthRoutes(mux *http.ServeMux) { if adminHome == "" { adminHome = "/admin" } + // The canonical no-slash path must be registered too: the global + // trailing-slash normalizer otherwise triggers a ServeMux redirect loop. + mux.HandleFunc("GET "+adminHome, st.handleAdminHome) mux.HandleFunc("GET "+adminHome+"/{$}", st.handleAdminHome) } } @@ -501,7 +506,6 @@ func (st *state) handleLoginPost(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, dest, http.StatusSeeOther) } - // tryLogin: GFM users first, then web_users when RBAC is on. func (st *state) tryLogin(username, password string) map[string]any { if st.auth.users != nil { @@ -558,8 +562,45 @@ func (st *state) handleLogout(w http.ResponseWriter, r *http.Request) { } func (st *state) handleAdminHome(w http.ResponseWriter, r *http.Request) { + // Only explicitly mounted forms expose their associated business tables. + // Never enumerate session/credential tables just because they share a DB. + var body strings.Builder + body.WriteString(`Admin

        Admin

        Mounted forms and their current business records (up to 100 rows per table).

        `) + seen := map[string]bool{} + for _, id := range sortedKeys(st.forms) { + selected, ok := st.forms[id].(map[string]any) + if !ok { + continue + } + tableName, _ := selected["table"].(string) + fmt.Fprintf(&body, `

        %s

        Open form

        `, esc(id), esc(url.PathEscape(id))) + if tableName != "" && st.dbURL != "" && !seen[tableName] { + current, err := db.Select(st.dbURL, tableName, 100, db.SelectOpts{}) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + var data strings.Builder + encoder := json.NewEncoder(&data) + encoder.SetIndent("", " ") + encoder.SetEscapeHTML(false) + if err := encoder.Encode(current["rows"]); err != nil { + http.Error(w, "cannot encode admin records", http.StatusInternalServerError) + return + } + // Escape once for HTML, preserving readable literal angle brackets + // instead of displaying JSON's optional Unicode escape sequences. + fmt.Fprintf(&body, `

        %s

        %s
        `, esc(tableName), esc(data.String())) + seen[tableName] = true + } + body.WriteString("
        ") + } + if len(st.forms) == 0 { + body.WriteString("

        No forms are mounted.

        ") + } + body.WriteString("") w.Header().Set("Content-Type", "text/html; charset=utf-8") - _, _ = io.WriteString(w, "

        Admin

        Site administration.

        ") + _, _ = io.WriteString(w, body.String()) } func loginDest(r *http.Request, fallback string) string { diff --git a/plugins/web/internal/httpx/auth_custom.go b/plugins/web/internal/httpx/auth_custom.go index e9f346e..2c94394 100644 --- a/plugins/web/internal/httpx/auth_custom.go +++ b/plugins/web/internal/httpx/auth_custom.go @@ -114,7 +114,7 @@ func (st *state) writeRegisterFailure(w http.ResponseWriter, r *http.Request, ms _, _ = io.WriteString(w, registerPageHTML(st.auth.registerPath, &loc, csrf)) } -func (st *state) mountExtraLoginPosts(mux *http.ServeMux, already map[string]bool) { +func (st *state) mountExtraLoginPosts(mux routeRegistrar, already map[string]bool) { for path, pageV := range st.routes { if already[path] { continue diff --git a/plugins/web/internal/httpx/auth_oidc.go b/plugins/web/internal/httpx/auth_oidc.go index a9f87c2..9f8e68f 100644 --- a/plugins/web/internal/httpx/auth_oidc.go +++ b/plugins/web/internal/httpx/auth_oidc.go @@ -74,7 +74,7 @@ func (st *state) oidcFallbackNext(r *http.Request) string { return "/" } -func (st *state) mountOIDCRoutes(mux *http.ServeMux) { +func (st *state) mountOIDCRoutes(mux routeRegistrar) { if !st.oidcEnabled() { return } diff --git a/plugins/web/internal/httpx/helpers_test.go b/plugins/web/internal/httpx/helpers_test.go index 6f01dfd..8b538ee 100644 --- a/plugins/web/internal/httpx/helpers_test.go +++ b/plugins/web/internal/httpx/helpers_test.go @@ -56,4 +56,3 @@ func TestResolveSessionReplacesStaleCookie(t *testing.T) { t.Fatalf("live session should not Set-Cookie again") } } - diff --git a/plugins/web/internal/httpx/inspection.go b/plugins/web/internal/httpx/inspection.go new file mode 100644 index 0000000..0b225be --- /dev/null +++ b/plugins/web/internal/httpx/inspection.go @@ -0,0 +1,171 @@ +package httpx + +import ( + "fmt" + "net/http" + "regexp" + "sort" + "strings" + + "github.com/marqdo/marqdo/plugins/web/internal/app" + "github.com/marqdo/marqdo/plugins/web/internal/artifact" + "github.com/marqdo/marqdo/plugins/web/internal/middleware" + "github.com/marqdo/marqdo/plugins/web/internal/oidc" +) + +type recordedMux struct { + validate *http.ServeMux + patterns []string +} + +func (mux *recordedMux) Handle(pattern string, _ http.Handler) { + // Validate registration conflicts without retaining or running handlers. + mux.validate.HandleFunc(pattern, func(http.ResponseWriter, *http.Request) {}) + mux.patterns = append(mux.patterns, pattern) +} +func (mux *recordedMux) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) { + mux.Handle(pattern, http.HandlerFunc(handler)) +} + +var tailWildcard = regexp.MustCompile(`\{([^{}]+)\.\.\.\}`) + +func inspectionPath(path string) string { + path = strings.TrimSuffix(path, "{$}") + return tailWildcard.ReplaceAllString(path, "{*$1}") +} + +// InspectApp executes only trusted registration logic. It does not create a +// session, reset global runtime state, query a DB, run Documents or listen. +func InspectApp(bag map[string]any) (report map[string]any, err error) { + defer func() { + if recovered := recover(); recovered != nil { + report = nil + err = fmt.Errorf("web.inspect: invalid route registration: %v", recovered) + } + }() + if bag == nil { + bag = map[string]any{} + } + routes := routeMapOf(bag, "routes") + page, _ := bag["page"].(map[string]any) + forms := map[string]any{} + if existing, ok := bag["forms"].(map[string]any); ok { + for key, value := range existing { + forms[key] = value + } + } + collectPageForms(page, forms) + for _, value := range routes { + if page, ok := value.(map[string]any); ok { + collectPageForms(page, forms) + } + } + root := strOpt(bag, "artifact_root", "") + staticDir := strOpt(bag, "static_dir", "") + if staticDir != "" { + staticDir = resolvePath(staticDir, root) + } + icons, err := iconRoutesFromBag(bag, root, staticDir) + if err != nil { + return nil, err + } + st := &state{ + page: page, routes: routes, forms: forms, mw: middleware.Parse(bag), entryDir: root, + iconRoutes: icons, redirects: redirectsOf(bag), sitemapRoutes: sitemapRoutesOf(bag), + robotsBody: robotsBodyOf(bag), page404: pageOf(bag, "page_404"), page500: pageOf(bag, "page_500"), + uploadRoutes: routeMapOf(bag, "upload_routes"), downloadRoutes: routeMapOf(bag, "download_routes"), + wsRoutes: routeMapOf(bag, "ws_routes"), galleryRoutes: routeMapOf(bag, "gallery_routes"), + proxyRoutes: routeMapOf(bag, "proxy_routes"), invokeRoutes: routeMapOf(bag, "invoke_routes"), + artifactRoutes: routeMapOf(bag, "artifact_routes"), auth: authConfigOf(bag), oidc: oidc.ParseConfig(bag), + } + // Only a nonempty DB URL determines whether DB-backed routes are enabled. + // Its existence and contents are intentionally not inspected here. + st.dbURL = dbURLOf(bag) + staticMount := app.NormalizeStaticMount(strOpt(bag, "static_mount", "/static")) + mux := &recordedMux{validate: http.NewServeMux()} + st.registerRoutes(mux, staticDir, staticMount, false) + report = artifact.InspectBag(bag, nil) + declarations := map[string]map[string]any{} + byPath := map[string]map[string]any{} + for _, row := range report["declared"].([]map[string]any) { + path := inspectionPath(goMuxPattern(fmt.Sprint(row["path"]))) + method := fmt.Sprint(row["method"]) + declarations[method+" "+path] = row + if _, exists := byPath[path]; !exists { + byPath[path] = row + } + } + // Classification uses the explicitly supplied Resource paths; the method + // and presence still come from the actual recorded registration. + for group, kind := range map[string]string{ + "ws_routes": "websocket", "upload_routes": "upload", "download_routes": "download", + "gallery_routes": "gallery", "proxy_routes": "proxy", "redirects": "redirect", "sitemap_routes": "sitemap", + } { + for key, value := range routeMapOf(bag, group) { + spec, _ := value.(map[string]any) + path := strOpt(spec, "path", key) + if parts := strings.SplitN(path, " ", 2); len(parts) == 2 { + path = parts[1] + } + path = inspectionPath(goMuxPattern(path)) + byPath[path] = map[string]any{"path": path, "kind": kind} + } + } + for _, query := range st.mw.JSONRoutes { + row := map[string]any{"path": query.Path, "method": query.Method, "kind": "data_query"} + declarations[query.Method+" "+query.Path] = row + } + var declared, system []map[string]any + seen := map[string]bool{} + for _, pattern := range mux.patterns { + method, path := "*", pattern + if parts := strings.SplitN(pattern, " ", 2); len(parts) == 2 { + method, path = parts[0], parts[1] + } + path = inspectionPath(path) + if method == "*" && (path == staticMount || path == staticMount+"/") && strOpt(bag, "static_dir", "") != "" { + method = "GET|HEAD" + } + key := method + " " + path + if seen[key] { + continue + } + seen[key] = true + row := map[string]any{"method": method, "path": path, "kind": "system"} + source, found := declarations[key] + if !found { + source, found = byPath[path] + } + if found { + for key, value := range source { + if key != "method" && key != "path" { + row[key] = value + } + } + declared = append(declared, row) + } else { + system = append(system, row) + } + } + less := func(rows []map[string]any) { + sort.Slice(rows, func(i, j int) bool { + a, b := fmt.Sprint(rows[i]["path"]), fmt.Sprint(rows[j]["path"]) + if a != b { + return a < b + } + return fmt.Sprint(rows[i]["method"]) < fmt.Sprint(rows[j]["method"]) + }) + } + less(declared) + less(system) + if declared == nil { + declared = []map[string]any{} + } + if system == nil { + system = []map[string]any{} + } + report["scope"] = "registered" + report["declared"] = declared + report["system"] = system + return report, nil +} diff --git a/plugins/web/internal/httpx/inspection_test.go b/plugins/web/internal/httpx/inspection_test.go new file mode 100644 index 0000000..735210f --- /dev/null +++ b/plugins/web/internal/httpx/inspection_test.go @@ -0,0 +1,101 @@ +package httpx + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/marqdo/marqdo/plugins/web/internal/app" + "github.com/marqdo/marqdo/plugins/web/internal/form" + "github.com/marqdo/marqdo/plugins/web/internal/session" +) + +func TestInspectionUsesActualRegistrationsAfterResourceBindingsWithoutExecutingThem(t *testing.T) { + filename := filepath.Join(t.TempDir(), "must-not-create.db") + bag := app.New(map[string]any{"page": map[string]any{"title": "Home"}, + "db": map[string]any{"url": "sqlite:" + filename}, "admin": true}) + bag["artifact_declared"] = []any{map[string]any{"method": "GET", "path": "/", "kind": "web", "file": "index.mq.md"}} + // A cached observation is deliberately stale and must never be returned. + bag["inspect"] = map[string]any{"declared": []any{map[string]any{"path": "/stale"}}} + var err error + bag, err = app.Route(bag, "/post/{id}", map[string]any{"title": "Post"}) + if err != nil { + t.Fatal(err) + } + before, err := InspectApp(bag) + if err != nil { + t.Fatal(err) + } + bag, err = app.Auth(bag, []any{map[string]any{"username": "fixture", "password": "never-return-this-secret"}}, map[string]any{"login_path": "/members/login"}) + if err != nil { + t.Fatal(err) + } + bag, err = app.MountForm(bag, "article", form.New("articles", "insert", "")) + if err != nil { + t.Fatal(err) + } + bag["ws_routes"] = map[string]any{"/live/{id}": map[string]any{"mode": "echo"}} + bag["middleware"] = map[string]any{"json_routes": map[string]any{"api/items": map[string]any{"table": "items", "method": "GET"}}} + bag["artifact_routes"] = map[string]any{"GET /api/ping": map[string]any{"method": "GET", "path": "/api/ping", "file": "/never-run.mq.md"}} + bag["static_dir"] = "." + bag["static_mount"] = "/assets" + session.Configure(session.Config{TTLSec: 3600}) + session.Reset(3600) + sid := session.NewID(3600) + session.SetValue(sid, "inspection_marker", "retained") + report, err := InspectApp(bag) + if err != nil { + t.Fatal(err) + } + if report["scope"] != "registered" { + t.Fatal(report) + } + type route struct{ method, path string } + observed := map[route]string{} + for _, group := range []string{"declared", "system"} { + for _, row := range report[group].([]map[string]any) { + key := route{row["method"].(string), row["path"].(string)} + if _, seen := observed[key]; seen { + t.Fatalf("duplicate registered route: %#v", key) + } + observed[key] = group + } + } + for _, key := range []route{{"GET", "/"}, {"GET", "/post/{id}"}, {"GET", "/live/{id}"}, {"GET", "/api/items"}, {"GET", "/api/ping"}} { + if observed[key] != "declared" { + t.Fatalf("missing current Resource declaration %#v: %#v", key, report) + } + } + for _, key := range []route{{"POST", "/_md"}, {"GET", "/_form/{id}"}, {"POST", "/_form/{id}"}, + {"GET", "/post/{id}/_part/{part}"}, {"GET", "/members/login"}, {"POST", "/members/login"}, + {"GET", "/admin/login"}, {"GET", "/admin"}, {"GET", "/admin/"}, {"GET|HEAD", "/assets/"}} { + if observed[key] != "system" { + t.Fatalf("missing actual system route %#v: %#v", key, report) + } + } + encoded, _ := json.Marshal(report) + if strings.Contains(string(encoded), "never-return-this-secret") || strings.Contains(string(encoded), "/stale") { + t.Fatalf("inspection leaked unrelated app state: %s", encoded) + } + if value, ok := session.GetValue(sid, "inspection_marker"); !ok || value != "retained" { + t.Fatal("inspection reset runtime sessions") + } + if _, err := os.Stat(filename); !os.IsNotExist(err) { + t.Fatalf("inspection opened a database: %v", err) + } + prior, _ := json.Marshal(before) + if strings.Contains(string(prior), "/live/") { + t.Fatal("inspection mutated an earlier returned observation") + } +} + +func TestInspectionRejectsActualRouteConflictsWithoutStartingTheServer(t *testing.T) { + bag := app.New(map[string]any{"page": map[string]any{}}) + bag["routes"] = map[string]any{"/_md": map[string]any{}} + bag["artifact_routes"] = map[string]any{"POST /_md": map[string]any{"method": "POST", "path": "/_md", "file": "never-run.mq.md"}} + if _, err := InspectApp(bag); err == nil || !strings.Contains(err.Error(), "invalid route registration") { + t.Fatalf("conflicting routes were advertised as usable: %v", err) + } +} diff --git a/plugins/web/internal/httpx/listen.go b/plugins/web/internal/httpx/listen.go index 8c9bbd2..f081991 100644 --- a/plugins/web/internal/httpx/listen.go +++ b/plugins/web/internal/httpx/listen.go @@ -18,6 +18,7 @@ import ( "time" "github.com/marqdo/marqdo/plugins/web/internal/app" + "github.com/marqdo/marqdo/plugins/web/internal/artifact" "github.com/marqdo/marqdo/plugins/web/internal/assets" "github.com/marqdo/marqdo/plugins/web/internal/db" "github.com/marqdo/marqdo/plugins/web/internal/form" @@ -129,6 +130,23 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) { } mux := http.NewServeMux() + st.registerRoutes(mux, staticDir, staticMount, true) + + handler := withMiddleware(mux, mw) + handler = withRBAC(handler, authCfg.gates, authCfg.loginPath) + handler = withTenant(handler, st.tenant) + handler = withStripTrailingSlash(handler) + return handler, nil +} + +// routeRegistrar is shared by the real server and its read-only inventory. +// Recording registrations does not invoke any captured handler. +type routeRegistrar interface { + Handle(string, http.Handler) + HandleFunc(string, func(http.ResponseWriter, *http.Request)) +} + +func (st *state) registerRoutes(mux routeRegistrar, staticDir, staticMount string, logSetup bool) { mux.HandleFunc("GET /{$}", st.handleHome) // Part slot uses {part} (not {id}) so dynamic routes like /desk/posts/{id} // do not collide with Go ServeMux duplicate wildcard names. @@ -137,10 +155,10 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) { mux.HandleFunc("POST /_form/{id}", st.handleFormPost) mux.HandleFunc("POST /_md", st.handleMarkdownPreview) - paths := sortedKeys(routes) + paths := sortedKeys(st.routes) for _, p := range paths { routePath := p - pageV, _ := routes[routePath].(map[string]any) + pageV, _ := st.routes[routePath].(map[string]any) if pageV == nil { pageV = map[string]any{} } @@ -158,7 +176,7 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) { } } - for _, jr := range mw.JSONRoutes { + for _, jr := range st.mw.JSONRoutes { route := jr pattern := route.Method + " " + route.Path mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { @@ -168,16 +186,20 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) { // Icon routes before the static prefix so /static/favicon.svg does not // conflict with Go 1.22+ ServeMux method/path overlap rules. - for _, ir := range iconRoutes { + for _, ir := range st.iconRoutes { url := ir.URL path := ir.Path ct := ir.ContentType if staticDir != "" && (url == staticMount || strings.HasPrefix(url, staticMount+"/")) { // FileServer under staticMount already serves these paths. - fmt.Fprintf(os.Stderr, "marqdo web icon: %s → static %s (via %s)\n", url, path, staticMount) + if logSetup { + fmt.Fprintf(os.Stderr, "marqdo web icon: %s → static %s (via %s)\n", url, path, staticMount) + } continue } - fmt.Fprintf(os.Stderr, "marqdo web icon: %s → %s (%s)\n", url, path, ct) + if logSetup { + fmt.Fprintf(os.Stderr, "marqdo web icon: %s → %s (%s)\n", url, path, ct) + } mux.HandleFunc("GET "+url, func(w http.ResponseWriter, r *http.Request) { st.serveIcon(w, path, ct) }) @@ -187,7 +209,9 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) { } if staticDir != "" { - fmt.Fprintf(os.Stderr, "marqdo web static: %s → %s\n", staticMount, staticDir) + if logSetup { + fmt.Fprintf(os.Stderr, "marqdo web static: %s → %s\n", staticMount, staticDir) + } fs := http.StripPrefix(staticMount, http.FileServer(http.Dir(staticDir))) // Register without method so GET+HEAD share one pattern (avoids conflicts // with more-specific GET/HEAD icon paths under the same prefix). @@ -245,11 +269,6 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) { mux.HandleFunc("/{path...}", st.handleNotFound) - handler := withMiddleware(mux, mw) - handler = withRBAC(handler, authCfg.gates, authCfg.loginPath) - handler = withTenant(handler, st.tenant) - handler = withStripTrailingSlash(handler) - return handler, nil } // Listen binds host:port from the app bag and serves until interrupt/kill. @@ -392,7 +411,19 @@ func (st *state) writePage(w http.ResponseWriter, r *http.Request, page map[stri p["_auth_next"] = next } setCookie := st.attachCSRF(p, r) - html := render.RenderPage(p, st.dbURL, "") + html := "" + if nodes, ok := p["artifact_nodes"]; ok { + document, err := artifact.RenderViewDocument(strOpt(p, "title", ""), nodes, func(resource map[string]any) (string, error) { + return st.renderViewResource(resource, p, r) + }) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + html = document + } else { + html = render.RenderPage(p, st.dbURL, "") + } w.Header().Set("Content-Type", "text/html; charset=utf-8") appendSetCookie(w, setCookie) _, _ = io.WriteString(w, html) @@ -401,7 +432,32 @@ func (st *state) writePage(w http.ResponseWriter, r *http.Request, page map[stri func (st *state) writePart(w http.ResponseWriter, r *http.Request, page map[string]any, id string) { p := st.preparePage(page, r) setCookie := st.attachCSRF(p, r) - html := render.RenderPage(p, st.dbURL, id) + html := "" + if nodes, ok := p["artifact_nodes"]; ok { + selected, found, err := artifact.FindSlot(nodes, id) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if !found { + if id != "main" { + http.NotFound(w, r) + return + } + // Keep the existing main-fragment fallback for a View without a + // named main region; never expose the Document's program source. + selected = nodes + } + html, err = artifact.RenderNodesWithResources(selected, func(resource map[string]any) (string, error) { + return st.renderViewResource(resource, p, r) + }) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + } else { + html = render.RenderPage(p, st.dbURL, id) + } w.Header().Set("Content-Type", "text/html; charset=utf-8") appendSetCookie(w, setCookie) _, _ = io.WriteString(w, html) @@ -500,7 +556,11 @@ func (st *state) handleFormGet(w http.ResponseWriter, r *http.Request) { _, _ = io.WriteString(w, fmt.Sprintf("

        unknown form %s

        ", id)) return } - html := form.Render(frm, id, nil, nil, "") + page := map[string]any{} + setCookie := st.attachCSRF(page, r) + csrf, _ := page["_csrf"].(string) + html := form.Render(frm, id, nil, nil, csrf) + appendSetCookie(w, setCookie) w.Header().Set("Content-Type", "text/html; charset=utf-8") _, _ = io.WriteString(w, html) } @@ -522,6 +582,19 @@ func (st *state) handleFormPost(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusBadRequest) return } + csrf := "" + if st.auth.users != nil || st.auth.rbac || st.oidcEnabled() { + sid, token, setCookie := resolveSession(r) + appendSetCookie(w, setCookie) + csrf = token + _, hadCookie := session.IDFromCookie(r.Header.Get("Cookie")) + if hadCookie || r.FormValue("_csrf") != "" { + if !session.ValidateCSRF(sid, r.FormValue("_csrf")) { + http.Error(w, "Invalid or missing CSRF token", http.StatusForbidden) + return + } + } + } data := map[string]any{} for k, vs := range r.PostForm { if len(vs) > 0 { @@ -547,13 +620,13 @@ func (st *state) handleFormPost(w http.ResponseWriter, r *http.Request) { // Prefer an explicit form redirect (e.g. cancel_href list URL) over the // composing page path stamped as _mq_return. redir := strOpt(res, "redirect", "/") - if (redir == "" || redir == "/") && ctx.ReturnPath != "" { + if (redir == "" || redir == "/") && ctx.ReturnPath != "" && strOpt(frm, "cancel_href", "") == "" { redir = ctx.ReturnPath } http.Redirect(w, r, redir, http.StatusSeeOther) return } - html := form.RenderBodyCtx(frm, id, data, res["errors"], "", ctx) + html := form.RenderBodyCtx(frm, id, data, res["errors"], csrf, ctx) w.Header().Set("Content-Type", "text/html; charset=utf-8") _, _ = io.WriteString(w, html) } diff --git a/plugins/web/internal/httpx/routes_artifact.go b/plugins/web/internal/httpx/routes_artifact.go index 61e361f..cce3288 100644 --- a/plugins/web/internal/httpx/routes_artifact.go +++ b/plugins/web/internal/httpx/routes_artifact.go @@ -33,7 +33,7 @@ func parseArtifactRoute(v any) artifactRoute { } } -func (st *state) mountArtifactRoutes(mux *http.ServeMux) { +func (st *state) mountArtifactRoutes(mux routeRegistrar) { for _, key := range sortedKeys(st.artifactRoutes) { cfg := parseArtifactRoute(st.artifactRoutes[key]) if cfg.File == "" || cfg.Path == "" { @@ -131,7 +131,7 @@ func (st *state) handleArtifact(w http.ResponseWriter, r *http.Request, route ar } } - value, err := plugin.RunArtifact(route.File, payload) + value, err := plugin.RunArtifactAtRoot(route.File, payload, st.entryDir) if err != nil { jsonErr(w, http.StatusInternalServerError, err.Error()) return diff --git a/plugins/web/internal/httpx/routes_invoke.go b/plugins/web/internal/httpx/routes_invoke.go index d3811a4..87dd249 100644 --- a/plugins/web/internal/httpx/routes_invoke.go +++ b/plugins/web/internal/httpx/routes_invoke.go @@ -63,7 +63,7 @@ func parseInvokeRoute(v any) invokeRoute { } } -func (st *state) mountInvokeRoutes(mux *http.ServeMux) { +func (st *state) mountInvokeRoutes(mux routeRegistrar) { for _, key := range sortedKeys(st.invokeRoutes) { cfg := parseInvokeRoute(st.invokeRoutes[key]) path := routePathKey(key) diff --git a/plugins/web/internal/httpx/routes_media.go b/plugins/web/internal/httpx/routes_media.go index db6e17a..b097370 100644 --- a/plugins/web/internal/httpx/routes_media.go +++ b/plugins/web/internal/httpx/routes_media.go @@ -47,7 +47,7 @@ func parseDownloadRoute(v any) downloadRoute { } } -func (st *state) mountUploadRoutes(mux *http.ServeMux) { +func (st *state) mountUploadRoutes(mux routeRegistrar) { for _, path := range sortedKeys(st.uploadRoutes) { routePath := path cfg := parseUploadRoute(st.uploadRoutes[path]) @@ -57,7 +57,7 @@ func (st *state) mountUploadRoutes(mux *http.ServeMux) { } } -func (st *state) mountDownloadRoutes(mux *http.ServeMux) { +func (st *state) mountDownloadRoutes(mux routeRegistrar) { for _, path := range sortedKeys(st.downloadRoutes) { routePath := path cfg := parseDownloadRoute(st.downloadRoutes[path]) @@ -68,7 +68,7 @@ func (st *state) mountDownloadRoutes(mux *http.ServeMux) { } } -func (st *state) mountGalleryRoutes(mux *http.ServeMux) { +func (st *state) mountGalleryRoutes(mux routeRegistrar) { for _, path := range sortedKeys(st.galleryRoutes) { cfg, _ := st.galleryRoutes[path].(map[string]any) mux.HandleFunc("GET "+path, func(w http.ResponseWriter, r *http.Request) { diff --git a/plugins/web/internal/httpx/routes_proxy.go b/plugins/web/internal/httpx/routes_proxy.go index e0c9047..872a5fb 100644 --- a/plugins/web/internal/httpx/routes_proxy.go +++ b/plugins/web/internal/httpx/routes_proxy.go @@ -90,7 +90,7 @@ func parseHeadersFromEnvStr(s string) []envHeader { return out } -func (st *state) mountProxyRoutes(mux *http.ServeMux) { +func (st *state) mountProxyRoutes(mux routeRegistrar) { for _, key := range sortedKeys(st.proxyRoutes) { cfg := parseProxyRoute(st.proxyRoutes[key]) path := routePathKey(key) diff --git a/plugins/web/internal/httpx/routes_runtime.go b/plugins/web/internal/httpx/routes_runtime.go index 9471913..8094446 100644 --- a/plugins/web/internal/httpx/routes_runtime.go +++ b/plugins/web/internal/httpx/routes_runtime.go @@ -13,7 +13,7 @@ import ( // System runtime control routes (M-R3 / M-R4). Cancel and event replay do not // enter the Marqdo interpreter lock. -func (st *state) mountRuntimeRoutes(mux *http.ServeMux) { +func (st *state) mountRuntimeRoutes(mux routeRegistrar) { mux.HandleFunc("POST /_runtime/tasks", st.handleRuntimeAdmit) mux.HandleFunc("GET /_runtime/tasks/{id}", st.handleRuntimeGet) mux.HandleFunc("POST /_runtime/tasks/{id}/cancel", st.handleRuntimeCancel) diff --git a/plugins/web/internal/httpx/routes_ws.go b/plugins/web/internal/httpx/routes_ws.go index c71fabf..3a5b662 100644 --- a/plugins/web/internal/httpx/routes_ws.go +++ b/plugins/web/internal/httpx/routes_ws.go @@ -28,7 +28,7 @@ func sameOrigin(r *http.Request) bool { return err == nil && strings.EqualFold(u.Host, r.Host) } -func (st *state) mountWSRoutes(mux *http.ServeMux) { +func (st *state) mountWSRoutes(mux routeRegistrar) { for _, path := range sortedKeys(st.wsRoutes) { spec := ws.ParseRouteSpec(st.wsRoutes[path]) // mode + optional room_key / on_message routePath := path diff --git a/plugins/web/internal/httpx/view_resources.go b/plugins/web/internal/httpx/view_resources.go new file mode 100644 index 0000000..c8069f4 --- /dev/null +++ b/plugins/web/internal/httpx/view_resources.go @@ -0,0 +1,185 @@ +package httpx + +import ( + "fmt" + "net/http" + "regexp" + "strings" + + "github.com/marqdo/marqdo/plugins/web/internal/artifact" + "github.com/marqdo/marqdo/plugins/web/internal/db" + "github.com/marqdo/marqdo/plugins/web/internal/form" + "github.com/marqdo/marqdo/plugins/web/internal/render" + "github.com/marqdo/marqdo/plugins/web/internal/tenant" +) + +// ValidateViewResource validates the closed Resource contracts without IO. +// Assembly calls this before listening; request rendering validates again. +func ValidateViewResource(resource map[string]any) (string, error) { + kind, _ := resource["_type"].(string) + switch kind { + case "document_head": + _, err := artifact.ParseDocumentHead(resource) + return "", err + case "data_query": + if source, ok := resource["source"].(string); !ok || strings.TrimSpace(source) == "" { + return "", fmt.Errorf("data_query: source must be a nonempty table name") + } + for _, key := range []string{"order", "link_prefix"} { + if value, exists := resource[key]; exists { + if _, ok := value.(string); !ok { + return "", fmt.Errorf("data_query: %s must be text", key) + } + } + } + for _, key := range []string{"detail", "tenant_scope"} { + if value, exists := resource[key]; exists { + if _, ok := value.(bool); !ok { + return "", fmt.Errorf("data_query: %s must be boolean", key) + } + } + } + if raw, exists := resource["limit"]; exists { + n, ok := raw.(float64) + if !ok || n < 1 || n > 1000 || n != float64(int64(n)) { + return "", fmt.Errorf("data_query: limit must be an integer in 1..1000") + } + } + if prefix, _ := resource["link_prefix"].(string); prefix != "" && (!strings.HasPrefix(prefix, "/") || strings.HasPrefix(prefix, "//")) { + return "", fmt.Errorf("data_query: link_prefix must be site-relative") + } + if where := resource["where"]; where != nil { + switch where.(type) { + case map[string]any, []any: + default: + return "", fmt.Errorf("data_query: where must be a native condition map or list") + } + } + case "form_ref": + if id, ok := resource["id"].(string); !ok || strings.TrimSpace(id) == "" { + return "", fmt.Errorf("form_ref: id must name an explicitly mounted form") + } + case "view_navigation": + region, _ := resource["region"].(string) + if region != "nav" && region != "sidebar" && region != "footer" { + return "", fmt.Errorf("view_navigation: region must be nav, sidebar or footer") + } + switch resource["items"].(type) { + case map[string]any, []any: + default: + return "", fmt.Errorf("view_navigation: items must be link records") + } + default: + return "", fmt.Errorf("unsupported View Resource %q", kind) + } + return "", nil +} + +var viewParameter = regexp.MustCompile(`\{([^{}]+)\}`) + +// Copy parameterized conditions without mutating the retained startup nodes. +func resourceWhere(value any, params map[string]any) (any, error) { + switch value := value.(type) { + case string: + var missing string + out := viewParameter.ReplaceAllStringFunc(value, func(token string) string { + key := token[1 : len(token)-1] + actual, ok := params[key] + if !ok { + missing = key + return token + } + return fmt.Sprint(actual) + }) + if missing != "" { + return nil, fmt.Errorf("data_query: missing route parameter %q", missing) + } + return out, nil + case map[string]any: + out := make(map[string]any, len(value)) + for key, item := range value { + resolved, err := resourceWhere(item, params) + if err != nil { + return nil, err + } + out[key] = resolved + } + return out, nil + case []any: + out := make([]any, len(value)) + for i, item := range value { + resolved, err := resourceWhere(item, params) + if err != nil { + return nil, err + } + out[i] = resolved + } + return out, nil + default: + return value, nil + } +} + +func (st *state) renderViewResource(resource, page map[string]any, request *http.Request) (string, error) { + if _, err := ValidateViewResource(resource); err != nil { + return "", err + } + switch resource["_type"] { + case "document_head": + return "", nil + case "data_query": + if st.dbURL == "" { + return "", fmt.Errorf("data_query: the application has no database resource") + } + params, _ := page["params"].(map[string]any) + where, err := resourceWhere(resource["where"], params) + if err != nil { + return "", err + } + scoped, _ := resource["tenant_scope"].(bool) + if scoped && !st.tenant.Enabled() { + return "", fmt.Errorf("data_query: scoped query requires a tenant policy") + } + if scoped || st.tenant.DefaultScope { + id := tenant.FromContext(request.Context()) + if id == "" { + return "", fmt.Errorf("data_query: tenant required") + } + where = tenant.MergeWhere(where, st.tenant.Column, id) + } + limit := int64(50) + if n, ok := resource["limit"].(float64); ok { + limit = int64(n) + } + order, _ := resource["order"].(string) + rows, err := db.Select(st.dbURL, resource["source"].(string), limit, db.SelectOpts{Where: where, Order: order}) + if err != nil { + return "", err + } + detail, _ := resource["detail"].(bool) + prefix, _ := resource["link_prefix"].(string) + return render.RenderQueryRows(rows["rows"], detail, prefix), nil + case "form_ref": + id := resource["id"].(string) + selected, ok := st.forms[id].(map[string]any) + if !ok { + return "", fmt.Errorf("form_ref: form %q was not explicitly mounted", id) + } + csrf, _ := page["_csrf"].(string) + return form.RenderBodyCtx(selected, id, nil, nil, csrf, st.requestContext(request, nil)), nil + case "view_navigation": + region := resource["region"].(string) + navigation := map[string]any{region: resource["items"]} + if region == "nav" { + navigation["nav"] = resource["items"] + } + if logged, ok := page["_logged_in"]; ok { + navigation["_logged_in"] = logged + } + if user, ok := page["_nav_user"]; ok { + navigation["_nav_user"] = user + } + return render.RenderPage(navigation, "", region), nil + } + return "", fmt.Errorf("unsupported View Resource") +} diff --git a/plugins/web/internal/httpx/view_resources_test.go b/plugins/web/internal/httpx/view_resources_test.go new file mode 100644 index 0000000..39bcaba --- /dev/null +++ b/plugins/web/internal/httpx/view_resources_test.go @@ -0,0 +1,205 @@ +package httpx + +import ( + "net/http" + "net/http/httptest" + "net/url" + "path/filepath" + "regexp" + "strings" + "testing" + + "github.com/marqdo/marqdo/plugins/web/internal/app" + "github.com/marqdo/marqdo/plugins/web/internal/artifact" + "github.com/marqdo/marqdo/plugins/web/internal/db" + "github.com/marqdo/marqdo/plugins/web/internal/form" + "github.com/marqdo/marqdo/plugins/web/internal/session" +) + +func resourceNode(resource map[string]any) map[string]any { + return map[string]any{"type": "resource", "value": resource, "slot": "content"} +} + +func TestViewResourcesObserveRequestsFormsAndNavigation(t *testing.T) { + uri := "sqlite:" + filepath.Join(t.TempDir(), "view.db") + fields := []any{ + map[string]any{"name": "id", "type": "integer", "nullable": false}, + map[string]any{"name": "title", "type": "text", "nullable": false}, + map[string]any{"name": "slug", "type": "text", "nullable": true}, + map[string]any{"name": "summary", "type": "text", "nullable": true}, + map[string]any{"name": "body", "type": "text", "nullable": true}, + } + if _, err := db.Init(uri, "articles", fields); err != nil { + t.Fatal(err) + } + if _, err := db.Insert(uri, "articles", map[string]any{ + "title": "Original ", "slug": "first", "summary": "Short summary", "body": "Full article body", + }); err != nil { + t.Fatal(err) + } + query := map[string]any{"_type": "data_query", "source": "articles", "limit": float64(50), "link_prefix": "/post/"} + navigation := map[string]any{"_type": "view_navigation", "region": "nav", "items": []any{ + map[string]any{"label": "Guest login", "href": "/admin/login", "when": "guest"}, + map[string]any{"label": "Private desk", "href": "/admin", "when": "auth"}, + }} + page := map[string]any{"title": "View resources", "artifact_nodes": []any{ + resourceNode(navigation), resourceNode(query), + resourceNode(map[string]any{"_type": "form_ref", "id": "article"}), + }} + bag := app.New(map[string]any{"page": page, "db": map[string]any{"url": uri}}) + var err error + bag, err = app.Auth(bag, []any{map[string]any{"username": "admin", "password": "secret", "role": "admin"}}, nil) + if err != nil { + t.Fatal(err) + } + selected := form.SetFields(form.New("articles", "insert", ""), fields[1:2]) + selected = form.SetRules(selected, []any{map[string]any{"field": "title", "rule": "required", "message": "Title required"}}) + selected = form.SetLabels(selected, "Publish", "Cancel", "/") + bag, err = app.MountForm(bag, "article", selected) + if err != nil { + t.Fatal(err) + } + detailed := map[string]any{"_type": "data_query", "source": "articles", "detail": true, + "where": map[string]any{"slug": "{slug}"}} + bag, err = app.Route(bag, "/post/{slug}", map[string]any{"title": "Article", "artifact_nodes": []any{resourceNode(detailed)}}) + if err != nil { + t.Fatal(err) + } + handler, err := NewHandler(bag, "") + if err != nil { + t.Fatal(err) + } + call := func(method, path, body, cookie string) *httptest.ResponseRecorder { + request := httptest.NewRequest(method, path, strings.NewReader(body)) + if body != "" { + request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } + if cookie != "" { + request.Header.Set("Cookie", cookie) + } + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + return recorder + } + initial := call("GET", "/", "", "") + if initial.Code != http.StatusOK { + t.Fatalf("initial: %d %s", initial.Code, initial.Body.String()) + } + text := initial.Body.String() + if !strings.Contains(text, "Guest login") || strings.Contains(text, "Private desk") || + !strings.Contains(text, "Short summary") || strings.Contains(text, "Full article body") || + !strings.Contains(text, "Original <title>") { + t.Fatal(text) + } + cookies := initial.Result().Cookies() + if len(cookies) == 0 { + t.Fatal("rendered form has no actual session cookie") + } + cookie := cookies[0].Name + "=" + cookies[0].Value + match := regexp.MustCompile(`name="_csrf" value="([^"]+)"`).FindStringSubmatch(text) + if len(match) != 2 { + t.Fatal("resource form omitted its CSRF token") + } + token := match[1] + bad := call("POST", "/_form/article", "title=Rejected&_csrf=wrong", cookie) + if bad.Code != http.StatusForbidden { + t.Fatalf("bad csrf accepted: %d %s", bad.Code, bad.Body.String()) + } + invalid := call("POST", "/_form/article", url.Values{"_csrf": {token}, "title": {""}}.Encode(), cookie) + if invalid.Code != http.StatusOK || !strings.Contains(invalid.Body.String(), "Title required") || + !strings.Contains(invalid.Body.String(), `name="_csrf" value="`+token+`"`) { + t.Fatalf("validation retry: %d %s", invalid.Code, invalid.Body.String()) + } + valid := call("POST", "/_form/article", url.Values{"_csrf": {token}, "title": {"Inserted after startup"}, "_mq_return": {"/new"}}.Encode(), cookie) + if valid.Code != http.StatusSeeOther || valid.Header().Get("Location") != "/" { + t.Fatalf("submit: %d %s", valid.Code, valid.Body.String()) + } + current := call("GET", "/", "", cookie) + if !strings.Contains(current.Body.String(), "Inserted after startup") { + t.Fatal("query cached startup rows") + } + fragment := call("GET", "/_part/main", "", cookie) + if fragment.Code != http.StatusOK || !strings.Contains(fragment.Body.String(), "Inserted after startup") || + !strings.Contains(fragment.Body.String(), `name="_csrf" value="`+token+`"`) || + strings.Contains(fragment.Body.String(), "<!DOCTYPE") { + t.Fatalf("request fragment lost context: %d %s", fragment.Code, fragment.Body.String()) + } + unknown := call("GET", "/_part/not-declared", "", cookie) + if unknown.Code != http.StatusNotFound { + t.Fatalf("unknown View slot: %d", unknown.Code) + } + + detail := call("GET", "/post/first?slug=other", "", cookie) + if detail.Code != http.StatusOK || !strings.Contains(detail.Body.String(), "Full article body") || + strings.Contains(detail.Body.String(), "Short summary") { + t.Fatal(detail.Body.String()) + } + if detailed["where"].(map[string]any)["slug"] != "{slug}" { + t.Fatal("request mutated retained Resource") + } + sid, ok := session.IDFromCookie(cookie) + if !ok || !session.SetValue(sid, "username", "admin") { + t.Fatal("could not establish fixture session") + } + logged := call("GET", "/", "", cookie) + if strings.Contains(logged.Body.String(), "Guest login") || !strings.Contains(logged.Body.String(), "Private desk") { + t.Fatal(logged.Body.String()) + } +} + +func TestViewResourceValidationDoesNotQueryAndFailuresRemainVisible(t *testing.T) { + query := map[string]any{"_type": "data_query", "source": "missing"} + if _, err := artifact.RenderNodesWithResources([]any{resourceNode(query)}, ValidateViewResource); err != nil { + t.Fatalf("startup unexpectedly queried missing DB: %v", err) + } + for _, resource := range []map[string]any{ + {"_type": "invented"}, {"_type": "data_query", "source": "items", "limit": 1.5}, + {"_type": "data_query", "source": "items", "link_prefix": "javascript:"}, + {"_type": "form_ref", "id": ""}, + } { + if _, err := ValidateViewResource(resource); err == nil { + t.Fatalf("bad resource accepted: %#v", resource) + } + } + if _, err := artifact.RenderNodes([]any{resourceNode(query)}); err == nil { + t.Fatal("offline render invented request context") + } + bag := app.New(map[string]any{"page": map[string]any{"artifact_nodes": []any{resourceNode(query)}}}) + handler, err := NewHandler(bag, "") + if err != nil { + t.Fatal(err) + } + response := httptest.NewRecorder() + handler.ServeHTTP(response, httptest.NewRequest("GET", "/", nil)) + if response.Code != http.StatusInternalServerError || !strings.Contains(response.Body.String(), "no database") { + t.Fatalf("missing backend became successful empty content: %d %s", response.Code, response.Body.String()) + } +} + +func TestViewHeadResourcesServeInHeadAndNeverLeakIntoFragments(t *testing.T) { + nodes := []any{ + map[string]any{"type": "resource", "value": map[string]any{"_type": "document_head", "meta": map[string]any{"key": "description", "value": "Actual SEO"}, "links": []any{map[string]any{"rel": "stylesheet", "href": "/theme.css"}}}}, + map[string]any{"type": "markdown", "slot": "content", "value": "# Real content"}, + } + bag := app.New(map[string]any{"page": map[string]any{"title": "Head test", "artifact_nodes": nodes}}) + handler, err := NewHandler(bag, "") + if err != nil { + t.Fatal(err) + } + for _, path := range []string{"/", "/_part/main", "/_part/content"} { + response := httptest.NewRecorder() + handler.ServeHTTP(response, httptest.NewRequest("GET", path, nil)) + body := response.Body.String() + if response.Code != http.StatusOK || !strings.Contains(body, "Real content") { + t.Fatalf("%s %d %s", path, response.Code, body) + } + if path == "/" { + head, rest, _ := strings.Cut(body, "</head>") + if !strings.Contains(head, `<meta name="description" content="Actual SEO"`) || !strings.Contains(head, `href="/theme.css"`) || strings.Contains(rest, "Actual SEO") { + t.Fatal(body) + } + } else if strings.Contains(body, "Actual SEO") || strings.Contains(body, "<head") || strings.Contains(body, "theme.css") { + t.Fatal(body) + } + } +} diff --git a/plugins/web/internal/plugin/host.go b/plugins/web/internal/plugin/host.go index 67ae69f..507b29b 100644 --- a/plugins/web/internal/plugin/host.go +++ b/plugins/web/internal/plugin/host.go @@ -53,7 +53,15 @@ func CallLibPath(path string, args map[string]any) (any, error) { // RunArtifact loads and runs a Document/Endpoint `.mq.md` (ADR 0007). // Request fields are passed as Metadata Binding overlays (`arg` / `--bind`). func RunArtifact(path string, args map[string]any) (any, error) { + return RunArtifactAtRoot(path, args, "") +} + +// RunArtifactAtRoot retains a selected site directory within the host's grant. +func RunArtifactAtRoot(path string, args map[string]any, root string) (any, error) { payload := map[string]any{"path": path} + if root != "" { + payload["root"] = root + } if len(args) > 0 { payload["args"] = args } diff --git a/plugins/web/internal/render/anlian_resolve_test.go b/plugins/web/internal/render/document_posts_resolve_test.go similarity index 94% rename from plugins/web/internal/render/anlian_resolve_test.go rename to plugins/web/internal/render/document_posts_resolve_test.go index 737dba9..356411c 100644 --- a/plugins/web/internal/render/anlian_resolve_test.go +++ b/plugins/web/internal/render/document_posts_resolve_test.go @@ -11,8 +11,8 @@ import ( "github.com/marqdo/marqdo/plugins/web/internal/table" ) -func TestAnlianPostsResolve(t *testing.T) { - url := "sqlite:" + filepath.Join(t.TempDir(), "anlian.db") +func TestDocumentPostsResolve(t *testing.T) { + url := "sqlite:" + filepath.Join(t.TempDir(), "posts.db") fields := []any{ map[string]any{"name": "title", "type": "text", "nullable": false}, map[string]any{"name": "summary", "type": "text"}, diff --git a/plugins/web/internal/render/render.go b/plugins/web/internal/render/render.go index e6207ef..6f4bbb1 100644 --- a/plugins/web/internal/render/render.go +++ b/plugins/web/internal/render/render.go @@ -3,6 +3,7 @@ package render import ( "fmt" + "sort" "strings" "github.com/marqdo/marqdo/plugins/web/internal/assets" @@ -846,6 +847,15 @@ func resolveLayout(page map[string]any) string { return normalizeLayout(raw) } +// DocumentHead reuses ordinary Document metadata, links and native head boot +// helpers without adding application configuration or a second HTML dialect. +func DocumentHead(title string, meta map[string]any, links []assets.HeadLink) string { + if title == "" { + title = "Marqdo" + } + return headHTML(map[string]any{"meta": meta, "head": assets.HeadLinksToJSON(links)}, title) +} + func headHTML(page map[string]any, defaultTitle string) string { pageTitle := defaultTitle if meta, ok := page["meta"].(map[string]any); ok { @@ -859,7 +869,13 @@ func headHTML(page map[string]any, defaultTitle string) string { s.WriteString(fmt.Sprintf(`<meta name="csrf-token" content="%s"/>`, esc(strings.TrimSpace(csrf)))) } if meta, ok := page["meta"].(map[string]any); ok { - for k, v := range meta { + keys := make([]string, 0, len(meta)) + for key := range meta { + keys = append(keys, key) + } + sort.Strings(keys) + for _, k := range keys { + v := meta[k] if k == "title" { continue } @@ -1361,6 +1377,39 @@ func renderFragment(page map[string]any, dbURL, slot string) string { } } +// RenderQueryRows projects native database records into existing card/article +// rendering. Query failures remain with the Resource caller, never empty success. +func RenderQueryRows(rows any, detail bool, prefix string) string { + raw, _ := rows.([]any) + var body strings.Builder + if !detail { + body.WriteString(`<section class="content cards">`) + } + for _, row := range raw { + item := projectArtifactRow(row) + if item == nil { + continue + } + if detail { + if object, ok := row.(map[string]any); ok { + if full, exists := object["body"]; exists { + item["body"] = text(full) + } + if full, exists := object["content"]; exists { + item["body"] = text(full) + } + } + body.WriteString(renderArticle(item)) + break + } + body.WriteString(renderCard(map[string]any{"link_prefix": prefix}, item)) + } + if !detail { + body.WriteString("</section>") + } + return body.String() +} + // RenderPage builds full-page HTML (or a part fragment when partID is set). func RenderPage(page map[string]any, dbURL string, partID string) string { // Explicit View Documents already own their structure and document shell. diff --git a/plugins/web/plugin.go b/plugins/web/plugin.go index d228467..7403f64 100644 --- a/plugins/web/plugin.go +++ b/plugins/web/plugin.go @@ -163,6 +163,7 @@ extern int web_render_nodes(char *args_json, char **out_json, char **err_msg); extern int web_render_document(char *args_json, char **out_json, char **err_msg); extern int web_dom_markdown(char *args_json, char **out_json, char **err_msg); extern int web_serve_root(char *args_json, char **out_json, char **err_msg); +extern int web_prepare_root(char *args_json, char **out_json, char **err_msg); extern int web_inspect(char *args_json, char **out_json, char **err_msg); extern int web_app_use(char *args_json, char **out_json, char **err_msg); extern int web_route_use(char *args_json, char **out_json, char **err_msg); @@ -272,6 +273,7 @@ static int register_core(void) { if (host_register((char *)"web_render_document", (char *)"page,body,db,title", web_render_document) != 0) return 1; if (host_register((char *)"web_dom_markdown", (char *)"text", web_dom_markdown) != 0) return 1; if (host_register((char *)"web_serve_root", (char *)"root,host,port,db,static_dir,middleware", web_serve_root) != 0) return 1; + if (host_register((char *)"web_prepare_root", (char *)"root,host,port,db,static_dir,middleware", web_prepare_root) != 0) return 1; if (host_register((char *)"web_inspect", (char *)"app,root", web_inspect) != 0) return 1; if (host_register((char *)"web_app_use", (char *)"app,middleware", web_app_use) != 0) return 1; if (host_register((char *)"web_route_use", (char *)"route,middleware", web_route_use) != 0) return 1; diff --git a/public/00-welcome.mq.md b/public/00-welcome.mq.md index 2d5fecc..7e17537 100644 --- a/public/00-welcome.mq.md +++ b/public/00-welcome.mq.md @@ -9,6 +9,10 @@ import: # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Hello — and welcome. I built Marqdo so that code is documentation and documentation is code: Markdown markers are the program structure, so what you read is what runs. AI systems already favor Markdown-shaped output. That raised a simple question: why keep docs and programs as two separate artifacts? Marqdo is the answer. The `.mq.md` suffix exists so a file stays renderable as Markdown while remaining executable. Richer OKF-style YAML catalogs and even slide decks are on the roadmap; for now this site itself is generated by Marqdo — and that often saves tokens when an AI is writing with you. @@ -32,11 +36,11 @@ $$ Then plot it: **_svg = math.plot formula=`f` var="x" min=-3 max=3** -Foreign lets you embed another language. Bind `hi` to a small Python block: +Foreign lets you embed another language. Use Node Intl for locale-aware currency formatting, a genuine presentation boundary: `hi` = -```python -print("hello-from-python") +```node +console.log(new Intl.NumberFormat("zh-CN", {style:"currency", currency:"CNY"}).format(950)); ``` Under Markdown this stays easy to read — which is the point: code as documentation, documentation as code. @@ -51,17 +55,17 @@ One file, three surfaces. The static site you are reading is generated from these files, so the examples are not screenshots. Run the same source and you get the same page. -Foreign v2 is a good example. Probe Python, then run the bound fence: +Foreign v2 is a good example. Probe Node, then run the bound fence: -**python = > foreign.probe lang="python"** +We first **node = [Check the formatting runtime](foreign.probe(lang="node"))** for the next step. -1. [ok](access(`python`, "ok")) - **hello = > foreign.run code=`hi`** - > print text=`hello` +1. [ok](access(`node`, "ok")) + We first **hello = [Format the native amount](foreign.run(code=`hi`))** for the next step. + We now **[Display this step's result](> print text=`hello`)**. 2. * - > print text="(python3 not found — install Python to run this cell)" + We now **[Display this step's result](> print text="(node not found — install Node to run this cell)")**. -The same module also supports JSON calls, parallel fan-out, persistent kernels and an explicit state bridge. See [stdlib/foreign.mq.md](stdlib/foreign.mq.md) and the full Python walkthrough in [features/19-foreign-view-cells.mq.md](features/19-foreign-view-cells.mq.md). +The same module also supports JSON calls, parallel fan-out, persistent kernels and an explicit state bridge. See [stdlib/foreign.mq.md](stdlib/foreign.mq.md) and the native-first Intl walkthrough in [features/19-foreign-view-cells.mq.md](features/19-foreign-view-cells.mq.md). A view document is still a document. Named kernels and a cell order are ordinary bound tables: @@ -70,8 +74,8 @@ A view document is still a document. Named kernels and a cell order are ordinary | 名称 | 语言 | 说明 | |------|------|------| -| 分析 | python | shared state | -| 复核 | python | isolated state | +| 分析 | node | shared state | +| 复核 | node | isolated state | `分析单元` = @@ -98,19 +102,15 @@ Read [features/20-okf-ekc.mq.md](features/20-okf-ekc.mq.md) for the concepts and Welcome again — enjoy exploring Marqdo. -## greet - -When we meet a visitor `who`, we **print text="Welcome, `who`!"** and close with*None*. - -## install +Installation choices. Install the interpreter (CLI) in any of these ways: | Way | Notes | |------|------| -| Ubuntu PPA | `sudo add-apt-repository ppa:cflmy/marqdo` then `sudo apt install marqdo` | +| Ubuntu PPA | sudo add-apt-repository ppa:cflmy/marqdo then sudo apt install marqdo | | GitHub Releases | Prebuilt Windows / Linux packages from [releases](https://github.com/cflmy/marqdo/releases) | -| From source | `cargo build --release` (needs a local Rust toolchain) | +| From source | cargo build --release (needs a local Rust toolchain) | Official extensions update independently of the CLI: @@ -120,3 +120,16 @@ marqdo ext add quantum ``` `ext add` tries CDN https://ext.marqdo.com first, then GitHub, then the proxy mirror. See [`features/05-extensions.mq.md`](features/05-extensions.mq.md). + + +## greet + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| who | any | required | Recipient name inserted into the greeting | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; this function performs the described effects instead of returning business data | + +When we meet a visitor `who`, we **print text="Welcome, `who`!"** and close with*None*. diff --git a/public/00-欢迎.mq.md b/public/00-欢迎.mq.md index 0d253c0..48959a4 100644 --- a/public/00-欢迎.mq.md +++ b/public/00-欢迎.mq.md @@ -9,6 +9,10 @@ description: 用户文档首页 — 代码即文档(中文版) # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 阅读到这里的朋友你好!我是 Marqdo 的开发者。Marqdo 是一门「代码即文档,文档即代码」的语言:Markdown 标记就是程序结构,你读到的就是能跑的程序。 AI 偏爱 Markdown 结构的输出。我当时的念头很简单——何必再把文档和代码拆成两套?于是有了 marqdo。为了让文件既能当文档渲染又能执行,后缀定为 `.mq.md`。更远的目标还有 OKF 式知识库的 YAML、甚至自动生成 PPT;眼下它至少已经是个不错的博客工具——对,这个站点就是 Marqdo 生成的。AI 写 `.mq.md` 时往往更省 token,钱包也会轻松一点。 @@ -35,8 +39,8 @@ $$ 外联则允许嵌一段别的语言。把`hi`绑成下面这样即可: `hi` = -```python -print("hello-from-python") +```node +console.log(new Intl.NumberFormat("zh-CN", {style:"currency", currency:"CNY"}).format(950)); ``` 这些在 Markdown 里读起来仍然像文章——这就是 marqdo 想坚持的:代码即文档,文档即代码。 @@ -51,17 +55,17 @@ print("hello-from-python") 你正在读的静态站就是由这些文件生成的,所以示例不是截图。运行同一份源,会得到同一页。 -外联 v2 是个好例子。先探测 Python,再运行绑定围栏: +外联 v2 是个好例子。先探测 Node,再运行绑定围栏: -**python = > 外联.探测 语言="python"** +我们先**node = [检查本地化展示所需的解释器](外联.探测(语言="node"))**,供下一步使用。 -1. [ok](access(`python`, "ok")) - **问候 = > 外联.运行 代码=`hi`** - > 打印 内容=`问候` +1. [ok](access(`node`, "ok")) + 我们先**问候 = [通过 Intl 展示原生金额](外联.运行(代码=`hi`))**,供下一步使用。 + 随后我们**[显示当前步骤的结果](> 打印 内容=`问候`)**。 2. * - > 打印 内容="(未找到 python3 — 安装 Python 后可运行此单元)" + 随后我们**[显示当前步骤的结果](> 打印 内容="(未找到 node — 安装 Node 后可运行此单元)")**。 -同一个模块还支持 JSON 调用、并行扇出、持久内核与显式状态桥。见 [stdlib/外联.mq.md](stdlib/外联.mq.md) 与完整 Python 示例 [features/19-外联视图单元.mq.md](features/19-外联视图单元.mq.md)。 +同一个模块还支持 JSON 调用、并行扇出、持久内核与显式状态桥。见 [stdlib/外联.mq.md](stdlib/外联.mq.md) 与原生分析与 Intl 示例 [features/19-外联视图单元.mq.md](features/19-外联视图单元.mq.md)。 view 仍然是一篇文档。命名内核与单元顺序就是普通绑定表: @@ -70,8 +74,8 @@ view 仍然是一篇文档。命名内核与单元顺序就是普通绑定表: | 名称 | 语言 | 说明 | |------|------|------| -| 分析 | python | 共享状态 | -| 复核 | python | 隔离状态 | +| 分析 | node | 共享状态 | +| 复核 | node | 隔离状态 | `分析单元` = @@ -98,19 +102,15 @@ view 仍然是一篇文档。命名内核与单元顺序就是普通绑定表: 最后,再次欢迎你,尽情体验 marqdo 吧! -## 问候 - -见到访客`谁`时,我们 **打印 内容="欢迎,`谁`!"**,然后收束为*None*。 - -## 安装 +安装方式。 解释器(CLI)任选其一: | 方式 | 说明 | |------|------| -| Ubuntu PPA | `sudo add-apt-repository ppa:cflmy/marqdo` 后 `sudo apt install marqdo` | +| Ubuntu PPA | sudo add-apt-repository ppa:cflmy/marqdo 后 sudo apt install marqdo | | GitHub Releases | [releases](https://github.com/cflmy/marqdo/releases) 下载 Windows / Linux 预编译包 | -| 源码 | `cargo build --release`(需本机 Rust) | +| 源码 | cargo build --release(需本机 Rust) | 官方扩展与 CLI 可分开更新。安装扩展: @@ -120,3 +120,16 @@ marqdo ext add quantum ``` `ext add` 下载顺序:CDN https://ext.marqdo.com → GitHub → proxy 镜像。详见本站 [`features/05-扩展.mq.md`](features/05-扩展.mq.md)。 + + +## 问候 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 谁 | any | 必填 | 要显示在问候中的称呼 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;本函数通过上述操作产生效果,不返回业务数据。 | + +见到访客`谁`时,我们 **打印 内容="欢迎,`谁`!"**,然后收束为*None*。 diff --git a/public/features/01-phase-i-treewalk.mq.md b/public/features/01-phase-i-treewalk.mq.md index b5de2b9..09858fd 100644 --- a/public/features/01-phase-i-treewalk.mq.md +++ b/public/features/01-phase-i-treewalk.mq.md @@ -6,10 +6,14 @@ description: Lex · parse · check · tree-walk end to end # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Milestone: Phase I (tree-walk). Pipeline: load → line classify → recursive-descent parse → semantic check → tree-walk eval. No Flex/Bison. This page runs as a program — documentation is executable: -> print text=Phase I: tree-walk interpreter is live. +We now **[Display this step's result](> print text="Phase I: tree-walk interpreter is live.")**. diff --git a/public/features/01-树遍历.mq.md b/public/features/01-树遍历.mq.md index 1282d6a..8609ea2 100644 --- a/public/features/01-树遍历.mq.md +++ b/public/features/01-树遍历.mq.md @@ -6,10 +6,14 @@ description: 词法 · 语法 · 语义 · 树遍历已贯通 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 里程碑:第一阶段(树遍历)。 流水线:加载 → 行分类 → 递归下降语法 → 语义检查 → 树遍历执行。实现不用 Flex/Bison。 本页本身即可运行,证明「文档即程序」已落地: -> 打印 内容=第一阶段:树遍历解释器已就绪。 +随后我们**[显示当前步骤的结果](> 打印 内容="第一阶段:树遍历解释器已就绪。")**。 diff --git a/public/features/02-bytecode.mq.md b/public/features/02-bytecode.mq.md index 645fde4..b83a3e2 100644 --- a/public/features/02-bytecode.mq.md +++ b/public/features/02-bytecode.mq.md @@ -6,6 +6,10 @@ description: `--backend bytecode` shares semantics with tree-walk # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Milestone: bytecode prototype. The same `.mq.md` runs on tree-walk or the bytecode VM: @@ -16,4 +20,4 @@ The same `.mq.md` runs on tree-walk or the bytecode VM: Output matches on both backends: -> print text=Bytecode backend: same program, alternate engine. +We now **[Display this step's result](> print text="Bytecode backend: same program, alternate engine.")**. diff --git a/public/features/02-字节码.mq.md b/public/features/02-字节码.mq.md index 77b0158..389f2ab 100644 --- a/public/features/02-字节码.mq.md +++ b/public/features/02-字节码.mq.md @@ -6,6 +6,10 @@ description: `--backend bytecode` 与树遍历共用语义 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 里程碑:字节码原型。 同一套 `.mq.md` 可用树遍历或字节码 VM: @@ -16,4 +20,4 @@ description: `--backend bytecode` 与树遍历共用语义 两种后端输出一致: -> 打印 内容=字节码后端:同一程序,另一引擎。 +随后我们**[显示当前步骤的结果](> 打印 内容="字节码后端:同一程序,另一引擎。")**。 diff --git a/public/features/03-view-and-docs.mq.md b/public/features/03-view-and-docs.mq.md index a323b2f..4bb18ba 100644 --- a/public/features/03-view-and-docs.mq.md +++ b/public/features/03-view-and-docs.mq.md @@ -6,6 +6,10 @@ description: Local browse and static export from the interpreter # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Version 2.6.0 keeps action descriptions in the sentence and moves their implementation to side notes. Empty parentheses explicitly mark missing logic. Multiple actions and returns keep their original prose, while ordinary links remain navigation. On compact screens, native disclosures keep the implementation readable even without JavaScript. Executable knowledge now presents inputs, returns, effects, dependencies and separate verification facts. Technical identities and digests stay folded. Source explanations are distinct from captured results; a pure effect summary or linked source is not proof that a program ran or its content was verified. @@ -33,4 +37,4 @@ Browse Structure keeps narration, highlights executable markers, and attaches run results (values, taken branch arms, call/loop frames). The same render path builds this user docs site; CI publishes to `gh-pages`. -> print text=Docs site: generated by the Marqdo interpreter, not hand-written HTML. +We now **[Display this step's result](> print text="Docs site: generated by the Marqdo interpreter, not hand-written HTML.")**. diff --git a/public/features/03-view与文档.mq.md b/public/features/03-view与文档.mq.md index 6325734..cbf505b 100644 --- a/public/features/03-view与文档.mq.md +++ b/public/features/03-view与文档.mq.md @@ -6,6 +6,10 @@ description: 本地浏览与静态导出由解释器生成 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 版本 2.6.0 将动作说明留在句子里,实际实现引到侧注;空圆括号明确提示待补逻辑。同一句话可以保留多个调用与返回,普通链接仍是导航。窄屏使用原生可展开详情,没有 JavaScript 也能查看实现。 可执行知识先展示输入、返回、调用边界、依赖和分别列出的验证依据,技术身份与摘要按需展开。源码说明与运行捕获有不同含义;pure、来源关联或构造配置都不能被当作已运行或内容已验证的证据。 @@ -28,4 +32,4 @@ description: 本地浏览与静态导出由解释器生成 Browse Structure 保真叙述、高亮可执行标记,并挂载运行结果(变量值、分支命中臂、调用/循环帧)。 用户站与 live view 同源渲染;CI 发布到 `gh-pages`。 -> 打印 内容=文档站:由 Marqdo 解释器生成,不是手写 HTML。 +随后我们**[显示当前步骤的结果](> 打印 内容="文档站:由 Marqdo 解释器生成,不是手写 HTML。")**。 diff --git a/public/features/04-objects.mq.md b/public/features/04-objects.mq.md index fd59381..a0d6f71 100644 --- a/public/features/04-objects.mq.md +++ b/public/features/04-objects.mq.md @@ -6,8 +6,12 @@ description: Sharp heading is a type; deeper headings are functions or methods # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + In Marqdo, a single sharp (#) defines an object / type constructor. Double sharp and deeper (## …) define free functions or methods. Constructing an object yields a map handle tagged with _type. Call methods with backtick object, then dot, then method name. See doc/design/objects.md. Example gold: tests/structure/object-handle.mq.md. Official ext/llm and ext/agent use this pattern. -> print text=objects-ok +We now **[Display this step's result](> print text="objects-ok")**. diff --git a/public/features/04-对象.mq.md b/public/features/04-对象.mq.md index bff0a48..3ad2191 100644 --- a/public/features/04-对象.mq.md +++ b/public/features/04-对象.mq.md @@ -6,8 +6,12 @@ description: 一级标题是类型;更深标题是函数或方法 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + Marqdo 中,单个井号(#)定义对象 / 类型构造体;二级及以上(## …)定义自由函数或方法。构造得到带 _type 标记的 map 句柄。方法调用形如:反引号对象、点、方法名。 详见 doc/design/objects.md。金样例:tests/structure/object-handle.mq.md。官方 ext/llm 与 ext/agent 使用同一模式。 -> 打印 内容=对象就绪 +随后我们**[显示当前步骤的结果](> 打印 内容="对象就绪")**。 diff --git a/public/features/05-extensions.mq.md b/public/features/05-extensions.mq.md index 49fff60..c64cec1 100644 --- a/public/features/05-extensions.mq.md +++ b/public/features/05-extensions.mq.md @@ -6,6 +6,10 @@ description: Optional packages — not stdlib # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + ext/ holds official optional extensions. They are not part of lib/. Resolve via `~/.marqdo/ext`, MARQDO_EXT, ./ext, or ext/ next to the binary. Install (v0.2+): @@ -39,7 +43,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 (default *Go libweb*, v0.4.0). W0–W7, P3, W8, and customization C0–C4; acceptance example `examples/anlian-mq/`. 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/web provides Documents/Endpoints, recursive View, document-head and request resources. Decompose layout to Markdown or native-control leaves; data, authentication and transport belong to ext/data, ext/security and ext/net. Follow examples/web-site/index.mq.md and examples/web-net-site/index.mq.md for complete workflows. Browser interaction uses Marqdo clients and the official WASM bridge. Development, builds and real acceptance run through marqdo call in skills/marqdo-dev/index.mq.md; the current author contract starts at ext/web/index.mq.md. 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 @@ -47,4 +51,4 @@ Installer: marqdo ext list / add / remove — doc/design/ext-cli.md Native plugins: lib/plugin + include/marqdo_abi.h — doc/design/ext-abi.md -> print text=ext-ok +We now **[Display this step's result](> print text="ext-ok")**. diff --git a/public/features/05-扩展.mq.md b/public/features/05-扩展.mq.md index 8d8c5b5..9ab5f76 100644 --- a/public/features/05-扩展.mq.md +++ b/public/features/05-扩展.mq.md @@ -6,6 +6,10 @@ description: 可选包 — 不是标准库 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + ext/ 存放官方可选扩展,不属于 lib/。解析顺序:`~/.marqdo/ext`、MARQDO_EXT、./ext、或可执行文件旁的 ext/。 安装(v0.2+): @@ -39,7 +43,7 @@ ext/llm(大模型)— OpenAI 兼容聊天。设计:doc/design/ext-llm.md ext/agent(智能体)— 智能体框架 + 原生插件。设计:doc/design/ext-agent.md -ext/web(网页)— HTTP / SQLite 站点助手 + 原生插件(默认 *Go libweb*,v0.4.0)。W0–W7、P3、W8 与定制 C0–C4;验收示例 `examples/anlian-mq/`。浏览器挂载(路线 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/web(网页)提供 Document/Endpoint、递归 View、页头和请求资源。布局拆到 Markdown 或原生控件叶子,数据、鉴权与运输分别归 ext/data、ext/security、ext/net。完整实践见 examples/web-site-zh/index.mq.md 与 examples/web-net-site-zh/index.mq.md;浏览器交互通过 Marqdo 客户端及官方 WASM 桥完成。开发、构建和真实验收入口为 skills/marqdo-dev/index.mq.md,操作使用 marqdo call;当前作者契约见 ext/web/网页/索引.mq.md。 ext/quantum(量子)— 电路、绘图、噪声、公式矩阵自定义门、Q7 密度/高级图、Q8 主题 SVG(`主题=dark|light|bw`)。设计:doc/design/ext-quantum.md · doc/design/ext-quantum-viz-style.md @@ -47,4 +51,4 @@ ext/quantum(量子)— 电路、绘图、噪声、公式矩阵自定义门 通用原生插件:lib/plugin + include/marqdo_abi.h — doc/design/ext-abi.md -> 打印 内容=扩展就绪 +随后我们**[显示当前步骤的结果](> 打印 内容="扩展就绪")**。 diff --git a/public/features/06-quantum.mq.md b/public/features/06-quantum.mq.md index de1d92d..25163d3 100644 --- a/public/features/06-quantum.mq.md +++ b/public/features/06-quantum.mq.md @@ -9,6 +9,10 @@ import: # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Optional package (not stdlib). Install: `marqdo ext add quantum` (or build `marqdo_plugin_quantum`). GHZ (3 qubits): H on q0, then CX 0→1 and 0→2. Ideal |000⟩ / |111⟩ each ≈ 1/2. @@ -25,11 +29,11 @@ Q8: `draw theme="dark"|"light"|"bw"` (default dark lab look) on circuit / probs | 2 | CX | 0,1 | | 3 | CX | 0,2 | -**`qc` = > quantum.circuit qubits=3 steps=`steps`** -**`p` = > `qc`.probabilities** -**`_` = > `qc`.draw kind="probs" theme="dark"** -**`H` = > gate.gate name="H"** -**`__` = > `H`.draw kind="matrix"** +We first **qc = [Compute qc](quantum.circuit(qubits=3, steps=`steps`))** for the next step. +We first **p = [Compute p](> `qc`.probabilities)** for the next step. +We first **_ = [Compute _](> `qc`.draw kind="probs" theme="dark")** for the next step. +We first **H = [Compute H](gate.gate(name="H"))** for the next step. +We first **__ = [Compute __](> `H`.draw kind="matrix")** for the next step. -> print text=`p` -> print text=quantum-feature-ok +We now **[Display this step's result](> print text=`p`)**. +We now **[Display this step's result](> print text="quantum-feature-ok")**. diff --git a/public/features/06-量子.mq.md b/public/features/06-量子.mq.md index 71fc8ae..ea78855 100644 --- a/public/features/06-量子.mq.md +++ b/public/features/06-量子.mq.md @@ -9,6 +9,10 @@ description: 官方量子模拟 — 表、门、Q7 密度与高级图、Q8 主 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 可选扩展(非 stdlib)。安装:`marqdo ext add quantum`(或编译 `marqdo_plugin_quantum`)。 中文面在同包 `ext/quantum/量子/`(根 skill:`索引.mq.md`),与英文模块树并列、不混排 API。 @@ -27,11 +31,11 @@ Q8:`绘图 主题="dark"|"light"|"bw"`(默认 dark 科技感)作用于电 | 2 | CX | 0,1 | | 3 | CX | 0,2 | -**`qc` = > 量子.电路 比特数=3 步骤=`步骤`** -**`p` = > `qc`.概率** -**`_` = > `qc`.绘图 种类="probs" 主题="dark"** -**`H` = > 门.门 名="H"** -**`__` = > `H`.绘图 种类="matrix"** +我们先**qc = [计算并保存 qc](量子.电路(比特数=3, 步骤=`步骤`))**,供下一步使用。 +我们先**p = [计算并保存 p](> `qc`.概率)**,供下一步使用。 +我们先**_ = [计算并保存 _](> `qc`.绘图 种类="probs" 主题="dark")**,供下一步使用。 +我们先**H = [计算并保存 H](门.门(名="H"))**,供下一步使用。 +我们先**__ = [计算并保存 __](> `H`.绘图 种类="matrix")**,供下一步使用。 -> 打印 内容=`p` -> 打印 内容=量子特性-ok +随后我们**[显示当前步骤的结果](> 打印 内容=`p`)**。 +随后我们**[显示当前步骤的结果](> 打印 内容="量子特性-ok")**。 diff --git a/public/features/07-linalg.mq.md b/public/features/07-linalg.mq.md index a3d499b..64ca0fb 100644 --- a/public/features/07-linalg.mq.md +++ b/public/features/07-linalg.mq.md @@ -8,12 +8,17 @@ import: # Formula documents with ext/linalg + Not stdlib. Install: `marqdo ext add linalg` (or build `marqdo_plugin_linalg`). *Idea:* if the `.mq.md` runs and the asserted form matches, the identity holds under the library rules. Algebra reads like a lecture; `factorize` / `lstsq` / `draw` stay explicit calculation steps. # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Declare symbols in a table, multiply, transpose — `T_ascii` is one-step display (auto-simplify). `shapes` = @@ -23,15 +28,15 @@ Declare symbols in a table, multiply, transpose — `T_ascii` is one-step displa | 1 | A | 2 | 3 | | 2 | B | 3 | 2 | -**`env` = > la.declare table=`shapes`** -**`A` = [A](access(env, "A"))** -**`B` = [B](access(env, "B"))** -**`P` = `A` * `B`** -**`t` = > `P`.T_ascii** -> print text=`t` +We first **env = [Compute env](la.declare(table=`shapes`))** for the next step. +We first **A = [A](access(`env`, "A"))** for the next step. +We first **B = [B](access(`env`, "B"))** for the next step. +We first **P = (`A` * `B`)** for the next step. +We first **t = [Compute t](> `P`.T_ascii)** for the next step. +We now **[Display this step's result](> print text=`t`)**. 1. `t` == "B^T*A^T" - > print text=formula-doc-ok + We now **[Display this step's result](> print text="formula-doc-ok")**. 2. * - > print text=formula-doc-fail + We now **[Display this step's result](> print text="formula-doc-fail")**. -> print text=see-examples-linalg-transpose +We now **[Display this step's result](> print text="see-examples-linalg-transpose")**. diff --git a/public/features/07-线性代数.mq.md b/public/features/07-线性代数.mq.md index 5a2d966..73aa26f 100644 --- a/public/features/07-线性代数.mq.md +++ b/public/features/07-线性代数.mq.md @@ -14,6 +14,14 @@ description: ext/linalg 公式文档面 — 声明、中缀、跑通即正确 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + +这里讨论符号表达式的形状,而不是对矩阵中的每个数值做计算。先声明 A 为两行三列、B 为三行两列,乘积才具有合法的二行二列形状;转置时两个因子的顺序交换,得到 B^T*A^T。输出相符只证明本例在库定义的规范化规则下成立,不意味着任意数值近似或未声明符号也会被接受。 + +阅读时先看形状表,再看乘法和转置的动作说明。公式库需要对应的原生插件,缺少依赖时应先安装 linalg;不要把插件加载错误当成恒等式不成立。此例不读取或写入业务文件,也不把输出字符串重新执行成代码。需要实际矩阵分解时,沿文件开头的导入路径阅读分解函数的独立契约。 + 用表声明符号,再乘与转置 — `转置文本` 一步展示(默认化简)。 `形状` = @@ -23,15 +31,15 @@ description: ext/linalg 公式文档面 — 声明、中缀、跑通即正确 | 1 | A | 2 | 3 | | 2 | B | 3 | 2 | -**`环境` = > la.声明 表=`形状`** -**`A` = [A](access(环境, "A"))** -**`B` = [B](access(环境, "B"))** -**`P` = `A` * `B`** -**`t` = > `P`.转置文本** -> 打印 内容=`t` +我们先**环境 = [声明带有行列约束的符号环境](la.声明(表=`形状`))**,供下一步使用。 +我们先**A = [A](access(`环境`, "A"))**,供下一步使用。 +我们先**B = [B](access(`环境`, "B"))**,供下一步使用。 +我们先**P = (`A` * `B`)**,供下一步使用。 +我们先**t = [取得当前步骤的转置公式或随机令牌](> `P`.转置文本)**,供下一步使用。 +随后我们**[显示当前步骤的结果](> 打印 内容=`t`)**。 1. `t` == "B^T*A^T" - > 打印 内容=formula-doc-ok + 随后我们**[显示当前步骤的结果](> 打印 内容="formula-doc-ok")**。 2. * - > 打印 内容=formula-doc-fail + 随后我们**[显示当前步骤的结果](> 打印 内容="formula-doc-fail")**。 -> 打印 内容=see-examples-linalg-transpose +随后我们**[显示当前步骤的结果](> 打印 内容="see-examples-linalg-transpose")**。 diff --git a/public/features/08-re-encoding.mq.md b/public/features/08-re-encoding.mq.md index 7a45139..d4ed0ca 100644 --- a/public/features/08-re-encoding.mq.md +++ b/public/features/08-re-encoding.mq.md @@ -9,17 +9,22 @@ import: # Regex and encoding in lib/ + Mid-tier stdlib: everyday primitives stay in `lib/`, not ABI plugins. # main -**`ok` = > re.is_match text="user@example.com" pattern="^[^@]+@[^@]+$"** -**`tok` = > enc.base64_encode text="marqdo"** -**`hex` = > enc.hex_encode text="ok"** -> print text=`ok` -> print text=`tok` -> print text=`hex` +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + +We first **ok = [Compute ok](re.is_match(text="user@example.com", pattern="^[^@]+@[^@]+$"))** for the next step. +We first **tok = [Compute tok](enc.base64_encode(text="marqdo"))** for the next step. +We first **hex = [Compute hex](enc.hex_encode(text="ok"))** for the next step. +We now **[Display this step's result](> print text=`ok`)**. +We now **[Display this step's result](> print text=`tok`)**. +We now **[Display this step's result](> print text=`hex`)**. 1. `ok` - > print text=mid-m1-ok + We now **[Display this step's result](> print text="mid-m1-ok")**. 2. * - > print text=mid-m1-fail + We now **[Display this step's result](> print text="mid-m1-fail")**. diff --git a/public/features/08-正则编解码.mq.md b/public/features/08-正则编解码.mq.md index 068ccd0..d812f5d 100644 --- a/public/features/08-正则编解码.mq.md +++ b/public/features/08-正则编解码.mq.md @@ -13,13 +13,21 @@ description: lib/正则 + lib/编码,无需插件(中层 M1) # main -**`ok` = > 正则.匹配 内容="user@example.com" 模式="^[^@]+@[^@]+$"** -**`tok` = > 编码.基64编码 内容="marqdo"** -**`hex` = > 编码.十六进制编码 内容="ok"** -> 打印 内容=`ok` -> 打印 内容=`tok` -> 打印 内容=`hex` +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + +本例从固定的邮箱样式文本开始:正则只检查是否符合给定模式,并不是邮件地址真实性验证。随后把普通 UTF-8 文本分别编码成 Base64 和十六进制,以展示三种返回值的区别:匹配结果是布尔值,两种编码结果是文本。编码后的文本可以继续传给解码函数,还原原始字节或文字。 + +编码不具有保密作用,也不会替调用方校验邮箱能否接收消息。这里没有网络请求、文件读写或插件安装;所有输入都来自正文中的字面值。实际接入用户输入时要保留模式与编码函数的错误诊断,不能用空字符串代替失败。最后的标记只检查本例的匹配分支,不能代替编码往返和非法输入的验收。 + +我们先**ok = [检查给定模式是否匹配邮箱样式](正则.匹配(内容="user@example.com", 模式="^[^@]+@[^@]+$"))**,供下一步使用。 +我们先**tok = [把文本编码为 Base64](编码.基64编码(内容="marqdo"))**,供下一步使用。 +我们先**hex = [把文本编码为十六进制](编码.十六进制编码(内容="ok"))**,供下一步使用。 +随后我们**[显示当前步骤的结果](> 打印 内容=`ok`)**。 +随后我们**[显示当前步骤的结果](> 打印 内容=`tok`)**。 +随后我们**[显示当前步骤的结果](> 打印 内容=`hex`)**。 1. `ok` - > 打印 内容=mid-m1-ok + 随后我们**[显示当前步骤的结果](> 打印 内容="mid-m1-ok")**。 2. * - > 打印 内容=mid-m1-fail + 随后我们**[显示当前步骤的结果](> 打印 内容="mid-m1-fail")**。 diff --git a/public/features/09-path-fs.mq.md b/public/features/09-path-fs.mq.md index 142a6e1..2a8f866 100644 --- a/public/features/09-path-fs.mq.md +++ b/public/features/09-path-fs.mq.md @@ -1,29 +1,34 @@ --- markup: occlusion -title: Mid stdlib — path and fs -description: lib/path + fs copy/move/temp (Mid M2) +title: Path algebra and isolated native file copying import: path: lib/path.mq.md fs: lib/fs.mq.md --- -# Path algebra and file mid-layer +This page composes native path and filesystem libraries. Call main with fs.write and a disposable --fs-root; the return contains actual observations for a caller or View. -Join and normalize without plugins; copy/move stay sandboxed under the program directory. +## main -# main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Joined/normalized path text and actual copied content | -**`p` = > path.join a="out" b="demo.txt"** -**`n` = > path.normalize path="out/./x/../demo.txt"** -> fs.write_text path=`p` text="path-m2" -> fs.copy_file src=`p` dest="out/demo-copy.txt" -**`body` = > fs.read_text path="out/demo-copy.txt"** -> print text=`p` -> print text=`n` -> print text=`body` -1. `body` == "path-m2" - > print text=mid-m2-ok -2. * - > print text=mid-m2-fail -> fs.remove path=`p` -> fs.remove path="out/demo-copy.txt" +Joining and normalizing transform path text without granting filesystem access. The illustrative out/demo.txt is not an actual write destination. All real IO uses a unique native temporary directory, so this page neither requires a pre-existing out directory nor overwrites a caller's same-named files. + +Grant fs.write and choose a disposable root. Native encoding, path and root checks still apply. Read the copied content before cleaning this run's directory; the returned value should be path-m2. The result contains observations rather than live file paths. An intermediate failure retains its native diagnostic and can leave this run's directory for inspection and caller cleanup. + +The complete flow demonstrates text-only path algebra, actual writing, copying, reading and scoped cleanup. A normalized string is not a filesystem permission, and a printed marker alone would not prove what bytes were copied. + +We **requested = [Join the illustrative output path](path.join(a="out", b="demo.txt"))** and **normalized = [Remove redundant path segments without filesystem IO](path.normalize(path="out/./x/../demo.txt"))** before the file demonstration. +For actual IO we **work = [Create a unique directory inside the granted root](fs.temp_dir(prefix="path-demo"))** and **original = [Name this run own source file](path.join(a=`work`, b="demo.txt"))** and **copied = [Name its isolated copy](path.join(a=`work`, b="demo-copy.txt"))**. +We **[Write the actual text to copy](fs.write_text(path=`original`, text="path-m2"))** and **[Copy only this run own file](fs.copy_file(src=`original`, dest=`copied`))**. +We **copied_text = [Observe the actual copied content](fs.read_text(path=`copied`))** and then **[Clean only this run unique directory](fs.remove_tree(path=`work`))**. + +`observed` = + +| requested | normalized | copied_text | +|---|---|---| +| `requested` | `normalized` | `copied_text` | + +After the isolated file operation we return *observed*. The temporary files have been removed. diff --git a/public/features/09-路径文件.mq.md b/public/features/09-路径文件.mq.md index 9c1d50e..1cdf6cf 100644 --- a/public/features/09-路径文件.mq.md +++ b/public/features/09-路径文件.mq.md @@ -1,29 +1,34 @@ --- markup: occlusion -title: 中层标准库 — 路径与文件 -description: lib/路径 + 文件复制/移动/临时(中层 M2) -导入: +title: 路径代数与隔离的原生文件复制 +import: 路径: lib/路径.mq.md 文件: lib/文件.mq.md --- -# 路径代数与文件中层 +本页直接使用路径库和文件库。调用 main 时授权 fs.write,并将 --fs-root 指向可丢弃的工作目录。函数返回实际观察记录,View 可以显示这些值;无需生成外部脚本。 -无插件拼接/规范化;复制/移动仍落在程序目录沙箱内。 +## main -# main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 路径拼接文本、规范化文本与实际复制正文 | -**`p` = > 路径.拼接 甲="out" 乙="demo.txt"** -**`n` = > 路径.规范化 路径="out/./x/../demo.txt"** -> 文件.写文本 路径=`p` 内容="path-m2" -> 文件.复制文件 源=`p` 目标="out/demo-copy.txt" -**`body` = > 文件.读文本 路径="out/demo-copy.txt"** -> 打印 内容=`p` -> 打印 内容=`n` -> 打印 内容=`body` -1. `body` == "path-m2" - > 打印 内容=mid-m2-ok -2. * - > 打印 内容=mid-m2-fail -> 文件.删除 路径=`p` -> 文件.删除 路径="out/demo-copy.txt" +路径拼接和规范化先处理文本,不隐含文件访问授权。out/demo.txt 只是这个代数示例的输入,不会成为实际写入目的地。真正的文件操作全部放在通过固有库创建的唯一临时目录里,因此不要求已有 out 目录,也不覆盖用户的同名文件。 + +调用需要 fs.write,文件库仍会检查授权根目录、编码与路径边界。复制后的正文应为 path-m2。保存这个实际值后清理本轮目录,再返回观察记录;临时路径不会成为可继续使用的持久产物。失败保留原生诊断,中途错误可能留下本轮临时目录供检查,调用方负责识别并清理它。 + +本函数既展示无 IO 的路径代数,也展示真实写入、复制、读取和清理。业务中不要根据一个规范化后的字符串就认为已经获得文件权限,更不要把打印成功标记当成已读回复制内容的证明。 + +先**requested = [组合演示用的相对路径文本](路径.拼接(甲="out", 乙="demo.txt"))**和**normalized = [消除相对路径中的冗余片段](路径.规范化(路径="out/./x/../demo.txt"))**,核对路径代数本身。 +为实际读写创建**work = [只使用本轮独有的授权临时目录](文件.临时目录(前缀="路径演示"))**,再准备**original = [在临时目录中命名原文件](路径.拼接(甲=`work`, 乙="demo.txt"))**和**copied = [在同一目录中命名副本](路径.拼接(甲=`work`, 乙="demo-copy.txt"))**。 +随后**[写入本轮需要复制的正文](文件.写文本(路径=`original`, 内容="path-m2"))**,并**[复制本轮文件而不触及已有用户文件](文件.复制文件(源=`original`, 目标=`copied`))**。 +读取阶段保存**copied_text = [读取副本的真实正文](文件.读文本(路径=`copied`))**,完成观察后**[清理本轮独有的临时目录](文件.删目录树(路径=`work`))**。 + +`observed` = + +| requested | normalized | copied_text | +|---|---|---| +| `requested` | `normalized` | `copied_text` | + +完成路径处理与隔离读写后,我们返回*observed*,其中保留的是已观察到的值,临时文件已经清理。 diff --git a/public/features/10-hash-secrets.mq.md b/public/features/10-hash-secrets.mq.md index 3548425..5de2661 100644 --- a/public/features/10-hash-secrets.mq.md +++ b/public/features/10-hash-secrets.mq.md @@ -9,16 +9,21 @@ import: # Digests and secure tokens + Integrity digests and cryptographic tokens stay in `lib/` — do not use `math.random` for secrets. # main -**`d` = > hash.sha256 text="marqdo"** -**`t` = > sec.token_hex n=8** -**`L` = > len `t`** -> print text=`d` -> print text=`L` +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + +We first **d = [Compute d](hash.sha256(text="marqdo"))** for the next step. +We first **t = [Compute t](sec.token_hex(n=8))** for the next step. +We first **L = [Compute L](len(`t`))** for the next step. +We now **[Display this step's result](> print text=`d`)**. +We now **[Display this step's result](> print text=`L`)**. 1. `L` == 16 - > print text=mid-m3-ok + We now **[Display this step's result](> print text="mid-m3-ok")**. 2. * - > print text=mid-m3-fail + We now **[Display this step's result](> print text="mid-m3-fail")**. diff --git a/public/features/10-哈希机密.mq.md b/public/features/10-哈希机密.mq.md index 4921ae4..a07bcc6 100644 --- a/public/features/10-哈希机密.mq.md +++ b/public/features/10-哈希机密.mq.md @@ -13,12 +13,20 @@ description: lib/哈希 + lib/机密,无需插件(中层 M3) # main -**`d` = > 哈希.哈希256 内容="marqdo"** -**`t` = > 机密.十六进制令牌 字节数=8** -**`L` = > 长度 `t`** -> 打印 内容=`d` -> 打印 内容=`L` +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + +摘要和随机令牌解决不同的问题。固定文本的 SHA-256 摘要可用于比对内容是否变化;随机令牌从安全随机源获取字节,再编码为十六进制文本。八个随机字节会显示为十六个十六进制字符,因此这里检查输出长度,不把令牌与某个固定值比较。 + +本例不会把令牌写到磁盘或发送到网络。实际产品需要依据用途选择令牌字节数,并在使用后按应用规则保管或撤销;这里的短值只演示参数与编码长度的关系。哈希不提供加密,也不能单靠未认证的摘要证明内容来自谁。随机源失败时应保留诊断,不能改用普通伪随机数或固定文本充当安全令牌。 + +我们先**d = [计算固定文本的 SHA-256](哈希.哈希256(内容="marqdo"))**,供下一步使用。 +我们先**t = [取得当前步骤的转置公式或随机令牌](机密.十六进制令牌(字节数=8))**,供下一步使用。 +我们先**L = [读取十六进制令牌的字符数](长度(`t`))**,供下一步使用。 +随后我们**[显示当前步骤的结果](> 打印 内容=`d`)**。 +随后我们**[显示当前步骤的结果](> 打印 内容=`L`)**。 1. `L` == 16 - > 打印 内容=mid-m3-ok + 随后我们**[显示当前步骤的结果](> 打印 内容="mid-m3-ok")**。 2. * - > 打印 内容=mid-m3-fail + 随后我们**[显示当前步骤的结果](> 打印 内容="mid-m3-fail")**。 diff --git a/public/features/11-csv-text.mq.md b/public/features/11-csv-text.mq.md index dc4ed43..ef2b2f1 100644 --- a/public/features/11-csv-text.mq.md +++ b/public/features/11-csv-text.mq.md @@ -9,18 +9,23 @@ import: # CSV cleaning with text helpers + Parse a tiny CSV, normalize a field, print — no plugins. # main -**raw = "name,city\nAda,london\nBob,PARIS\n"** -**rows = > csv.parse text=`raw`** -**r0 = > at value=`rows` index=0** -**city = > text.to_upper text=[city](access(`r0`, "city"))** -> print text=[name](access(`r0`, "name")) -> print text=`city` -**n = > len `rows`** +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + +We first **raw = "name,city\nAda,london\nBob,PARIS\n"** for the next step. +We first **rows = [Compute rows](csv.parse(text=`raw`))** for the next step. +We first **r0 = [Compute r0](at(value=`rows`, index=0))** for the next step. +We first **city = [Compute city](text.to_upper(text=[city](access(`r0`, "city"))))** for the next step. +We now **[Display this step's result](> print text=[name](access(`r0`, "name")))**. +We now **[Display this step's result](> print text=`city`)**. +We first **n = [Compute n](len(`rows`))** for the next step. 1. `n` == 2 - > print text=mid-m4-ok + We now **[Display this step's result](> print text="mid-m4-ok")**. 2. * - > print text=mid-m4-fail + We now **[Display this step's result](> print text="mid-m4-fail")**. diff --git a/public/features/11-逗号表文本.mq.md b/public/features/11-逗号表文本.mq.md index 9e46b40..bd22944 100644 --- a/public/features/11-逗号表文本.mq.md +++ b/public/features/11-逗号表文本.mq.md @@ -13,14 +13,22 @@ description: lib/逗号表 + 加厚 lib/文本(中层 M4) # main -**raw = "name,city\nAda,london\nBob,PARIS\n"** -**rows = > 逗号表.解析 内容=`raw`** -**r0 = > at value=`rows` index=0** -**city = > 文本.大写 内容=[city](access(`r0`, "city"))** -> 打印 内容=[name](access(`r0`, "name")) -> 打印 内容=`city` -**n = > 长度 `rows`** +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + +CSV 解析先保留每个单元格的文本语义;下面选择第一条记录,再把城市字段规范为大写,得到 LONDON。姓名字段仍是 Ada,另一条记录仍保留在原集合中。调用文本变换不会自动替换原记录,因此这里只展示规范化值,不宣称整个表已经被清洗。 + +这里的 at 使用从零开始的位置,access 则按字段名读取记录;不要把二者的索引规则混用。输入正文直接写在本页,没有文件或进程访问。接入真实文件时先用原生文件库读取文本,再交给同一个解析函数;需要金额等数值运算时必须另外做明确的类型转换,不能根据 CSV 中的数字外观推断类型。两行计数只验证这份固定样本的解析结果。 + +我们先**raw = "name,city\nAda,london\nBob,PARIS\n"**,供下一步使用。 +我们先**rows = [解析或排序当前行记录](逗号表.解析(内容=`raw`))**,供下一步使用。 +我们先**r0 = [选择列表中的第一条记录](at(value=`rows`, index=0))**,供下一步使用。 +我们先**city = [将第一条记录的城市改为大写文本](文本.大写(内容=[city](access(`r0`, "city"))))**,供下一步使用。 +随后我们**[显示当前步骤的结果](> 打印 内容=[name](access(`r0`, "name")))**。 +随后我们**[显示当前步骤的结果](> 打印 内容=`city`)**。 +我们先**n = [取得本步骤需要的路径或计数](长度(`rows`))**,供下一步使用。 1. `n` == 2 - > 打印 内容=mid-m4-ok + 随后我们**[显示当前步骤的结果](> 打印 内容="mid-m4-ok")**。 2. * - > 打印 内容=mid-m4-fail + 随后我们**[显示当前步骤的结果](> 打印 内容="mid-m4-fail")**。 diff --git a/public/features/12-list-cli.mq.md b/public/features/12-list-cli.mq.md index ea1a859..80f9d90 100644 --- a/public/features/12-list-cli.mq.md +++ b/public/features/12-list-cli.mq.md @@ -10,20 +10,25 @@ import: # Sort CSV rows and parse flags + Zero plugins: parse CSV, sort by key, parse `--input`. # main -**raw = "name,score\nbob,2\nalice,10\n"** -**rows = > csv.parse text=`raw`** -**rows = > table.sort_by list=`rows` key="name"** -**r0 = > at value=`rows` index=0** -> print text=[name](access(`r0`, "name")) +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | -**args = > split value="--input,scores.csv,--pretty" sep=","** -**flags = > cli.parse args=`args`** -> print text=[input](access(`flags`, "input")) +We first **raw = "name,score\nbob,2\nalice,10\n"** for the next step. +We first **rows = [Compute rows](csv.parse(text=`raw`))** for the next step. +We first **rows = [Compute rows](table.sort_by(list=`rows`, key="name"))** for the next step. +We first **r0 = [Compute r0](at(value=`rows`, index=0))** for the next step. +We now **[Display this step's result](> print text=[name](access(`r0`, "name")))**. + +We first **args = [Compute args](split(value="--input,scores.csv,--pretty", sep=","))** for the next step. +We first **flags = [Compute flags](cli.parse(args=`args`))** for the next step. +We now **[Display this step's result](> print text=[input](access(`flags`, "input")))**. 1. [pretty](access(`flags`, "pretty")) - > print text=mid-m5-ok + We now **[Display this step's result](> print text="mid-m5-ok")**. 2. * - > print text=mid-m5-fail + We now **[Display this step's result](> print text="mid-m5-fail")**. diff --git a/public/features/12-列表命令行.mq.md b/public/features/12-列表命令行.mq.md index fa1173d..ec6d49c 100644 --- a/public/features/12-列表命令行.mq.md +++ b/public/features/12-列表命令行.mq.md @@ -14,16 +14,24 @@ description: 表排序/去重 + 命令行解析(中层 M5) # main -**raw = "name,score\nbob,2\nalice,10\n"** -**rows = > 逗号表.解析 内容=`raw`** -**rows = > 表.按键排序 list=`rows` key="name"** -**r0 = > at value=`rows` index=0** -> 打印 内容=[name](access(`r0`, "name")) +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | -**args = > split value="--input,scores.csv,--pretty" sep=","** -**flags = > 命令行.解析 参数=`args`** -> 打印 内容=[input](access(`flags`, "input")) +这里先按 name 字段对 CSV 记录排序,所以第一条姓名是 alice;score 在本例中仍是文本,尚未参与数值排序。排序函数返回新集合,重新保存 rows 才能让后续取值使用排序结果。随后构造三个命令参数并交给命令行库,读取 input 的文件名以及 pretty 的开关状态。 + +参数数组中的元素始终是数据:本例解析 scores.csv 这个名字,不会读取该文件,也不会启动命令解释器。用于真实进程调用时应继续保持逐个参数传递,选项文本要加引号,不要拼成 shell 源码。没有插件、网络和文件授权需求;缺少必须的业务参数时,应由上层根据解析结果决定是否继续,而不是仅看到 pretty 为真就认定所有输入有效。 + +我们先**raw = "name,score\nbob,2\nalice,10\n"**,供下一步使用。 +我们先**rows = [解析或排序当前行记录](逗号表.解析(内容=`raw`))**,供下一步使用。 +我们先**rows = [解析或排序当前行记录](表.按键排序(list=`rows`, key="name"))**,供下一步使用。 +我们先**r0 = [选择列表中的第一条记录](at(value=`rows`, index=0))**,供下一步使用。 +随后我们**[显示当前步骤的结果](> 打印 内容=[name](access(`r0`, "name")))**。 + +我们先**args = [构造逐项传递的命令参数](split(value="--input,scores.csv,--pretty", sep=","))**,供下一步使用。 +我们先**flags = [解析选项值与布尔开关](命令行.解析(参数=`args`))**,供下一步使用。 +随后我们**[显示当前步骤的结果](> 打印 内容=[input](access(`flags`, "input")))**。 1. [pretty](access(`flags`, "pretty")) - > 打印 内容=mid-m5-ok + 随后我们**[显示当前步骤的结果](> 打印 内容="mid-m5-ok")**。 2. * - > 打印 内容=mid-m5-fail + 随后我们**[显示当前步骤的结果](> 打印 内容="mid-m5-fail")**。 diff --git a/public/features/13-log-uuid.mq.md b/public/features/13-log-uuid.mq.md index 317c8a4..c4d6b8d 100644 --- a/public/features/13-log-uuid.mq.md +++ b/public/features/13-log-uuid.mq.md @@ -9,18 +9,23 @@ import: # Observable scripts without plugins + Default log level is info; raise to debug when you need more. Mint ids with uuid.v4. # main -> log.info text="mid-m6-start" +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | -> log.debug text="skipped-by-default" +We now **[Call log.info](> log.info text="mid-m6-start")**. -> log.set_level level="debug" +We now **[Call log.debug](> log.debug text="skipped-by-default")**. -> log.debug text="now-visible" +We now **[Call log.set level](> log.set_level level="debug")**. -**id = > uuid.v4** -**n = > len `id`** -> print text=`n` +We now **[Call log.debug](> log.debug text="now-visible")**. + +We first **id = [Compute id](uuid.v4())** for the next step. +We first **n = [Compute n](len(`id`))** for the next step. +We now **[Display this step's result](> print text=`n`)**. diff --git a/public/features/13-日志标识.mq.md b/public/features/13-日志标识.mq.md index 3623694..ccbd8c7 100644 --- a/public/features/13-日志标识.mq.md +++ b/public/features/13-日志标识.mq.md @@ -9,18 +9,26 @@ description: 按级别过滤的日志 + UUID 版本4(中层 M6) # 无插件的可观测脚本 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;本段完成下述操作,不额外返回业务数据。 | + 默认日志级别为 info;需要细节时再调到 debug。用 标识.版本4 生成 id。 # main -> 日志.信息 内容="中层-m6-开始" +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | -> 日志.调试 内容="默认会跳过" +随后我们**[执行 日志.信息](> 日志.信息 内容="中层-m6-开始")**。 -> 日志.设级别 级别="debug" +随后我们**[执行 日志.调试](> 日志.调试 内容="默认会跳过")**。 -> 日志.调试 内容="现在可见" +随后我们**[执行 日志.设级别](> 日志.设级别 级别="debug")**。 -**id = > 标识.版本4** -**n = > 长度 `id`** -> 打印 内容=`n` +随后我们**[执行 日志.调试](> 日志.调试 内容="现在可见")**。 + +我们先**id = [计算并保存 id](标识.版本4())**,供下一步使用。 +我们先**n = [计算并保存 n](长度(`id`))**,供下一步使用。 +随后我们**[显示当前步骤的结果](> 打印 内容=`n`)**。 diff --git a/public/features/14-datetime-url.mq.md b/public/features/14-datetime-url.mq.md index 2199e61..e5b6377 100644 --- a/public/features/14-datetime-url.mq.md +++ b/public/features/14-datetime-url.mq.md @@ -9,13 +9,18 @@ import: # Time and addresses without plugins + Moments are maps `{unix, zone, iso}`. Parse HTTPS URLs and round-trip query strings in `lib/url` (segment encoding stays in `net.url_encode`). # main -**epoch = > dt.from_unix unix=0 zone="Asia/Shanghai"** -> print text=[iso](access(`epoch`, "iso")) +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | -**u = > url.parse text="https://example.com/path?q=1#top"** -> print text=[host](access(`u`, "host")) -> print text=[query](access(`u`, "query")) +We first **epoch = [Compute epoch](dt.from_unix(unix=0, zone="Asia/Shanghai"))** for the next step. +We now **[Display this step's result](> print text=[iso](access(`epoch`, "iso")))**. + +We first **u = [Compute u](url.parse(text="https://example.com/path?q=1#top"))** for the next step. +We now **[Display this step's result](> print text=[host](access(`u`, "host")))**. +We now **[Display this step's result](> print text=[query](access(`u`, "query")))**. diff --git a/public/features/14-日期时间地址.mq.md b/public/features/14-日期时间地址.mq.md index 1df041a..d8c0ce0 100644 --- a/public/features/14-日期时间地址.mq.md +++ b/public/features/14-日期时间地址.mq.md @@ -13,9 +13,17 @@ description: 日历时刻 + URL/查询串(Mid2 M7) # main -**epoch = > 日时.自戳 秒=0 区="Asia/Shanghai"** -> print text=[iso](access(`epoch`, "iso")) +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | -**u = > 址.解析 内容="https://example.com/path?q=1"** -> print text=[host](access(`u`, "host")) -> print text=[query](access(`u`, "query")) +时间戳零表示同一个时间点;指定 Asia/Shanghai 后,ISO 展示采用该时区的当地时间。改变时区不应改变 unix 字段所代表的瞬间。固定时间戳使本例可以重复验证,不依赖机器当前时钟,也不要求读取时间服务。 + +地址解析只拆分给定的 HTTPS 文本,host 应为 example.com,query 保留 q=1。它不会访问服务器、验证网站可用性或把查询字符串当作本地文件名。后续需要查询参数时应使用地址库对应的查询解析能力,并保留转义和重复键的边界。时间与 URL 都返回有明确字段的记录;先按契约读取字段,再决定展示格式,避免把整份记录误当成最终用户需要的单段文本。 + +我们先**epoch = [构造固定时区的零时刻](日时.自戳(秒=0, 区="Asia/Shanghai"))**,供下一步使用。 +随后我们**[显示当前步骤的结果](> print text=[iso](access(`epoch`, "iso")))**。 + +我们先**u = [解析当前日期或 URL 输入](址.解析(内容="https://example.com/path?q=1"))**,供下一步使用。 +随后我们**[显示当前步骤的结果](> print text=[host](access(`u`, "host")))**。 +随后我们**[显示当前步骤的结果](> print text=[query](access(`u`, "query")))**。 diff --git a/public/features/15-toml-html-encoding.mq.md b/public/features/15-toml-html-encoding.mq.md index 9bf1f60..6125a01 100644 --- a/public/features/15-toml-html-encoding.mq.md +++ b/public/features/15-toml-html-encoding.mq.md @@ -10,17 +10,22 @@ import: # Config and safe text without plugins + Parse a TOML subset for tools, escape HTML before assembly, encode with base32. # main -**cfg = > toml.parse text="app = \"demo\"\n[server]\nport = 8080\n"** -> print text=[app](access(`cfg`, "app")) -**srv = [server](access(`cfg`, "server"))** -> print text=[port](access(`srv`, "port")) +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | -**safe = > html.escape text="<tag>"** -> print text=`safe` +We first **cfg = [Compute cfg](toml.parse(text="app = \"demo\"\n[server]\nport = 8080\n"))** for the next step. +We now **[Display this step's result](> print text=[app](access(`cfg`, "app")))**. +We first **srv = [server](access(`cfg`, "server"))** for the next step. +We now **[Display this step's result](> print text=[port](access(`srv`, "port")))**. -**b = > enc.base32_encode text="ok"** -> print text=`b` +We first **safe = [Compute safe](html.escape(text="<tag>"))** for the next step. +We now **[Display this step's result](> print text=`safe`)**. + +We first **b = [Compute b](enc.base32_encode(text="ok"))** for the next step. +We now **[Display this step's result](> print text=`b`)**. diff --git a/public/features/15-配置表超文本编码.mq.md b/public/features/15-配置表超文本编码.mq.md index 27b70f6..2b25884 100644 --- a/public/features/15-配置表超文本编码.mq.md +++ b/public/features/15-配置表超文本编码.mq.md @@ -12,11 +12,19 @@ description: TOML 配置 + HTML 转义 + base32(Mid2 M8) # main -**cfg = > 配置.解析 内容="app = \"演示\"\n"** -> print text=[app](access(`cfg`, "app")) +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | -**safe = > 超.转义 内容="<tag>"** -> print text=`safe` +三个步骤处理三种文本边界:TOML 解析得到 app 字段的记录,HTML 转义把尖括号变成普通可展示文本,Base32 把 UTF-8 输入编码为另一种文本表示。它们彼此独立,不能把配置解析、页面布局和编码混成一个隐藏的字符串处理流程。 -**b = > 编.基32编码 内容="ok"** -> print text=`b` +TOML 文本直接来自本页,读取真实配置文件时应先使用原生文件库;本例不会隐式寻找系统配置。HTML 转义适用于普通文本展示,不能代替 URL、脚本或样式上下文各自需要的处理,更不应因此拼接大量业务 HTML。Base32 只改变表示方法,不加密数据。所有结果都可继续传递给其他 Marqdo 函数,当前步骤不创建文件、不发送网络请求,也不需要外联解释器。 + +我们先**cfg = [解析显式提供的 TOML 配置](配置.解析(内容="app = \"演示\"\n"))**,供下一步使用。 +随后我们**[显示当前步骤的结果](> print text=[app](access(`cfg`, "app")))**。 + +我们先**safe = [将尖括号转义为普通展示文本](超.转义(内容="<tag>"))**,供下一步使用。 +随后我们**[显示当前步骤的结果](> print text=`safe`)**。 + +我们先**b = [把输入文本编码为 Base32](编.基32编码(内容="ok"))**,供下一步使用。 +随后我们**[显示当前步骤的结果](> print text=`b`)**。 diff --git a/public/features/16-fs-mid2.mq.md b/public/features/16-fs-mid2.mq.md index a780fe5..9cbe5ac 100644 --- a/public/features/16-fs-mid2.mq.md +++ b/public/features/16-fs-mid2.mq.md @@ -1,26 +1,33 @@ --- markup: occlusion -title: Mid stdlib — fs make_dirs, walk, stat -description: Recursive dirs, walk, and file metadata (Mid2 M9) +title: Native directory trees, enumeration and file metadata import: fs: lib/fs.mq.md --- -# Practical filesystem without plugins +This complete demonstration uses native filesystem tools. Call main with fs.write and a disposable --fs-root. It returns actual metadata and relative paths after cleaning its own temporary directory. -`make_dirs` / `remove_tree` / `stat` / `walk` thicken `lib/fs` for scripts and tools. +## main -# main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Actual byte size, directory entry count and relative paths | -> fs.make_dirs path="m9-demo/sub" +Create a unique temporary directory, then one child directory and one text file. Every write remains under the granted root, avoiding collisions with a pre-existing demo folder. Paths are built explicitly; no generated reader/writer or foreign process participates. -> fs.write_text path="m9-demo/readme.txt" text="ok" +The content ok occupies two UTF-8 bytes. File size measures stored bytes rather than text character count. Enumeration returns relative paths for the child directory and file; counting those paths is another distinct observation. The example does not depend on operating-system enumeration order. Sort explicitly if a later workflow requires stable ordering. -**st = > fs.stat path="m9-demo/readme.txt"** -> print text=[size](access(`st`, "size")) +Collect the real metadata and paths before removing this run's unique tree. Returned paths describe an observation, not still-live artifacts. A failure can retain its native diagnostic and this run's directory for caller inspection. Cleanup must stay scoped to the directory created by this invocation. -**w = > fs.walk path="m9-demo"** -**n = > len `w`** -> print text=`n` +We **work = [Create a unique directory inside the granted root](fs.temp_dir(prefix="fs-tree-demo"))** and **child = work + "/sub"** and **note = work + "/readme.txt"**. +We **[Create this run own child directory](fs.make_dirs(path=`child`))** and **[Write the exact UTF-8 example content](fs.write_text(path=`note`, text="ok"))**. +We **metadata = [Read the actual file metadata](fs.stat(path=`note`))** and **paths = [Enumerate this run directory entries](fs.walk(path=`work`))** and **size = [Retain storage byte size](access(metadata, "size"))** and **entries = [Count the actual enumerated paths](len(`paths`))**. +We **[Remove only this run unique directory tree](fs.remove_tree(path=`work`))** after collecting the observations. -> fs.remove_tree path="m9-demo" +`observed` = + +| size | entries | paths | +|---|---|---| +| `size` | `entries` | `paths` | + +After observing and cleaning this run we return *observed*. diff --git a/public/features/16-文件mid2.mq.md b/public/features/16-文件mid2.mq.md index 40d2658..be7898f 100644 --- a/public/features/16-文件mid2.mq.md +++ b/public/features/16-文件mid2.mq.md @@ -1,24 +1,33 @@ --- markup: occlusion -title: 中层标准库 — 文件目录树与状态 -description: 递归目录、遍历与元数据(Mid2 M9) -导入: +title: 原生目录树、遍历与文件状态 +import: 文件: lib/文件.mq.md --- -# 无需插件的实用文件系统 +使用固有文件库完成整个演示。调用 main 时授予 fs.write,并指定独立的 --fs-root。函数返回实际元数据与相对路径列表,正常结束后清理自己的临时目录。 -# main +## main -> 文件.建目录树 路径="m9-演示/子" +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 真实文件字节数、目录条目数与相对路径列表 | -> 文件.写文本 路径="m9-演示/说明.txt" 内容="好" +本轮先创建唯一临时目录,再在其中建立子目录和文本文件,避免固定的演示名称与已有目录冲突。创建和写入都受 --fs-root 约束,目录参数并不授予访问其他位置的权限。所有路径由当前流程明确构造,没有外部脚本代为读取或修改正文。 -**st = > 文件.状态 路径="m9-演示/说明.txt"** -> print text=[size](access(`st`, "size")) +内容“好”占三个 UTF-8 字节,size 描述存储大小而不是字符数。遍历结果包含文件和子目录的相对路径,条目数与字符串长度也是不同的量。本例只观察枚举内容,不依赖操作系统给出的顺序;需要稳定排序时应继续组合表库。 -**w = > 文件.遍历 路径="m9-演示"** -**n = > 长度 `w`** -> print text=`n` +实际观察值保存后删除本轮独有的临时树。返回的路径列表描述已经观察过的内容,不是仍然存在的文件句柄。中途失败保留原生诊断与可能留下的本轮目录,调用方可以检查后清理,不应递归删除与演示无关的用户目录。 -> 文件.删目录树 路径="m9-演示" +先**work = [创建本轮独有的授权临时目录](文件.临时目录(前缀="文件树演示"))**和**child = work + "/子"**及**note = work + "/说明.txt"**。 +接着**[递归创建本轮子目录](文件.建目录树(路径=`child`))**,并**[写入一个明确的 UTF-8 字符](文件.写文本(路径=`note`, 内容="好"))**。 +观察时保存**metadata = [读取真实文件元数据](文件.状态(路径=`note`))**和**paths = [枚举本轮目录里的实际条目](文件.遍历(路径=`work`))**及**size = [保留存储字节数](access(metadata, "size"))**和**entries = [保留遍历条目数](长度(`paths`))**。 +最后**[只清理本轮独有的目录树](文件.删目录树(路径=`work`))**,再组织实际观察值。 + +`observed` = + +| size | entries | paths | +|---|---|---| +| `size` | `entries` | `paths` | + +完成观察与清理后,我们返回*observed*。 diff --git a/public/features/17-stats-log.mq.md b/public/features/17-stats-log.mq.md index 803d8aa..3489945 100644 --- a/public/features/17-stats-log.mq.md +++ b/public/features/17-stats-log.mq.md @@ -9,10 +9,15 @@ import: # Closing Mid2 sugar + Light statistics and optional `fields=` on log lines — no remote sinks, no dataframes. # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + `xs` = | | @@ -21,8 +26,8 @@ Light statistics and optional `fields=` on log lines — no remote sinks, no dat | 20 | | 30 | -**m = > stats.mean list=`xs`** -> print text=`m` +We first **m = [Compute m](stats.mean(list=`xs`))** for the next step. +We now **[Display this step's result](> print text=`m`)**. `fld` = @@ -30,4 +35,4 @@ Light statistics and optional `fields=` on log lines — no remote sinks, no dat |------|--------| | done | ok | -> log.info text="mid2-m10" fields=`fld` +We now **[Call log.info](> log.info text="mid2-m10" fields=`fld`)**. diff --git a/public/features/17-统计日志.mq.md b/public/features/17-统计日志.mq.md index 167713b..0052614 100644 --- a/public/features/17-统计日志.mq.md +++ b/public/features/17-统计日志.mq.md @@ -11,6 +11,14 @@ description: 薄均值/中位数/标准差 + 日志 fields(Mid2 M10) # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + +数值列表包含十、二十和三十,平均值应为二十。这里把数据写成一列表格,让读者能直接核对输入,而不是在外部解释器中再构造同一份列表。统计函数不修改原集合;需要中位数、标准差或空集合策略时,应继续阅读统计库对应函数的独立契约。 + +结构化日志同时携带消息与步骤、状态字段,用于后续过滤或诊断。日志输出不是函数的业务返回值,也不能作为已经完成某项发布或文件写入的证据。本例没有文件和网络操作;实际日志目的地与权限沿用日志库的运行环境规则。若后续任务依赖统计结果,就应直接传递 m 的数值,而不是重新解析打印文本或把最后一条日志当作成功标志。 + `xs` = | | @@ -19,8 +27,8 @@ description: 薄均值/中位数/标准差 + 日志 fields(Mid2 M10) | 20 | | 30 | -**m = > 统计.均值 列表=`xs`** -> print text=`m` +我们先**m = [计算列表的算术平均值](统计.均值(列表=`xs`))**,供下一步使用。 +随后我们**[显示当前步骤的结果](> print text=`m`)**。 `fld` = @@ -28,4 +36,4 @@ description: 薄均值/中位数/标准差 + 日志 fields(Mid2 M10) |------|------| | 完成 | ok | -> 日志.信息 内容="mid2-m10" 字段=`fld` +随后我们**[执行 日志.信息](> 日志.信息 内容="mid2-m10" 字段=`fld`)**。 diff --git a/public/features/18-AI原生闭环.mq.md b/public/features/18-AI原生闭环.mq.md index 6ca5951..4f5500d 100644 --- a/public/features/18-AI原生闭环.mq.md +++ b/public/features/18-AI原生闭环.mq.md @@ -6,6 +6,10 @@ description: 渐进式契约、结构化诊断与面向 AI 的 Marqdo 语言服 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 里程碑(v1.1.0):AI 原生闭环——让 AI 不仅能写 Marqdo,还能验证 Marqdo。 三件套。核心表面守卫(`doc/design/core-surface.md`)钉住 19 个核心构造,任一侧(清单 / 文档 / 金样)单边改动,CI 必红。渐进式契约是可选的 `参数` / `返回` / `字段` 表,直接嵌在叙述里,四边界校验:调用实参、返回值、表绑定、键访问。MLSP for AI(`marqdo mlsp`)是行分隔 JSON 的语言服务,AI 按需查询语法,而不是背诵整部语法。 @@ -30,10 +34,10 @@ printf '%s\n' '{"id":1,"method":"syntax","params":{"query":"返回"}}' | marqdo MLSP 方法:`locate`(查符号 / 构造卡片)、`syntax`(戒律原文 + 样例 + 文档锚点)、`validate`(结构化诊断)、`repair_targets`(有界靶点)、`repair_apply`(有界行编辑,越界必拒)、`schema`(单元契约)。 -> print text=契约是可选的:不写契约表,文件保持全动态。 +随后我们**[显示当前步骤的结果](> print text="契约是可选的:不写契约表,文件保持全动态。")**。 -> print text=诊断自带 code / severity / suggestion / doc_anchor / doc_quote。 +随后我们**[显示当前步骤的结果](> print text="诊断自带 code / severity / suggestion / doc_anchor / doc_quote。")**。 -> print text=MLSP 语法卡片内嵌戒律原文与样例,AI 无需预学语法。 +随后我们**[显示当前步骤的结果](> print text="MLSP 语法卡片内嵌戒律原文与样例,AI 无需预学语法。")**。 验证结果见:`doc/roadmap/perf-validation-report-2026-09-23.md`。 diff --git a/public/features/18-ai-native-loop.mq.md b/public/features/18-ai-native-loop.mq.md index 3c2116e..47ca0d8 100644 --- a/public/features/18-ai-native-loop.mq.md +++ b/public/features/18-ai-native-loop.mq.md @@ -6,6 +6,10 @@ description: Progressive contracts, structured diagnostics, and the Marqdo Langu # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Milestone (v1.1.0): the AI-native loop — so an AI can verify Marqdo, not just write it. Three pieces. A core surface guard (`doc/design/core-surface.md`) pins the 19 core constructs, so a single-sided change (list / doc / golden sample) turns CI red. Progressive contracts are optional `参数` / `返回` / `字段` tables embedded in the narrative, checked at four boundaries: call argument, return, table bind, key access. MLSP for AI (`marqdo mlsp`) is a line-delimited JSON language service; the AI queries syntax on demand instead of memorizing the whole grammar. @@ -30,10 +34,10 @@ printf '%s\n' '{"id":1,"method":"syntax","params":{"query":"返回"}}' | marqdo MLSP methods: `locate` (find a symbol / construct card), `syntax` (rule text + sample + doc anchor), `validate` (structured diagnostics), `repair_targets` (bounded span), `repair_apply` (bounded line edits, out-of-scope refused), `schema` (contract of one unit). -> print text=Contracts are optional: with no contract table, a file stays fully dynamic. +We now **[Display this step's result](> print text="Contracts are optional: with no contract table, a file stays fully dynamic.")**. -> print text=Diagnostics carry code, severity, suggestion, doc_anchor and doc_quote. +We now **[Display this step's result](> print text="Diagnostics carry code, severity, suggestion, doc_anchor and doc_quote.")**. -> print text=MLSP syntax cards embed the rule text and a sample, so AI need not pre-learn the grammar. +We now **[Display this step's result](> print text="MLSP syntax cards embed the rule text and a sample, so AI need not pre-learn the grammar.")**. See validation results: `doc/roadmap/perf-validation-report-2026-09-23.md`. diff --git a/public/features/19-foreign-view-cells.mq.md b/public/features/19-foreign-view-cells.mq.md index 4aa27c6..b1d8c0e 100644 --- a/public/features/19-foreign-view-cells.mq.md +++ b/public/features/19-foreign-view-cells.mq.md @@ -1,34 +1,57 @@ --- markup: occlusion -title: Foreign kernels v2 — Python analysis in view -description: Kernel state, Marqdo-to-kernel values and view cells — without a stdin-only demo +title: Native analysis and an explicit Intl formatting boundary import: foreign: lib/foreign.mq.md + table: lib/table.mq.md + result: lib/result.mq.md + native: ../../examples/foreign-native-report/index.mq.md --- -# main +This page keeps order analysis in Marqdo and uses Node Intl only for locale-aware +currency formatting. Read [the actual native report tools](../../examples/foreign-native-report/index.mq.md) +for their independently callable input and return contracts. That single module +contains grouping, population statistics and the bounded persistent formatter. -This page shows the foreign runtime as a language feature: a persistent kernel, explicit state from Marqdo values, and view cells that share kernel state. It never asks the reader to type JSON into stdin. +Call this page's main with process.exec for a full workflow, or call analyze_orders +in that module with no effects for native analysis alone. View evaluates the same +cells with shared state and isolated kernels. No Python interpreter is needed. ---- +## main -Probe the interpreter first. The result is ordinary Marqdo data. +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | View-session plan plus the native report and checked localized formatting | -**python = > foreign.probe lang="python"** +This complete page uses six ordinary orders: their native total is 950, count +is six, and the four regional rows retain count, total, mean and normalized span. +The pure analysis is independently callable in the linked module. Formatting is a separate +capability with an explicit process.exec grant and an installed Node runtime. +The successful return contains report and formatting alongside the view-session +plan; it contains no live kernel handle and can be returned by marqdo call. -> print text=[ok](access(`python`, "ok")) -> print text=[version](access(`python`, "version")) +The view gets the same native report copied into two named kernels. Its cells +perform presentation rather than reimplementing native grouping or arithmetic. +Run All first initializes the formatter in the analysis kernel, then a second +cell reuses it. The review kernel receives its own report copy and formatter. +This demonstrates both shared state and kernel isolation. Running the dependent +formatting cell before its initializer should show the real missing-state error. ---- +Static View export evaluates those same cells and embeds actual stdout. +Interactive View retains their kernels for later runs. The low-level formatter +used to check the public return is opened and closed separately, so it cannot +secretly supply state to the view kernels. No stdin, notebook command, generated +file-reader program or package installation is hidden in this example. +If Node or formatting fails, the page returns that failure before declaring a +ready view. Native-only consumers can still call analyze_orders with no effects. +The table cells below are data, while the three bound node fences are explicit +foreign code. The distinction is visible without translating a Python workflow +into another ad hoc command sequence. -Marqdo values into a kernel. +`orders` = -The `订单` table is a normal Marqdo value. `foreign.session_set` copies it into the Python kernel as JSON; no shell and no stdin. - -`订单` = - -| @ | 区域 | 金额 | -|---|------|------| +| @ | region | amount | +|---|---|---| | 1 | 华东 | 120 | | 2 | 华东 | 300 | | 3 | 华南 | 90 | @@ -36,119 +59,58 @@ The `订单` table is a normal Marqdo value. `foreign.session_set` copies it int | 5 | 华北 | 220 | | 6 | 西部 | 80 | -**内核会话 = > foreign.session_open lang="python"** +We **report = [Perform all analysis in Marqdo](native.analyze_orders(orders=`orders`))** and **formatted = [Use the genuine external formatting boundary](native.format_summary(report=`report`))**. +1. not access(`formatted`, "ok") + Return *formatted* before declaring an executable view ready. -**> foreign.session_set id=`内核会话` name="orders" value=`订单`** - -`total_code` = -```python -round(sum(float(row["金额"]) for row in orders), 2) -``` - -**total = > foreign.session_eval id=`内核会话` code=`total_code`** - -> print text=[result](access(`total`, "result")) - -The low-level kernel session is managed entirely by `foreign`; the table crossed the boundary as an explicit JSON copy. - ---- - -Kernel state persists. - -Two evaluations share the same kernel. The second sees the first variable. - -`set_values_code` = -```python -values = [3, 4, 5] -``` - -**> foreign.session_eval id=`内核会话` code=`set_values_code`** - -`square_sum_code` = -```python -sum(value * value for value in values) -``` - -**square_sum = > foreign.session_eval id=`内核会话` code=`square_sum_code`** - -> print text=[result](access(`square_sum`, "result")) - -**> foreign.session_close id=`内核会话`** - -This is kernel state, not a one-shot process. It is created, queried and closed through `foreign`. - ---- - -View cells share state. - -`foreign.session` declares a view session from ordinary tables. The table names are free; this document uses `分析内核` and `分析单元`. - -`分析内核` = +`kernels` = | @ | 名称 | 语言 | -|---|------|------| -| 1 | 分析 | python | -| 2 | 复核 | python | +|---|---|---| +| 1 | 分析 | node | +| 2 | 复核 | node | -`分析单元` = +`cells` = | @ | 单元 | 内核 | -|---|------|------| +|---|---|---| | 1 | 计算 | 分析 | -| 2 | 复核 | 复核 | +| 2 | 格式化 | 分析 | +| 3 | 复核 | 复核 | -`初始值` = +`initial` = -| 内核 | 名称 | 值 | -|------|------|----| -| 分析 | orders | `订单` | -| 复核 | orders | `订单` | +| @ | 内核 | 名称 | 值 | +|---|---|---|---| +| 1 | 分析 | report | `report` | +| 2 | 复核 | report | `report` | -`会话` = > foreign.session kernels=`分析内核` cells=`分析单元` values=`初始值` +We **会话 = [Declare the view with native values and explicit kernels](foreign.session(kernels=`kernels`, cells=`cells`, values=`initial`))**. `计算` = -```python -import json -import statistics +```node +var money = new Intl.NumberFormat("en-US", {style:"currency", currency:"CNY"}); +console.log(JSON.stringify(report)); +``` -by_region = {} -for row in orders: - by_region.setdefault(row["区域"], []).append(float(row["金额"])) - -summary = [] -for region, values in sorted(by_region.items()): - mean = statistics.mean(values) - sd = statistics.pstdev(values) or 1.0 - summary.append({ - "region": region, - "orders": len(values), - "total": round(sum(values), 2), - "mean": round(mean, 2), - "z_span": round((max(values) - mean) / sd, 3), - }) - -print(json.dumps({ - "regions": summary, - "total": round(sum(float(row["金额"]) for row in orders), 2), - "count": len(orders), -}, ensure_ascii=False)) +`格式化` = +```node +console.log(money.format(report.total)); +console.log(money.format(report.average)); ``` `复核` = -```python -import json - -print(json.dumps({ - "kernel": "复核", - "count": len(orders), - "total": round(sum(float(row["金额"]) for row in orders), 2), -}, ensure_ascii=False)) +```node +var reviewMoney = new Intl.NumberFormat("en-US", {style:"currency", currency:"CNY"}); +console.log(JSON.stringify({count:report.count, total:reviewMoney.format(report.total)})); ``` -`查看` consumes the `会话` handle. Run All runs `计算` in the `分析` kernel and `复核` in the `复核` kernel; the static export runs the same cells and embeds their real outputs. +We **formatting = [Retain the checked persistent-kernel result](access(formatted, "value"))**. -The important language point: +`evidence` = -The `初始值` table passes the same Marqdo `订单` value into both kernels. Kernel state lives in `foreign`. View only renders the handle and its cells. `run` still executes the same document as a program. +| report | formatting | +|---|---| +| `report` | `formatting` | -There is no separate notebook CLI, no stdin requirement in this example, and no hidden language switch. +Return *[The executable view plan with native analysis evidence](table.merge(a=`会话`, b=`evidence`))*. diff --git a/public/features/19-外联视图单元.mq.md b/public/features/19-外联视图单元.mq.md index ad489f2..8dde8e1 100644 --- a/public/features/19-外联视图单元.mq.md +++ b/public/features/19-外联视图单元.mq.md @@ -1,34 +1,38 @@ --- markup: occlusion -title: 外联内核 v2 — Python 分析(view 单元) -description: 内核态、Marqdo 值传入与 view 单元 —— 不依赖 stdin 的完整示例 -导入: +title: 原生分析与明确的 Intl 格式化边界 +import: 外联: lib/外联.mq.md + 表: lib/table.mq.md + 例程: ../../examples/foreign-native-report/index.mq.md --- -# main +先用固有能力,外联只补真实的能力缺口。本页复用 [原生报告例程](../../examples/foreign-native-report/index.mq.md),让统计在 Marqdo 中完成,再通过已支持的 Node 持久内核使用 Intl。阅读例程的源码即可找到可以独立调用的参数、返回值与失败约束。 -这一页把外联运行时当作语言能力来展示:持久内核、从 Marqdo 值显式传入状态,以及共享内核状态的 view 单元。读者不需要向 stdin 输入 JSON。 +在仓库根目录调用 marqdo call public/features/19-外联视图单元.mq.md main --effects process.exec --fs-root . --json 可以获得真实报告与视图计划。使用 view 导出同一份源码即可运行下面声明的单元。这里采用函数标题 main,便于作为工具直接调用;不需要 Python 解释器或另一套笔记本入口。 ---- +## main -先探测解释器。结果仍然是普通 Marqdo 数据。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 包含 report、formatting 及内核/单元/初始值的视图计划;失败时返回实际 Result | -**python = > 外联.探测 语言="python"** +格式化结果中的数字会显示为 950.00 与 158.33,货币标志由区域设置决定;原生 report 保留未格式化的数值。 -> 打印 内容=[ok](access(`python`, "ok")) -> 打印 内容=[version](access(`python`, "version")) +本页的六笔订单全部由 Marqdo 固有能力处理,得到合计 950、数量六、四个区域的订单数、合计、均值和总体标准化跨度。分组、排序、统计与数值运算都不需要外部脚本;真正交给 Node 的只有 Intl 本地化货币格式。直接调用本页 main 需要 process.exec,Node 应预先安装。成功返回的计划包含 report 原始报告和 formatting 展示结果,调用者可以继续验证具体数值。 ---- +共享例程有独立的参数及返回表,区域键和金额键都由调用者明确指定,因此中文字段不需要重命名成另一套 JSON 拼接语言。本页和英文页共同调用一份原生算法,避免两个版本逐渐出现不同的统计规则。纯数据分析可以直接调用例程的 analyze_orders,不需要任何进程授权;空输入、单元素区域与相同金额的区域也有清楚的定义。金额只是示例数值,展示的两位小数由 Intl 决定,不宣称是金融十进制定点模型。 -Marqdo 值进入内核。 +视图的分析内核先输出已经算好的报告,并创建本地化格式器;同一内核中的第二个单元继续使用这个格式器。因此 Run All 的顺序是明确的执行依赖,直接先运行格式化单元应展示真实的未初始化状态。复核单元使用另一份内核和自己的格式器,体现状态隔离。两个内核收到的是报告的数据拷贝,谁都不会重新实现一份分组算法,也不会修改 Marqdo 的源订单。 -`订单` 表是普通 Marqdo 值。`外联.会话设值` 把它作为 JSON 复制进 Python 内核;没有 shell,也没有 stdin。 +用于验证工具返回值的低层格式化例程单独创建并关闭了一个持久内核:第一次求值创建格式器,第二次复用状态。它检查每次求值的 ok,遇到可恢复错误时关闭仍存活的内核,再返回真实诊断。用于视图的会话随后才被声明;工具验证的内核不能暗中给视图提供状态。视图的静态导出与交互模式运行同一批单元,输出来自实际执行,不用预写的通过文字冒充结果。 + +正文先交代数据来源和边界,再把调用放入相应的句子。下面的订单、内核、单元和初始值都是普通表格;三段绑定的 node 围栏才是明确外联的代码。整个操作不要求向终端输入 JSON,也不生成文件读取器。若解释器不可用或格式化失败,会在创建可用视图之前把失败交给调用者。 `订单` = | @ | 区域 | 金额 | -|---|------|------| +|---|---|---| | 1 | 华东 | 120 | | 2 | 华东 | 300 | | 3 | 华南 | 90 | @@ -36,119 +40,58 @@ Marqdo 值进入内核。 | 5 | 华北 | 220 | | 6 | 西部 | 80 | -**内核会话 = > 外联.会话开启 语言="python"** +我们先**报告 = [使用固有库完成分组和总体统计](例程.analyze_orders(orders=`订单`, region_key="区域", amount_key="金额"))**,再**格式结果 = [把真正缺失的本地化展示交给 Intl](例程.format_summary(report=`报告`, locale="zh-CN"))**。 +1. not access(`格式结果`, "ok") + 返回*格式结果*,保留外联解释器或格式化的真实失败。 -**> 外联.会话设值 标识=`内核会话` 名称="orders" 值=`订单`** - -`合计代码` = -```python -round(sum(float(row["金额"]) for row in orders), 2) -``` - -**合计 = > 外联.会话求值 标识=`内核会话` 代码=`合计代码`** - -> 打印 内容=[result](access(`合计`, "result")) - -低层内核会话完全由 `外联` 管理;表格以显式 JSON 拷贝跨过边界。 - ---- - -内核态是持续的。 - -两次求值共享同一个内核。第二次能看到第一次创建的变量。 - -`设值代码` = -```python -values = [3, 4, 5] -``` - -**> 外联.会话求值 标识=`内核会话` 代码=`设值代码`** - -`平方和代码` = -```python -sum(value * value for value in values) -``` - -**平方和 = > 外联.会话求值 标识=`内核会话` 代码=`平方和代码`** - -> 打印 内容=[result](access(`平方和`, "result")) - -**> 外联.会话关闭 标识=`内核会话`** - -这是内核态,不是一次性进程。它由 `外联` 创建、查询和关闭。 - ---- - -view 单元共享状态。 - -`外联.会话` 从普通表格声明一个 view 会话。表名完全自由;本页用 `分析内核` 和 `分析单元`。 - -`分析内核` = +`内核` = | @ | 名称 | 语言 | -|---|------|------| -| 1 | 分析 | python | -| 2 | 复核 | python | +|---|---|---| +| 1 | 分析 | node | +| 2 | 复核 | node | -`分析单元` = +`单元` = | @ | 单元 | 内核 | -|---|------|------| +|---|---|---| | 1 | 计算 | 分析 | -| 2 | 复核 | 复核 | +| 2 | 格式化 | 分析 | +| 3 | 复核 | 复核 | `初始值` = -| 内核 | 名称 | 值 | -|------|------|----| -| 分析 | orders | `订单` | -| 复核 | orders | `订单` | +| @ | 内核 | 名称 | 值 | +|---|---|---|---| +| 1 | 分析 | report | `报告` | +| 2 | 复核 | report | `报告` | -`会话` = > 外联.会话 内核表=`分析内核` 单元表=`分析单元` 值表=`初始值` +接着**会话 = [用普通表格声明显式的视图会话](外联.会话(内核表=`内核`, 单元表=`单元`, 值表=`初始值`))**,让两份内核获得同一个原生报告的独立 JSON 拷贝。 `计算` = -```python -import json -import statistics +```node +var money = new Intl.NumberFormat("zh-CN", {style:"currency", currency:"CNY"}); +console.log(JSON.stringify(report)); +``` -by_region = {} -for row in orders: - by_region.setdefault(row["区域"], []).append(float(row["金额"])) - -summary = [] -for region, values in sorted(by_region.items()): - mean = statistics.mean(values) - sd = statistics.pstdev(values) or 1.0 - summary.append({ - "region": region, - "orders": len(values), - "total": round(sum(values), 2), - "mean": round(mean, 2), - "z_span": round((max(values) - mean) / sd, 3), - }) - -print(json.dumps({ - "regions": summary, - "total": round(sum(float(row["金额"]) for row in orders), 2), - "count": len(orders), -}, ensure_ascii=False)) +`格式化` = +```node +console.log(money.format(report.total)); +console.log(money.format(report.average)); ``` `复核` = -```python -import json - -print(json.dumps({ - "kernel": "复核", - "count": len(orders), - "total": round(sum(float(row["金额"]) for row in orders), 2), -}, ensure_ascii=False)) +```node +var reviewMoney = new Intl.NumberFormat("zh-CN", {style:"currency", currency:"CNY"}); +console.log(JSON.stringify({count:report.count, total:reviewMoney.format(report.total)})); ``` -`查看` 消费 `会话` 句柄。Run All 在 `分析` 内核执行 `计算`,在 `复核` 内核执行 `复核`;静态导出走同一批单元,并把真实输出嵌入页面。 +我们**展示 = [保留已经检查过的持久格式化结果](access(格式结果, "value"))**,把数据与展示来源一并交给调用者。 -语言上的重点: +`依据` = -`初始值` 表把同一个 Marqdo `订单` 值传给两个内核。内核态归 `外联` 管理。view 只渲染句柄和单元。`run` 仍然把同一份文档当程序执行。 +| report | formatting | +|---|---| +| `报告` | `展示` | -没有单独的 notebook CLI,这个示例不依赖 stdin,也没有隐藏的语言切换。 +所有值准备好后返回*[带原生分析依据的可执行视图计划](表.merge(a=`会话`, b=`依据`))*。 diff --git a/public/features/20-OKF与EKC.mq.md b/public/features/20-OKF与EKC.mq.md index 40819a8..5fa515f 100644 --- a/public/features/20-OKF与EKC.mq.md +++ b/public/features/20-OKF与EKC.mq.md @@ -6,6 +6,10 @@ description: Marqdo 如何以一份可执行源为唯一权威,把它投影成 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + Marqdo 的宪法是「代码即文档,文档即知识库」。`.mq.md` 不是程序截图:它同时是可读源码、可执行单元和知识页。 这个承诺只有在知识始终从源派生时才成立。OKF 提供可移植知识包的形态;EKC 提供工程化投影。二者都不成为第二份权威。 @@ -21,7 +25,7 @@ OKF(Open Knowledge Format)用 Markdown + YAML frontmatter 表示知识:一 ```yaml type: Capability title: 持久外联内核 -description: 在命名内核中运行 Python 或 Node 并保留状态 +description: 向显式声明的本地内核传递原生数据并保留状态 resource: public/features/19-外联视图单元.mq.md status: stable verified: @@ -63,7 +67,7 @@ EKC 把仓库投影成工程知识系统,并在 Agent 写新代码前提供 pr |---|---|---| | L0 Repository | 语言、规模、根目录 | 仓库总览 | | L1 Module | imports、exports、职责 | 外联内核模块 | -| L2 Symbol | 签名、调用、指纹 | Python 分析函数 | +| L2 Symbol | 签名、调用、指纹 | 外部源码中的函数 | | L3 Capability | 工程能做什么 | 运行持久外联内核 | | L4 Knowledge | 决策、约束、失败 | 为什么状态桥必须显式 | @@ -119,7 +123,7 @@ marqdo knowledge verify 一个知识页说“这个工程能分析订单”,就必须指向一个真正能跑的 `.mq.md` 资源。这是 OKF 形态的笔记与可执行知识系统的区别。 -在外联示例里,页面本身就是证明:Python 调用、持久内核和状态桥都从读者正在看的同一份 Markdown 源运行。没有另一个会漂移的演示项目。 +外联示例先用 Marqdo 固有能力分析订单,再把本地化展示交给 Node Intl。显式导入指向共享的可调用报表手册,页面本身声明实际的视图内核、原生值与单元。验收仍要检查逐单元的真实结果,不能把一份可序列化计划当作单元已经运行成功的证明。 --- diff --git a/public/features/20-okf-ekc.mq.md b/public/features/20-okf-ekc.mq.md index 813c11a..8c77599 100644 --- a/public/features/20-okf-ekc.mq.md +++ b/public/features/20-okf-ekc.mq.md @@ -6,6 +6,10 @@ description: How Marqdo keeps one executable source of truth while projecting it # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Marqdo's constitution is code as documentation and documentation as knowledge. A `.mq.md` file is not a screenshot of a program: it is the readable source, the executable unit and the knowledge page at the same time. That claim matters only if the knowledge stays derived from the source. OKF gives us the shape of a portable knowledge bundle; EKC gives us the engineering projection. Neither becomes a second source of truth. @@ -21,7 +25,7 @@ A concept page can therefore point at the exact file that proves it: ```yaml type: Capability title: Persistent foreign kernels -description: Run Python or Node in a named, stateful kernel +description: Run an explicitly declared local kernel with native data resource: public/features/19-foreign-view-cells.mq.md status: stable verified: @@ -63,7 +67,7 @@ EKC projects the repository into an engineering knowledge system, then exposes i |---|---|---| | L0 Repository | language, size, roots | repository summary | | L1 Module | imports, exports, responsibility | a foreign kernel module | -| L2 Symbol | signature, calls, fingerprint | a Python analysis function | +| L2 Symbol | signature, calls, fingerprint | a function in external source code | | L3 Capability | what the project can do | run a persistent foreign kernel | | L4 Knowledge | decisions, constraints, failures | why the bridge is explicit | @@ -119,7 +123,7 @@ Every claimed capability has an executable resource. A knowledge page that says “this project can analyze orders” must point to a `.mq.md` resource that actually runs. That is the difference between an OKF-shaped note and an executable knowledge system. -In the foreign example, the page itself is the proof: the Python call, the persistent kernel and the state bridge all run from the same Markdown source that a reader is looking at. There is no separate demo project to drift out of sync. +The foreign example computes its order report in native Marqdo and uses Node Intl for locale-aware presentation. Explicit imports point to the shared callable report handbook, while the page declares the actual view kernels, values and cells. Inspect the real per-cell results; a serialized plan alone does not establish that its cells ran successfully. --- diff --git a/public/features/21-persistence.mq.md b/public/features/21-persistence.mq.md index 5c95076..2e8e355 100644 --- a/public/features/21-persistence.mq.md +++ b/public/features/21-persistence.mq.md @@ -1,58 +1,58 @@ --- markup: occlusion -title: Persisting foreign execution results -description: Static snapshots and writeback — how foreign results survive after the process exits +title: Persist an actual formatting result through native writeback import: - foreign: lib/foreign.mq.md + guide: ../../doc/library-development.mq.md + formatter: ../../examples/foreign-native-report/index.mq.md writeback: lib/writeback.mq.md + result: lib/result.mq.md --- -# main +The source remains the manual for this file operation. Its callable main computes +native data, crosses a genuine formatting boundary, checks the result and records +only the successful value. Invoke with process.exec,fs.write and --fs-root .; +static View uses the same source and embeds its actual observed output. -Foreign code has two useful lives: as a published snapshot, and as a living document whose latest result is kept in source. They answer different questions and should not be confused. +## main ---- +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with the actual string recorded in this source's total slot | -Static snapshot: publish the result. +A static View snapshot embeds executed output in HTML. Explicit writeback +instead keeps a selected value in this source file's named slot. A caller should +choose that file effect deliberately: this main needs process.exec and fs.write, +with --fs-root pointing at the repository. Reading the page alone does not write. -`marqdo view output` executes the document's cells and embeds their real output in the generated HTML. The `.mq.md` source is not modified. This is the default choice for user documentation, reviews and stable links: a reader sees the result without running anything, and the source stays clean. +The amount is computed by the native programming guide, then the shared example +uses Node Intl only for locale-aware currency formatting. Its persistent kernel +is closed before this page receives the result. No Python process, foreign file +writer or duplicated arithmetic participates. The exact returned string is then +passed to lib/writeback, so the file operation remains a Marqdo capability. -The static snapshot is a point-in-time artifact. If an external service changes, rebuild it; do not treat it as a live dashboard. +The total slot below is actual recorded output. Repeated execution replaces that +same key rather than appending another slot. An unavailable interpreter or failed +formatting returns before the write; native write-policy or IO faults retain +their diagnostics. Writeback persists this selected ordinary value, not a live +kernel or arbitrary process memory. Review source changes with the repository's +normal diff workflow. For published docs use a static snapshot unless a living +auditable source result is intended, as it explicitly is in this demonstration. ---- +We **amount = [Compute the native amount](guide.计算金额(单价=190, 数量=5))**. -Writeback: keep the result in the source. +`report` = -For an exploratory or audit document, pair `foreign` with `lib/writeback`. `writeback.record` writes a keyed output slot next to the call. The slot is visible in the Markdown source, can be reviewed in a diff and can be committed with the document. +| total | average | +|---|---| +| `amount` | `amount` | -| Step | What it does | -|------|--------------| -| Foreign run / Foreign session | Execute the foreign code and return a Marqdo value | -| Writeback record | Persist that value in a named slot | -| git diff | Review the changed result like any other document change | - -A real writeback in this page. - -This page is itself the runnable example. The code fence below is ordinary Marqdo data; `foreign.run` executes it, then `writeback.record` writes the `total` slot into this source file. - -`写回代码` = -```python -print(950) -``` - -**结果 = > foreign.run code=`写回代码`** - -**> writeback.record value=`结果` key="total"** +We **formatted = [Use only the actual Intl presentation gap](formatter.format_summary(report=`report`))**. +1. not access(`formatted`, "ok") + Return *formatted* before writing a result slot. +We **text = [Select the actual formatter output](access(access(formatted, "value"), "total"))**. +We **written = [Persist this actual output through Marqdo's native writeback](writeback.record(value=`text`, key="total"))**. <!-- marqdo-out total -950 +CN¥950.00 --> -The generated slot is directly below that call. Re-running the page replaces only the `total` slot; it does not duplicate it. - -Writeback is explicit. It is not hidden kernel serialization, does not persist arbitrary kernel memory, and does not touch a file unless the document calls it. - ---- - -Choosing. - -For published user docs, use the static snapshot. For a living report that must keep the latest run result in the `.mq.md` itself, use writeback. Both can coexist in one repository: static pages for readers, writeback examples for authors and audits. +After the explicit native file operation, return *[The persisted formatted value](result.ok(value=`text`))*. diff --git a/public/features/21-持久化.mq.md b/public/features/21-持久化.mq.md index c1dc650..11903c3 100644 --- a/public/features/21-持久化.mq.md +++ b/public/features/21-持久化.mq.md @@ -1,58 +1,44 @@ --- markup: occlusion -title: 外联执行结果的持久化 -description: 静态快照与自写回 —— 外联结果在进程退出后如何保留 -导入: - 外联: lib/外联.mq.md - writeback: lib/writeback.mq.md +title: 用固有写回保存真实的格式化结果 +import: + 指南: ../../doc/library-development.mq.md + 例程: ../../examples/foreign-native-report/index.mq.md + 写回: lib/writeback.mq.md + 结果: lib/result.mq.md --- -# main +调用 main 需要 process.exec,fs.write,并将 --fs-root 指向仓库根目录。这是本页明确声明的文件修改,普通阅读不会写文件。静态 View 与可调用函数使用同一份源码,输出来自实际执行。 -外联代码有两种有用的形态:发布快照,以及把最新结果保留在源码里的活文档。两者回答不同的问题,不应混为一谈。 +## main ---- +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result:保存到本页 total 槽位的实际文本 | -静态快照:发布结果。 +静态快照把执行输出嵌入 HTML;显式写回则把选定结果保存在源码的命名槽位里。本页正是需要后者的活文档示例,调用者应先知道会修改本页,再授予 fs.write。写回后的值可以在普通 Markdown 源码和差异中审阅,不依赖仍存活的外部进程。 -`marqdo view output` 执行文档单元,并把真实输出嵌入生成的 HTML。`.mq.md` 源码不会被修改。这是用户文档、评审和稳定链接的默认选择:读者不需要运行任何东西就能看到结果,源码保持干净。 +金额由原生开发指南计算,随后共享例程只调用 Node Intl 完成固有库尚未提供的本地化货币展示。例程检查每次求值并关闭其持久内核,调用者得到的已经是普通文本。没有 Python 编排,也没有外部文件写入器;保存动作继续使用 Marqdo 的 writeback。示例的金额为 950,当前区域设置下的文本为 ¥950.00,真实输出会成为下面的 total 槽位内容。 -静态快照是某个时间点的产物。外部服务变化后重新构建即可,不要把它当成实时看板。 +再次执行替换同一个键,不重复添加槽位。若解释器不可用或格式化失败,在写文件之前就返回真实失败;固有文件策略或 IO 错误也保留诊断。这里持久化的是已经选定的文本,不保存任意内核内存,也不能根据它重建活资源句柄。完成后可用正常的仓库差异审阅流程检查变更,再决定是否随文档提交。 ---- +面向读者的发布页面通常选择静态快照;明确需要在源码中保存最新运行结果的审计文档才使用写回。两者可以共存,但静态导出如果执行了本页,仍会尊重这个显式写回操作。权限不会因为文档外观而被隐式扩张,依赖步骤也不能在失败后继续伪造结果。 -自写回:把结果留在源码里。 +先**金额 = [计算需要展示的原生金额](指南.计算金额(单价=190, 数量=5))**. -对于探索性或审计型文档,把 `外联` 和 `lib/writeback` 搭配使用。`writeback.record` 会在调用点附近写入带 key 的输出槽位。槽位在 Markdown 源码中可见,可以在 diff 中审阅,也可以随文档提交。 +`report` = -| 步骤 | 作用 | -|------|------| -| 外联执行 / 外联会话 | 执行外联代码并返回 Marqdo 值 | -| 写回记录 | 把该值持久化到命名槽位 | -| git diff | 像审阅普通文档改动一样审阅结果 | +| total | average | +|---|---| +| `金额` | `金额` | -这一页本身就是完整示例。 - -这一页就是可运行的示例。下面的代码围栏是普通 Marqdo 值;`外联.运行` 执行它,然后 `writeback.record` 把 `total` 槽位写进本页源码。 - -`写回代码` = -```python -print(950) -``` - -**结果 = > 外联.运行 代码=`写回代码`** - -**> writeback.record value=`结果` key="total"** +再**格式结果 = [只把本地化展示交给 Intl](例程.format_summary(report=`report`, locale="zh-CN"))**。 +1. not access(`格式结果`, "ok") + 返回*格式结果*,失败时不进入文件写回。 +我们**正文 = [读取实际格式化文本](access(access(格式结果, "value"), "total"))**。 +随后**写入 = [使用固有写回能力保存真实文本](写回.record(value=`正文`, key="total"))**。 <!-- marqdo-out total -950 +¥950.00 --> -生成的槽位就在这次调用下方。再次运行只替换 `total` 槽位,不会重复添加。 - -自写回是显式动作。它不是隐藏的内核序列化,不持久化任意内核内存,也不会在文档没有调用时修改文件。 - ---- - -如何选择。 - -面向用户的发布文档用静态快照;需要把最新执行结果留在 `.mq.md` 本身里的活文档用自写回。两者可以共存于同一个仓库:静态页面给读者,自写回示例给作者和审计。 +写回完成后返回*[已经保存的格式化文本](结果.ok(value=`正文`))*。 diff --git a/public/features/22-call.mq.md b/public/features/22-call.mq.md index dac6e41..b785515 100644 --- a/public/features/22-call.mq.md +++ b/public/features/22-call.mq.md @@ -6,6 +6,10 @@ description: v2.2.0 marqdo call runs a function inside any .mq.md. The explanati # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + v2.2.0 adds one command: `marqdo call`. It adds no Markdown marker and no skill system. An ordinary .mq.md file is already a document, a piece of knowledge and a program. What was missing is a way to call one of its functions from outside. The usual command runs the whole file. Functions inside it run only when the entry calls them. Trying one calculation meant writing an entry, a print and a check. The smallest unit you can execute is now a function. @@ -42,18 +46,40 @@ After editing a function, call it again with the inputs that failed. A passing c # calculator +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Object/type namespace for the child functions below; call the intended child directly | + This is an ordinary Marqdo document. It holds a little reusable arithmetic. ## add +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | Left operand supplied to this calculation | +| b | any | required | Right operand supplied to this calculation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | The value explicitly returned below; conditional returns follow the selected branch | + Add the numbers `a` and `b`. -*[result](a + b)* +After these steps, return *[result]((`a` + `b`))*. ## multiply +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | Left operand supplied to this calculation | +| b | any | required | Right operand supplied to this calculation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | The value explicitly returned below; conditional returns follow the selected branch | + Multiply the numbers `a` and `b`. -*[result](a * b)* +After these steps, return *[result]((`a` * `b`))*. diff --git a/public/features/22-函数调用.mq.md b/public/features/22-函数调用.mq.md index 04ef985..093966e 100644 --- a/public/features/22-函数调用.mq.md +++ b/public/features/22-函数调用.mq.md @@ -6,6 +6,10 @@ description: v2.2.0 的 marqdo call 让任意 .mq.md 里的函数可以带参数 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + v2.2.0 增加一条命令:`marqdo call`。它不新增 Markdown 标记,也不另建一套技能系统。一个普通的 .mq.md 本来就是文档、知识和程序。缺的是从外部直接调用其中某个函数。 以前日常用法是运行整份文件。入口对象跑完,里面的函数要等文件自己去调用。要试验一个计算,往往得再写入口、打印和检查。现在最小可执行单位是函数。 @@ -42,18 +46,40 @@ marqdo call public/features/22-函数调用.mq.md 计算器.加法 a=2 b=3 # 计算器 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 供下述方法复用的对象或类型命名空间;直接调用所需的子函数。 | + 这是一个普通的 Marqdo 文档。 其中包含一些可以复用的数学计算知识。 ## 加法 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | 必填 | Left operand supplied to this calculation | +| b | any | 必填 | Right operand supplied to this calculation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | + 计算两个数字`a`和`b`的和。 -*[计算结果](a + b)* +完成上述步骤后,返回*[计算结果]((`a` + `b`))*。 ## 乘法 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | 必填 | Left operand supplied to this calculation | +| b | any | 必填 | Right operand supplied to this calculation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | + 计算两个数字`a`和`b`的积。 -*[计算结果](a * b)* +完成上述步骤后,返回*[计算结果]((`a` * `b`))*。 diff --git a/public/keywords/bool-logic.mq.md b/public/keywords/bool-logic.mq.md index 9d02908..3fbf84b 100644 --- a/public/keywords/bool-logic.mq.md +++ b/public/keywords/bool-logic.mq.md @@ -6,19 +6,23 @@ description: True / False / None and and / or / not # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Keywords: `True`, `False`, `None`, and `and` / `or` / `not`. -**`a` = True** -**`b` = False** +We first **a = True** for the next step. +We first **b = False** for the next step. 1. `a` and not `b` - > print text=ok + We now **[Display this step's result](> print text="ok")**. 2. * - > print text=fail + We now **[Display this step's result](> print text="fail")**. -**`probe` = 1** +We first **probe = 1** for the next step. 1. None - > print text=none-truthy + We now **[Display this step's result](> print text="none-truthy")**. 2. * - > print text=none-falsy + We now **[Display this step's result](> print text="none-falsy")**. diff --git a/public/keywords/input.mq.md b/public/keywords/input.mq.md index fb17a3f..97097c0 100644 --- a/public/keywords/input.mq.md +++ b/public/keywords/input.mq.md @@ -7,8 +7,12 @@ stdin: Ada # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + The input builtin reads one line. For demos and marqdo view / static export, put sample lines in frontmatter (stdin:). CLI can also use a pipe or --stdin-file. Live view can override with the Preset input box. -**`name` = > input prompt="Name: "** +We first **name = [Compute name](input(prompt="Name: "))** for the next step. -> print text=Hello `name`! +We now **[Display this step's result](> print text="Hello `name`!")**. diff --git a/public/keywords/print.mq.md b/public/keywords/print.mq.md index 0904f9c..7f4346a 100644 --- a/public/keywords/print.mq.md +++ b/public/keywords/print.mq.md @@ -6,10 +6,14 @@ description: Named and positional forms # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + The `print` builtin accepts named or positional arguments: -> print text=named form +We now **[Display this step's result](> print text="named form")**. -> print positional +We now **[Display this step's result](> print "positional")**. Named args may contain spaces; positional args may not. diff --git a/public/keywords/stdlib.mq.md b/public/keywords/stdlib.mq.md index 9e573f7..b4cf79a 100644 --- a/public/keywords/stdlib.mq.md +++ b/public/keywords/stdlib.mq.md @@ -6,30 +6,34 @@ description: Host builtins for strings and tables # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Length and type: -**`s` = "hello"** +We first **s = "hello"** for the next step. -**`n` = > len `s`** +We first **n = [Compute n](len(`s`))** for the next step. -> print text=`n` +We now **[Display this step's result](> print text=`n`)**. -**`ty` = > type `s`** +We first **ty = [Compute ty](type(`s`))** for the next step. -> print text=`ty` +We now **[Display this step's result](> print text=`ty`)**. Trim, split, join, and index: -**`t` = > trim value=" hi "** +We first **t = [Compute t](trim(value=" hi "))** for the next step. -**`parts` = > split value="a,b" sep=","** +We first **parts = [Compute parts](split(value="a,b", sep=","))** for the next step. -**`mid` = > at value=`parts` index=0** +We first **mid = [Compute mid](at(value=`parts`, index=0))** for the next step. -**`j` = > join value=`parts` sep="-"** +We first **j = [Compute j](join(value=`parts`, sep="-"))** for the next step. -> print text=`t` +We now **[Display this step's result](> print text=`t`)**. -> print text=`mid` +We now **[Display this step's result](> print text=`mid`)**. -> print text=`j` +We now **[Display this step's result](> print text=`j`)**. diff --git a/public/keywords/内核双名.mq.md b/public/keywords/内核双名.mq.md index 1c29d62..5f8d52f 100644 --- a/public/keywords/内核双名.mq.md +++ b/public/keywords/内核双名.mq.md @@ -6,12 +6,16 @@ description: 无需导入:打印、长度、文本、整数 与 print / len / # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 内核中英别名等价,可混用: -**`s` = "你好"** +我们先**s = "你好"**,供下一步使用。 -**`n` = > 长度 值=`s`** +我们先**n = [计算并保存 n](长度(值=`s`))**,供下一步使用。 -> 打印 内容=`n` +随后我们**[显示当前步骤的结果](> 打印 内容=`n`)**。 -> print text=also-english +随后我们**[显示当前步骤的结果](> print text="also-english")**。 diff --git a/public/keywords/布尔逻辑.mq.md b/public/keywords/布尔逻辑.mq.md index 30c78de..922420b 100644 --- a/public/keywords/布尔逻辑.mq.md +++ b/public/keywords/布尔逻辑.mq.md @@ -6,19 +6,23 @@ description: 真 / 假 / 空 与 且 / 或 / 非 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 关键字:`真`、`假`、`空`,以及 `且` / `或` / `非`。 -**`a` = 真** -**`b` = 假** +我们先**a = True**,供下一步使用。 +我们先**b = False**,供下一步使用。 1. `a` 且 非 `b` - > 打印 内容=通过 + 随后我们**[显示当前步骤的结果](> 打印 内容="通过")**。 2. * - > 打印 内容=失败 + 随后我们**[显示当前步骤的结果](> 打印 内容="失败")**。 -**`probe` = 1** +我们先**probe = 1**,供下一步使用。 1. 空 - > 打印 内容=空为真 + 随后我们**[显示当前步骤的结果](> 打印 内容="空为真")**。 2. * - > 打印 内容=空为假 + 随后我们**[显示当前步骤的结果](> 打印 内容="空为假")**。 diff --git a/public/keywords/打印.mq.md b/public/keywords/打印.mq.md index 084bf3c..11ecbc8 100644 --- a/public/keywords/打印.mq.md +++ b/public/keywords/打印.mq.md @@ -6,10 +6,14 @@ description: 具名与位置两种写法 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 内置 `打印` 接受具名或位置实参: -> 打印 内容=具名写法 +随后我们**[显示当前步骤的结果](> 打印 内容="具名写法")**。 -> 打印 位置写法 +随后我们**[显示当前步骤的结果](> 打印 "位置写法")**。 具名实参可以带空格;位置实参不可以。 diff --git a/public/keywords/标准库.mq.md b/public/keywords/标准库.mq.md index 7d729ed..d0f17be 100644 --- a/public/keywords/标准库.mq.md +++ b/public/keywords/标准库.mq.md @@ -6,30 +6,34 @@ description: 主机内置;中文别名覆盖常用几个 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 长度与英文 `type`(类型无中文内核别名,见标准库文档): -**`s` = "你好"** +我们先**s = "你好"**,供下一步使用。 -**`n` = > 长度 值=`s`** +我们先**n = [计算并保存 n](长度(值=`s`))**,供下一步使用。 -> 打印 内容=`n` +随后我们**[显示当前步骤的结果](> 打印 内容=`n`)**。 -**`ty` = > type `s`** +我们先**ty = [计算并保存 ty](type(`s`))**,供下一步使用。 -> 打印 内容=`ty` +随后我们**[显示当前步骤的结果](> 打印 内容=`ty`)**。 去空白、拆分、拼接、按下标(主机名仍为英文): -**`t` = > trim value=" 嗨 "** +我们先**t = [计算并保存 t](trim(value=" 嗨 "))**,供下一步使用。 -**`parts` = > split value="甲,乙" sep=","** +我们先**parts = [计算并保存 parts](split(value="甲,乙", sep=","))**,供下一步使用。 -**`mid` = > at value=`parts` index=0** +我们先**mid = [计算并保存 mid](at(value=`parts`, index=0))**,供下一步使用。 -**`j` = > join value=`parts` sep="-"** +我们先**j = [计算并保存 j](join(value=`parts`, sep="-"))**,供下一步使用。 -> 打印 内容=`t` +随后我们**[显示当前步骤的结果](> 打印 内容=`t`)**。 -> 打印 内容=`mid` +随后我们**[显示当前步骤的结果](> 打印 内容=`mid`)**。 -> 打印 内容=`j` +随后我们**[显示当前步骤的结果](> 打印 内容=`j`)**。 diff --git a/public/keywords/输入.mq.md b/public/keywords/输入.mq.md index c37a995..1241408 100644 --- a/public/keywords/输入.mq.md +++ b/public/keywords/输入.mq.md @@ -7,8 +7,12 @@ description: 从 stdin 读一行;可选提示。演示数据写在 frontmatter # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 内置「输入」读一行。演示与 marqdo view / 静态导出可在 frontmatter 写「输入:」(或 stdin:)。CLI 也可用管道或 --stdin-file。Live view 可用 Preset input 覆盖。 -**`名字` = > 输入 提示="名字:"** +我们先**名字 = [计算并保存 名字](输入(提示="名字:"))**,供下一步使用。 -> 打印 内容=你好 `名字`! +随后我们**[显示当前步骤的结果](> 打印 内容="你好 `名字`!")**。 diff --git a/public/stdlib/00-overview.mq.md b/public/stdlib/00-overview.mq.md index dadcd42..8f69a24 100644 --- a/public/stdlib/00-overview.mq.md +++ b/public/stdlib/00-overview.mq.md @@ -6,6 +6,10 @@ description: How to import official lib modules # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Version 2.6.0: each standard library is normally one lib/name.mq.md source file, which is its own handbook. No extra index is required. Read the parameter/default and return tables below its headings to call it; multi-file extensions use indexes to organize modules. The 61 public sources provide 650 functions. Import with a nested YAML import mapping. File, network and process effects still need authorization at the execution entry. marqdo call defaults to pure functions; file operations require explicit --effects and --fs-root. Contract documentation never grants permission. @@ -26,4 +30,4 @@ Official optional extensions live under ext/ (not stdlib): ext/llm, ext/agent Sibling pages in this folder document each module. Chinese overview: 00-索引.mq.md. -> print text=stdlib overview ok +We now **[Display this step's result](> print text="stdlib overview ok")**. diff --git a/public/stdlib/00-索引.mq.md b/public/stdlib/00-索引.mq.md index 568c202..3df806d 100644 --- a/public/stdlib/00-索引.mq.md +++ b/public/stdlib/00-索引.mq.md @@ -6,6 +6,10 @@ description: 如何导入官方 lib 模块 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 版本 2.6.0:标准库通常是单个 lib/名称.mq.md 文件,源码本身就是手册,不要求额外 index。直接阅读标题下的参数、默认值和返回表即可调用;多文件拓展库才通过 index 组织模块。当前 61 份公开标准库包含 650 个函数。 使用 YAML 的 import(或导入)映射导入模块。文件、网络、进程等副作用仍由运行入口授权;marqdo call 默认只运行纯函数,文件调用要明确 --effects 与 --fs-root。文档契约不会自动授予权限。 @@ -26,4 +30,4 @@ description: 如何导入官方 lib 模块 各模块说明见本目录其它页。English: 00-overview.mq.md. -> 打印 内容=标准库总览就绪 +随后我们**[显示当前步骤的结果](> 打印 内容="标准库总览就绪")**。 diff --git a/public/stdlib/foreign.mq.md b/public/stdlib/foreign.mq.md index 26439ef..fad27f7 100644 --- a/public/stdlib/foreign.mq.md +++ b/public/stdlib/foreign.mq.md @@ -9,6 +9,10 @@ stdin: 21 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + `lib/foreign` runs code fences and inline sources with local interpreters. v2 keeps the Markdown surface unchanged while adding structured records, JSON in/out, parallel fan-out, persistent Python/Node kernels and an explicit state bridge. The same file is still a document: a bound fence is readable Markdown, and `foreign.*` turns it into an executable unit. @@ -17,10 +21,10 @@ The same file is still a document: a bound fence is readable Markdown, and `fore Probe before you run. -**node = > foreign.probe lang="node"** +We first **node = [Compute node](foreign.probe(lang="node"))** for the next step. -> print text=[ok](access(`node`, "ok")) -> print text=[version](access(`node`, "version")) +We now **[Display this step's result](> print text=[ok](access(`node`, "ok")))**. +We now **[Display this step's result](> print text=[version](access(`node`, "version")))**. `probe` returns `{lang, cmd, path, ok, version, error}`. Omit `lang` to inspect every known language. @@ -30,14 +34,14 @@ A structured record, not just stdout. `marker` = ```node -console.log("hello from a foreign kernel"); +console.log(new Intl.NumberFormat("en-US", {style:"currency", currency:"CNY"}).format(950)); ``` -**record = > foreign.invoke code=`marker`** +We first **record = [Compute record](foreign.invoke(code=`marker`))** for the next step. -> print text=[ok](access(`record`, "ok")) -> print text=[stdout](access(`record`, "stdout")) -> print text=[code](access(`record`, "code")) +We now **[Display this step's result](> print text=[ok](access(`record`, "ok")))**. +We now **[Display this step's result](> print text=[stdout](access(`record`, "stdout")))**. +We now **[Display this step's result](> print text=[code](access(`record`, "code")))**. `invoke` never throws on a process failure. Read `ok`, `code`, `stdout`, `stderr`, `ms`, `timed_out`, `truncated`, `result` and `error` from one record. @@ -45,18 +49,18 @@ console.log("hello from a foreign kernel"); JSON in, JSON out. -`double` = +`format_money` = ```node let input = ""; process.stdin.on("data", chunk => { input += chunk; }); process.stdin.on("end", () => { - console.log(JSON.stringify(JSON.parse(input) * 2)); + console.log(JSON.stringify(new Intl.NumberFormat("en-US", {style:"currency", currency:"CNY"}).format(JSON.parse(input)))); }); ``` -**single = > foreign.call code=`double` input=21** +We first **single = [Compute single](foreign.call(code=`format_money`, input=21))** for the next step. -> print text=`single` +We now **[Display this step's result](> print text=`single`)**. The input is encoded as JSON on stdin; the last stdout value is parsed as JSON. Use `output="json"` with `invoke` when you also want the raw record. @@ -73,9 +77,10 @@ Parallel fan-out. | 3 | | 4 | -**doubled = > foreign.call_many code=`double` inputs=`numbers` concurrency=4** +This single-column bound table is a native list of numbers, ready for the batch call. +We **formatted_batch = [Format each amount while retaining input order](foreign.call_many(code=`format_money`, inputs=`numbers`, concurrency=4))**. -> print text=`doubled` +We now **[Display this step's result](> print text=`formatted_batch`)**. `call_many` applies one program to every input, runs independently, preserves input order, and returns parsed JSON results. `run_many` does the same for full invoke-option maps. @@ -83,13 +88,13 @@ Parallel fan-out. A persistent kernel. -**session = > foreign.session_open lang="node"** +We first **session = [Compute session](foreign.session_open(lang="node"))** for the next step. -**first = > foreign.session_eval id=`session` source="let total = 0; for (let i = 1; i <= 5; i += 1) total += i;"** +We first **first = [Compute first](foreign.session_eval(id=`session`, source="var money = new Intl.NumberFormat(\"en-US\", {style:\"currency\", currency:\"CNY\"});"))** for the next step. -**second = > foreign.session_eval id=`session` source="total * 2"** +We first **second = [Compute second](foreign.session_eval(id=`session`, source="money.format(21)"))** for the next step. -> print text=[result](access(`second`, "result")) +We now **[Display this step's result](> print text=[result](access(`second`, "result")))**. Variables created in the first evaluation survive into the second. The kernel is not a shell: use `session_eval`, `session_get`, `session_names`, then `session_close`. @@ -97,13 +102,13 @@ Variables created in the first evaluation survive into the second. The kernel is The explicit state bridge. -**> foreign.session_set id=`session` name="rate" value=0.08** +We **[Copy the explicit rate into the existing kernel](foreign.session_set(id=`session`, name="rate", value=0.08))**. -**rate = > foreign.session_get id=`session` name="rate"** +We first **rate = [Compute rate](foreign.session_get(id=`session`, name="rate"))** for the next step. -> print text=`rate` +We now **[Display this step's result](> print text=`rate`)**. -**> foreign.session_close id=`session`** +After reading the copied value, we **[Close this persistent formatting kernel](foreign.session_close(id=`session`))**. This is a JSON copy, not shared memory. The kernel receives a value; Marqdo receives a value. There is no implicit mirroring and no hidden global namespace. @@ -118,8 +123,8 @@ Cells in view. | 名称 | 语言 | 命令 | 说明 | |------|------|------|------| -| 分析 | python | | shared analysis | -| 复核 | python | | isolated review | +| 分析 | node | | shared analysis | +| 复核 | node | | isolated review | `分析单元` = @@ -132,7 +137,7 @@ Cells in view. `会话` = > foreign.session kernels=`分析内核` cells=`分析单元` ``` -`view` consumes the `会话` handle and adds Run All, Step, kernel switching, a journal and per-cell state. Without `会话`, view cells are stateless one-shot runs: same shell, no persistent kernel. There is no second CLI mode. See the complete Python walkthrough in [`features/19-foreign-view-cells.mq.md`](../features/19-foreign-view-cells.mq.md). +`view` consumes the `会话` handle and adds Run All, Step, kernel switching, a journal and per-cell state. Without `会话`, view cells are stateless one-shot runs: same shell, no persistent kernel. There is no second CLI mode. See the native-first Intl workflow in [`features/19-foreign-view-cells.mq.md`](../features/19-foreign-view-cells.mq.md). --- @@ -144,7 +149,7 @@ Safety defaults. | Shell | no shell; arguments are split explicitly | | Output | bounded, with truncated | | Timeout | process group killed on Unix / taskkill /T on Windows | -| CWD | file sandbox root; no implicit escape | +| CWD | starts at the granted root; the child retains normal OS authority | | Parallelism | capped fan-out; each item isolated | Read the full API in [../../lib/foreign.mq.md](../../lib/foreign.mq.md) and the design in [../../doc/design/foreign-kernel.md](../../doc/design/foreign-kernel.md). diff --git a/public/stdlib/fs.mq.md b/public/stdlib/fs.mq.md index c80dec1..a59c48e 100644 --- a/public/stdlib/fs.mq.md +++ b/public/stdlib/fs.mq.md @@ -8,9 +8,13 @@ import: # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Filesystem helpers from lib/fs. Bare path words must not contain `/` (division). Prefer a same-folder name or a variable. -**`ok` = [fs.exists] path="demo.txt"** +We first **ok = [Compute ok](fs.exists(path="demo.txt"))** for the next step. 1. `ok` **打印 内容="demo-present"** diff --git a/public/stdlib/json.mq.md b/public/stdlib/json.mq.md index 13e8fb5..7205ce0 100644 --- a/public/stdlib/json.mq.md +++ b/public/stdlib/json.mq.md @@ -8,12 +8,16 @@ import: # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Shared JSON helpers for EN and ZH docs. Prefer parse, stringify, and quote. Build maps with tables or table.put — not json.set chains. -**`obj` = [json.parse] text="{}"** -**`ty` = [type] `obj`** +We first **obj = [Compute obj](json.parse(text="{}"))** for the next step. +We first **ty = [Compute ty](type(`obj`))** for the next step. **打印 内容=`ty`** -**`out` = [json.stringify] value=`obj`** +We first **out = [Compute out](json.stringify(value=`obj`))** for the next step. **打印 内容=`out`** diff --git a/public/stdlib/math.mq.md b/public/stdlib/math.mq.md index 9dcc631..72460e7 100644 --- a/public/stdlib/math.mq.md +++ b/public/stdlib/math.mq.md @@ -8,6 +8,10 @@ import: # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Import lib/math.mq.md. Runtime types: num (float) and formula (symbolic tree). Bind a formula with an empty-RHS assign followed by a `$$…$$` fence (same shape as table assigns). In view, Structure renders that fence with KaTeX. `f` = @@ -23,18 +27,18 @@ Plotting (already in the library): plot / plot_points / plot_conic return SVG te diff / simplify / expand / partial subs return formula values so you can chain (e.g. differentiate twice, then plot or eval). -**`ty` = [type] `f`** +We first **ty = [Compute ty](type(`f`))** for the next step. -> print text=`ty` +We now **[Display this step's result](> print text=`ty`)**. -**`df` = [math.diff] formula=`f` var="x"** +We first **df = [Compute df](math.diff(formula=`f`, var="x"))** for the next step. -> print text=`df` +We now **[Display this step's result](> print text=`df`)**. -**`roots` = [math.solve] formula=`f` var="x"** +We first **roots = [Compute roots](math.solve(formula=`f`, var="x"))** for the next step. -> print text=`roots` +We now **[Display this step's result](> print text=`roots`)**. -**`_svg` = [math.plot] formula=`f` var="x" min=-3 max=3** +We first **_svg = [Compute _svg](math.plot(formula=`f`, var="x", min=-3, max=3))** for the next step. -> print text=plot-ok +We now **[Display this step's result](> print text="plot-ok")**. diff --git a/public/stdlib/net.mq.md b/public/stdlib/net.mq.md index e6acbc8..b164dea 100644 --- a/public/stdlib/net.mq.md +++ b/public/stdlib/net.mq.md @@ -8,8 +8,12 @@ import: # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Import lib/net.mq.md. Functions: http_get, http_post, http_post_sse, openai_sse_parse, http_request, url_encode. HTTPS and optional headers= map are supported. Default post content-type is JSON. `http_post_sse` / `openai_sse_parse` return OpenAI chat stream event lists (`delta` / `done`). -**`e` = [net.url_encode] text="hello world"** +We first **e = [Compute e](net.url_encode(text="hello world"))** for the next step. -> print text=`e` +We now **[Display this step's result](> print text=`e`)**. diff --git a/public/stdlib/plugin.mq.md b/public/stdlib/plugin.mq.md index c3430d3..14d8d68 100644 --- a/public/stdlib/plugin.mq.md +++ b/public/stdlib/plugin.mq.md @@ -8,13 +8,17 @@ import: # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Import lib/plugin.mq.md. Functions: load(path), unload(), list(). After load, registered plugin names are callable like other functions. C ABI: include/marqdo_abi.h — see doc/design/ext-abi.md. Path must stay under the program sandbox (cwd / fs root). -**`names` = [plugin.list]** +We first **names = [Compute names](plugin.list())** for the next step. -**`n` = [len] `names`** +We first **n = [Compute n](len(`names`))** for the next step. 1. `n` >= 0 - > print text=plugin-ok + We now **[Display this step's result](> print text="plugin-ok")**. 2. * - > print text=plugin-bad + We now **[Display this step's result](> print text="plugin-bad")**. diff --git a/public/stdlib/subtask.mq.md b/public/stdlib/subtask.mq.md index 9d6ee36..931a26f 100644 --- a/public/stdlib/subtask.mq.md +++ b/public/stdlib/subtask.mq.md @@ -8,6 +8,10 @@ import: # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + spawn picks one mode (others default to None). path= runs a marqdo run child process; wait returns the exit code. @@ -20,4 +24,4 @@ lang= plus source= runs foreign source; wait returns stdout text. File children are silent unless quiet=False. Also: poll id=, kill id=, wait_all. Parent exit kills file/foreign children. -> print text=subtask overview ok +We now **[Display this step's result](> print text="subtask overview ok")**. diff --git a/public/stdlib/sys.mq.md b/public/stdlib/sys.mq.md index d9b85bf..1f4286e 100644 --- a/public/stdlib/sys.mq.md +++ b/public/stdlib/sys.mq.md @@ -8,13 +8,17 @@ import: # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Import lib/sys.mq.md. Functions: env_get, env_set, load_dotenv(optional path), args, cwd, exit(code), exec(cmd), stream_publish(event). load_dotenv does not override existing variables. Under view, exit soft-fails instead of killing the process. `stream_publish` feeds the view SSE EventBus. -**`d` = [sys.cwd]** +We first **d = [Compute d](sys.cwd())** for the next step. -**`n` = [len] `d`** +We first **n = [Compute n](len(`d`))** for the next step. 1. `n` > 0 - > print text=cwd-ok + We now **[Display this step's result](> print text="cwd-ok")**. 2. * - > print text=cwd-empty + We now **[Display this step's result](> print text="cwd-empty")**. diff --git a/public/stdlib/table.mq.md b/public/stdlib/table.mq.md index bd8f2d5..029005f 100644 --- a/public/stdlib/table.mq.md +++ b/public/stdlib/table.mq.md @@ -8,10 +8,14 @@ import: # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Prefer table.put for element updates (at= text key, 1-based int, or list path). Read with link-index get. Use json for parse/stringify only. -**`h` = [table.put] in=None at="Authorization" value="Bearer-demo"** +We first **h = [Compute h](table.put(in=None, at="Authorization", value="Bearer-demo"))** for the next step. `xs` = @@ -20,8 +24,8 @@ Read with link-index get. Use json for parse/stringify only. | a | | b | -**`xs` = [table.put] in=`xs` at=1 value="A"** -**`n` = [table.rows] xs=`xs`** +We first **xs = [Compute xs](table.put(in=`xs`, at=1, value="A"))** for the next step. +We first **n = [Compute n](table.rows(xs=`xs`))** for the next step. **打印 内容=[Authorization](access(h, "Authorization"))** **打印 内容=[1](access(xs, "1"))** diff --git a/public/stdlib/text.mq.md b/public/stdlib/text.mq.md index e604ed9..2a9bf8e 100644 --- a/public/stdlib/text.mq.md +++ b/public/stdlib/text.mq.md @@ -8,11 +8,15 @@ import: # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Import lib/text. Bracket path or classic dotted calls both work. -**`t` = [text.str_trim] s=" marqdo "** +We first **t = [Compute t](text.str_trim(s=" marqdo "))** for the next step. **打印 内容=`t`** -**`parts` = [text.str_split] s="a,b,c" sep=","** -**`j` = [text.str_join] xs=`parts` sep="-"** +We first **parts = [Compute parts](text.str_split(s="a,b,c", sep=","))** for the next step. +We first **j = [Compute j](text.str_join(xs=`parts`, sep="-"))** for the next step. **打印 内容=`j`** diff --git a/public/stdlib/time.mq.md b/public/stdlib/time.mq.md index 2cb06df..1221ebe 100644 --- a/public/stdlib/time.mq.md +++ b/public/stdlib/time.mq.md @@ -8,12 +8,16 @@ import: # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Unix time helpers from lib/time. Patterns use strftime. -**`s` = [time.format] unix=0 pattern="%Y-%m-%d"** +We first **s = [Compute s](time.format(unix=0, pattern="%Y-%m-%d"))** for the next step. **打印 内容=`s`** -**`u` = [time.parse] text="1970-01-01 00:00:00" pattern="%Y-%m-%d %H:%M:%S"** +We first **u = [Compute u](time.parse(text="1970-01-01 00:00:00", pattern="%Y-%m-%d %H:%M:%S"))** for the next step. **打印 内容=`u`** **[time.sleep_ms] ms=0** diff --git a/public/stdlib/writeback.mq.md b/public/stdlib/writeback.mq.md index ac7e0a7..8ad1468 100644 --- a/public/stdlib/writeback.mq.md +++ b/public/stdlib/writeback.mq.md @@ -8,6 +8,10 @@ import: # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Writeback stores output in `<!-- marqdo-out … -->` blocks in the **entry** file (the one you run). record value= — default: insert or replace the block below the call; at_end=true → single block at EOF. @@ -16,4 +20,4 @@ get / clear — read or remove the adjacent block (or EOF block when at_end=true list — all output blocks in the entry file. -> print text=writeback overview ok +We now **[Display this step's result](> print text="writeback overview ok")**. diff --git a/public/stdlib/外联.mq.md b/public/stdlib/外联.mq.md index 0b08dd8..48e2fab 100644 --- a/public/stdlib/外联.mq.md +++ b/public/stdlib/外联.mq.md @@ -9,6 +9,10 @@ stdin: 21 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + `lib/外联` 用本机解释器运行代码围栏和内联源码。v2 不改 Markdown 表面,新增结构化记录、JSON 进出、并行扇出、Python/Node 持久内核和显式状态桥。 文件仍然是一篇文档:绑定的代码围栏是可读的 Markdown,`外联.*` 把它变成可执行单元。 @@ -17,10 +21,10 @@ stdin: 21 先探测,再运行。 -**node = > 外联.探测 语言="node"** +我们先**node = [计算并保存 node](外联.探测(语言="node"))**,供下一步使用。 -> 打印 内容=[ok](access(`node`, "ok")) -> 打印 内容=[version](access(`node`, "version")) +随后我们**[显示当前步骤的结果](> 打印 内容=[ok](access(`node`, "ok")))**。 +随后我们**[显示当前步骤的结果](> 打印 内容=[version](access(`node`, "version")))**。 `探测` 返回 `{lang, cmd, path, ok, version, error}`。省略语言时探测所有已知语言。 @@ -30,14 +34,14 @@ stdin: 21 `标记` = ```node -console.log("来自外联内核的问候"); +console.log(new Intl.NumberFormat("zh-CN", {style:"currency", currency:"CNY"}).format(950)); ``` -**记录 = > 外联.执行 代码=`标记`** +我们先**记录 = [计算并保存 记录](外联.执行(代码=`标记`))**,供下一步使用。 -> 打印 内容=[ok](access(`记录`, "ok")) -> 打印 内容=[stdout](access(`记录`, "stdout")) -> 打印 内容=[code](access(`记录`, "code")) +随后我们**[显示当前步骤的结果](> 打印 内容=[ok](access(`记录`, "ok")))**。 +随后我们**[显示当前步骤的结果](> 打印 内容=[stdout](access(`记录`, "stdout")))**。 +随后我们**[显示当前步骤的结果](> 打印 内容=[code](access(`记录`, "code")))**。 `执行` 在进程失败时不抛错,而是在一条记录里给出 `ok`、`code`、`stdout`、`stderr`、`ms`、`timed_out`、`truncated`、`result` 与 `error`。 @@ -45,18 +49,18 @@ console.log("来自外联内核的问候"); JSON 进,JSON 出。 -`双倍` = +`金额格式` = ```node let input = ""; process.stdin.on("data", chunk => { input += chunk; }); process.stdin.on("end", () => { - console.log(JSON.stringify(JSON.parse(input) * 2)); + console.log(JSON.stringify(new Intl.NumberFormat("zh-CN", {style:"currency", currency:"CNY"}).format(JSON.parse(input)))); }); ``` -**单个 = > 外联.调用 代码=`双倍` 输入=21** +我们先**单个 = [计算并保存 单个](外联.调用(代码=`金额格式`, 输入=21))**,供下一步使用。 -> 打印 内容=`单个` +随后我们**[显示当前步骤的结果](> 打印 内容=`单个`)**。 输入编码成 JSON 写到 stdin;stdout 的最后一个值再解析成 JSON。想同时保留原始记录时,用 `执行` 的 `输出="json"`。 @@ -73,9 +77,10 @@ process.stdin.on("end", () => { | 3 | | 4 | -**翻倍 = > 外联.批量调用 代码=`双倍` 输入表=`数值表` 并发=4** +这张单列绑定表本身就是原生数值列表,可以直接交给批量调用。 +随后我们**格式列表 = [并行展示金额并保持输入顺序](外联.批量调用(代码=`金额格式`, 输入表=`数值表`, 并发=4))**。 -> 打印 内容=`翻倍` +随后我们**[显示当前步骤的结果](> 打印 内容=`格式列表`)**。 `批量调用` 对每个输入独立运行同一程序,保持输入顺序并返回解析后的 JSON 列表;`批量运行` 对完整 invoke 选项表做同样的事。 @@ -83,13 +88,13 @@ process.stdin.on("end", () => { 持久内核。 -**会话 = > 外联.会话开启 语言="node"** +我们先**会话 = [计算并保存 会话](外联.会话开启(语言="node"))**,供下一步使用。 -**第一次 = > 外联.会话求值 标识=`会话` 源码="let total = 0; for (let i = 1; i <= 5; i += 1) total += i;"** +我们先**第一次 = [计算并保存 第一次](外联.会话求值(标识=`会话`, 源码="var money = new Intl.NumberFormat(\"zh-CN\", {style:\"currency\", currency:\"CNY\"});"))**,供下一步使用。 -**第二次 = > 外联.会话求值 标识=`会话` 源码="total * 2"** +我们先**第二次 = [计算并保存 第二次](外联.会话求值(标识=`会话`, 源码="money.format(21)"))**,供下一步使用。 -> 打印 内容=[result](access(`第二次`, "result")) +随后我们**[显示当前步骤的结果](> 打印 内容=[result](access(`第二次`, "result")))**。 第一次求值创建的变量会保留到第二次。内核不是 shell:用 `会话求值`、`会话取值`、`会话变量`,最后 `会话关闭`。 @@ -97,13 +102,13 @@ process.stdin.on("end", () => { 显式状态桥。 -**> 外联.会话设值 标识=`会话` 名称="rate" 值=0.08** +我们**[将明确选定的值复制进已有内核](外联.会话设值(标识=`会话`, 名称="rate", 值=0.08))**。 -**利率 = > 外联.会话取值 标识=`会话` 名称="rate"** +我们先**利率 = [计算并保存 利率](外联.会话取值(标识=`会话`, 名称="rate"))**,供下一步使用。 -> 打印 内容=`利率` +随后我们**[显示当前步骤的结果](> 打印 内容=`利率`)**。 -**> 外联.会话关闭 标识=`会话`** +读回所需结果后,我们**[关闭本次持久展示内核](外联.会话关闭(标识=`会话`))**。 这是 JSON 拷贝,不是共享内存:内核收到一个值,Marqdo 取回一个值。没有隐式镜像,也没有隐藏的全局命名空间。 @@ -118,8 +123,8 @@ view 中的单元。 | 名称 | 语言 | 命令 | 说明 | |------|------|------|------| -| 分析 | python | | 共享分析 | -| 复核 | python | | 独立复核 | +| 分析 | node | | 共享分析 | +| 复核 | node | | 独立复核 | `分析单元` = @@ -132,7 +137,7 @@ view 中的单元。 `会话` = > foreign.session kernels=`分析内核` cells=`分析单元` ``` -`view` 消费 `会话` 句柄,提供 Run All、Step、切换内核、journal 和单元状态。没有 `会话` 时,view 的 cells 是无状态的一次性运行:同一套外壳,但没有持久内核。没有第二个 CLI 模式。完整 Python 示例见 [`features/19-外联视图单元.mq.md`](../features/19-外联视图单元.mq.md)。 +`view` 消费 `会话` 句柄,提供 Run All、Step、切换内核、journal 和单元状态。没有 `会话` 时,view 的 cells 是无状态的一次性运行:同一套外壳,但没有持久内核。没有第二个 CLI 模式。原生分析与 Intl 示例见 [`features/19-外联视图单元.mq.md`](../features/19-外联视图单元.mq.md)。 --- diff --git a/public/stdlib/子任务.mq.md b/public/stdlib/子任务.mq.md index 2b20472..c2fac20 100644 --- a/public/stdlib/子任务.mq.md +++ b/public/stdlib/子任务.mq.md @@ -8,6 +8,10 @@ description: 文件、函数或外联代码并行执行 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 启动(spawn)四选一(其余参数默认 None)。 路径=:marqdo run 子进程;等待返回退出码。 @@ -20,4 +24,4 @@ description: 文件、函数或外联代码并行执行 文件子任务默认静默;静默=假 时继承父终端。另有:探测、终止、等待全部。父进程结束会终止文件/外联子进程。 -> 打印 内容=子任务总览就绪 +随后我们**[显示当前步骤的结果](> 打印 内容="子任务总览就绪")**。 diff --git a/public/stdlib/插件.mq.md b/public/stdlib/插件.mq.md index 81d883c..62739b1 100644 --- a/public/stdlib/插件.mq.md +++ b/public/stdlib/插件.mq.md @@ -8,13 +8,17 @@ description: 加载可选共享库(.dll / .so / .dylib) # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 导入 lib/插件.mq.md。函数:加载(路径)、卸载()、列出()。加载后,插件注册的名称可像普通函数一样调用。C 契约见 include/marqdo_abi.h 与 doc/design/ext-abi.md。路径须落在程序沙箱内。 -**`names` = [插件.列出]** +我们先**names = [计算并保存 names](插件.列出())**,供下一步使用。 -**`n` = [长度] 值=`names`** +我们先**n = [计算并保存 n](长度(值=`names`))**,供下一步使用。 1. `n` >= 0 - > 打印 内容=插件就绪 + 随后我们**[显示当前步骤的结果](> 打印 内容="插件就绪")**。 2. * - > 打印 内容=插件异常 + 随后我们**[显示当前步骤的结果](> 打印 内容="插件异常")**。 diff --git a/public/stdlib/数学.mq.md b/public/stdlib/数学.mq.md index 9f4b1ec..d5205a8 100644 --- a/public/stdlib/数学.mq.md +++ b/public/stdlib/数学.mq.md @@ -8,6 +8,10 @@ description: 高中数学标准库(中文) # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 导入 lib/数学.mq.md。运行时类型:num(浮点)与 formula(符号树)。用空 RHS 赋值后跟 `$$…$$` 围栏绑定公式(与表格赋值同构)。view 的 Structure 会用 KaTeX 渲染该公式。 `f` = @@ -23,18 +27,18 @@ $$ 求导 / 化简 / 展开 / 未完全数值化的代入仍返回 formula,可继续链式调用(例如求二阶导后再绘图或求值)。 -**`ty` = [type] `f`** +我们先**ty = [计算并保存 ty](type(`f`))**,供下一步使用。 -> print text=`ty` +随后我们**[显示当前步骤的结果](> print text=`ty`)**。 -**`df` = [数学.求导] formula=`f` var="x"** +我们先**df = [计算并保存 df](数学.求导(formula=`f`, var="x"))**,供下一步使用。 -> print text=`df` +随后我们**[显示当前步骤的结果](> print text=`df`)**。 -**`roots` = [数学.求解] formula=`f` var="x"** +我们先**roots = [计算并保存 roots](数学.求解(formula=`f`, var="x"))**,供下一步使用。 -> print text=`roots` +随后我们**[显示当前步骤的结果](> print text=`roots`)**。 -**`_svg` = [数学.绘图] formula=`f` var="x" min=-3 max=3** +我们先**_svg = [计算并保存 _svg](数学.绘图(formula=`f`, var="x", min=-3, max=3))**,供下一步使用。 -> print text=plot-ok +随后我们**[显示当前步骤的结果](> print text="plot-ok")**。 diff --git a/public/stdlib/文件.mq.md b/public/stdlib/文件.mq.md index dff678a..18ce32d 100644 --- a/public/stdlib/文件.mq.md +++ b/public/stdlib/文件.mq.md @@ -8,9 +8,13 @@ description: 沙箱内读写文本 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 文件系统助手(lib/文件)。裸路径不要写斜杠(会被当成除法)。可用同目录文件名或变量。 -**`ok` = [文件.存在] 路径="demo.txt"** +我们先**ok = [计算并保存 ok](文件.存在(路径="demo.txt"))**,供下一步使用。 1. `ok` **打印 内容="有演示文件"** diff --git a/public/stdlib/文本.mq.md b/public/stdlib/文本.mq.md index ebf3597..b42bab9 100644 --- a/public/stdlib/文本.mq.md +++ b/public/stdlib/文本.mq.md @@ -8,11 +8,15 @@ description: 去空白、拆分、拼接(代码即文档试点) # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 导入 lib/文本。括号路径或经典点号调用均可。 -**`t` = [文本.去空白] s=" marqdo "** +我们先**t = [计算并保存 t](文本.去空白(s=" marqdo "))**,供下一步使用。 **打印 内容=`t`** -**`parts` = [文本.拆分] s="甲,乙,丙" sep=","** -**`j` = [文本.拼接] xs=`parts` sep="-"** +我们先**parts = [计算并保存 parts](文本.拆分(s="甲,乙,丙", sep=","))**,供下一步使用。 +我们先**j = [计算并保存 j](文本.拼接(xs=`parts`, sep="-"))**,供下一步使用。 **打印 内容=`j`** diff --git a/public/stdlib/时间.mq.md b/public/stdlib/时间.mq.md index f6a51c5..67ac365 100644 --- a/public/stdlib/时间.mq.md +++ b/public/stdlib/时间.mq.md @@ -8,12 +8,20 @@ description: Unix 时间、格式化、解析、睡眠 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + +这一页使用固定的 Unix 时间戳与固定日期文本,展示格式化和解析之间的关系。格式化得到 1970-01-01,解析得到相应秒数;它没有读取机器当前时钟。格式串使用 strftime 规则,接入其他来源时应明确原文本的时区与完整格式,不能根据看起来相似的日期就假设含义相同。 + +最后的零毫秒睡眠只演示调用位置,不用于测量调度精度,也不会制造实际等待。格式化、解析与睡眠有各自的效应和错误边界,按时间库契约授权即可。非法日期或格式不匹配时应保留诊断,不回退到时间戳零来掩盖失败。本页输出用于观察这两个固定值,不把打印结果写回源文件。 + Unix 时间助手(lib/时间)。格式为 strftime。 -**`s` = [时间.格式化] 秒=0 格式="%Y-%m-%d"** +我们先**s = [格式化给定的零时刻](时间.格式化(秒=0, 格式="%Y-%m-%d"))**,供下一步使用。 **打印 内容=`s`** -**`u` = [时间.解析时间] 内容="1970-01-01 00:00:00" 格式="%Y-%m-%d %H:%M:%S"** +我们先**u = [解析当前日期或 URL 输入](时间.解析时间(内容="1970-01-01 00:00:00", 格式="%Y-%m-%d %H:%M:%S"))**,供下一步使用。 **打印 内容=`u`** -**[时间.睡眠毫秒] 毫秒=0** +此处**[以零毫秒演示等待调用](时间.睡眠毫秒(毫秒=0))**,随后即可结束本页演示。 diff --git a/public/stdlib/系统.mq.md b/public/stdlib/系统.mq.md index 32fa3b4..77c74cc 100644 --- a/public/stdlib/系统.mq.md +++ b/public/stdlib/系统.mq.md @@ -8,13 +8,17 @@ description: 环境变量、dotenv、工作目录、参数、退出、执行 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 导入 lib/系统.mq.md。函数:取环境、设环境、加载环境(可选路径)、参数表、工作目录、退出(码)、执行(命令)。加载环境不覆盖已有变量。view 下退出会软失败,不结束进程。 -**`d` = [系统.工作目录]** +我们先**d = [计算并保存 d](系统.工作目录())**,供下一步使用。 -**`n` = [长度] 值=`d`** +我们先**n = [计算并保存 n](长度(值=`d`))**,供下一步使用。 1. `n` > 0 - > 打印 内容=工作目录就绪 + 随后我们**[显示当前步骤的结果](> 打印 内容="工作目录就绪")**。 2. * - > 打印 内容=工作目录空 + 随后我们**[显示当前步骤的结果](> 打印 内容="工作目录空")**。 diff --git a/public/stdlib/网络.mq.md b/public/stdlib/网络.mq.md index 2f69aab..1f914a8 100644 --- a/public/stdlib/网络.mq.md +++ b/public/stdlib/网络.mq.md @@ -8,8 +8,12 @@ description: HTTP(S) 与地址编码 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 导入 lib/网络.mq.md。函数:获取(地址)、提交(地址, 内容;可选 content_type / headers)、编码地址(内容)。支持 HTTP 与 HTTPS(ureq)。 -**`e` = [网络.编码地址] 内容="你好"** +我们先**e = [计算并保存 e](网络.编码地址(内容="你好"))**,供下一步使用。 -> 打印 内容=`e` +随后我们**[显示当前步骤的结果](> 打印 内容=`e`)**。 diff --git a/public/stdlib/自写回.mq.md b/public/stdlib/自写回.mq.md index 32b9e7c..facc756 100644 --- a/public/stdlib/自写回.mq.md +++ b/public/stdlib/自写回.mq.md @@ -8,6 +8,10 @@ description: 把运行结果写回入口 .mq.md # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 自写回把结果写入入口文件(你 run 的那份 .mq.md)里的 marqdo-out 注释块。 记录 内容=(record)— 默认写在调用下方;at_end=真 则在文件末尾单独一块。 @@ -16,4 +20,4 @@ description: 把运行结果写回入口 .mq.md 列表 — 列出文件中所有输出块。 -> 打印 内容=自写回总览就绪 +随后我们**[显示当前步骤的结果](> 打印 内容="自写回总览就绪")**。 diff --git a/public/stdlib/表.mq.md b/public/stdlib/表.mq.md index 0707d56..e0a1430 100644 --- a/public/stdlib/表.mq.md +++ b/public/stdlib/表.mq.md @@ -8,6 +8,14 @@ description: 改 / 行数 / 取行(代码即文档试点) # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + +先用一列表格表示两个文本元素,再替换第一项并保存返回的新列表。集合更新是不可变操作,若忽略返回值,原变量就仍指向旧数据。改操作的路径位置从一开始,而取行的 i 从零开始;本例刻意把两者并排展示,以免读者把不同接口的索引约定混为一谈。 + +更新后的第一项为甲改,列表长度仍为二,取行返回同一个第一项。本例不涉及文件、插件或解释器,输入与返回均是普通 Marqdo 值。真实业务可以继续组合筛选、映射和聚合;对于嵌套记录,先明确路径中每一段是字段名还是列表位置,并让缺失路径的诊断保持可见。打印只帮助观察,不会使后续函数自动获得这些值。 + 嵌套写入用 表.改;读元用链接取元。 `xs` = @@ -17,9 +25,9 @@ description: 改 / 行数 / 取行(代码即文档试点) | 甲 | | 乙 | -**`xs` = [表.改] 入=`xs` 于=1 值="甲改"** -**`n` = [表.行数] xs=`xs`** -**`r` = [表.取行] xs=`xs` i=0** +我们先**xs = [替换列表第一项并保留新集合](表.改(入=`xs`, 于=1, 值="甲改"))**,供下一步使用。 +我们先**n = [取得本步骤需要的路径或计数](表.行数(xs=`xs`))**,供下一步使用。 +我们先**r = [按零起点读取第一行](表.取行(xs=`xs`, i=0))**,供下一步使用。 **打印 内容=[1](access(xs, "1"))** **打印 内容=`n`** diff --git a/public/structure/01-hello.mq.md b/public/structure/01-hello.mq.md index dc3313b..c1f33c2 100644 --- a/public/structure/01-hello.mq.md +++ b/public/structure/01-hello.mq.md @@ -6,8 +6,12 @@ description: Smallest runnable doc # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Ordinary paragraphs are comments. `print` is a built-in, not a syntax marker. Lines that start with Markdown emphasis markers can be treated as code — keep narrative as plain prose. -> print text=Hello World! +We now **[Display this step's result](> print text="Hello World!")**. diff --git a/public/structure/01-你好.mq.md b/public/structure/01-你好.mq.md index 877d751..b53cefa 100644 --- a/public/structure/01-你好.mq.md +++ b/public/structure/01-你好.mq.md @@ -6,8 +6,12 @@ description: 最小可运行文档 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 普通段落是注释。`打印` 是内置函数,不是语法标记。 以 Markdown 强调标记开头的行可当作代码——叙述请用普通段落。 -> 打印 内容=你好世界! +随后我们**[显示当前步骤的结果](> 打印 内容="你好世界!")**。 diff --git a/public/structure/02-function.mq.md b/public/structure/02-function.mq.md index 630d10f..511017b 100644 --- a/public/structure/02-function.mq.md +++ b/public/structure/02-function.mq.md @@ -1,18 +1,30 @@ --- markup: occlusion title: Functions and named calls -description: `#` defines functions; `>` calls; `-` lists parameter names +description: Callable headings, narrative inputs and readable named calls --- # main -Use `#` / `##` for functions. Parameters are bare `- name` lines under the heading. +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + +Headings expose callable definitions. The input contract sits directly below the heading, and its body names the recipient in prose; callers supply that value by name. Call with `>` and named args `param=value`: -> greet who=World +We now **[Call greet](> greet who="World")**. ## greet - + `who` -> print text=Hello `who`! +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| who | any | required | Recipient name inserted into the greeting | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; display the computed content on stdout | +Input `who`, used by the steps below. + +We now **[Display this step's result](> print text="Hello `who`!")**. diff --git a/public/structure/02-函数.mq.md b/public/structure/02-函数.mq.md index 005631e..b9d99d6 100644 --- a/public/structure/02-函数.mq.md +++ b/public/structure/02-函数.mq.md @@ -6,13 +6,25 @@ description: `#` 定义函数;`>` 调用;`-` 列出参数名 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 用 `#` / `##` 定义函数。参数是标题下的裸 `- 名` 行。 用 `>` 与具名实参 `参数=值` 调用: -> 问候 谁=世界 +随后我们**[执行 问候](> 问候 谁="世界")**。 ## 问候 - + `谁` -> 打印 内容=你好 `谁`! +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 谁 | any | 必填 | 要显示在问候中的称呼 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;通过标准输出显示本函数计算的内容。 | +输入`谁`,按下方步骤使用这个值。 + +随后我们**[显示当前步骤的结果](> 打印 内容="你好 `谁`!")**。 diff --git a/public/structure/03-positional-call.mq.md b/public/structure/03-positional-call.mq.md index 8b69aac..5516c4b 100644 --- a/public/structure/03-positional-call.mq.md +++ b/public/structure/03-positional-call.mq.md @@ -6,15 +6,27 @@ description: Bind by parameter order; named form still works # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Positional args bind in declaration order (no `who=` needed): -> greet Marqdo +We now **[Call greet](> greet "Marqdo")**. Named form still works: -> greet who=World +We now **[Call greet](> greet who="World")**. ## greet - + `who` -> print text=Hello `who`! +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| who | any | required | Recipient name inserted into the greeting | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; display the computed content on stdout | +Input `who`, used by the steps below. + +We now **[Display this step's result](> print text="Hello `who`!")**. diff --git a/public/structure/03-位置调用.mq.md b/public/structure/03-位置调用.mq.md index 321a7f8..f78db05 100644 --- a/public/structure/03-位置调用.mq.md +++ b/public/structure/03-位置调用.mq.md @@ -6,15 +6,27 @@ description: 按参数声明顺序绑定;具名写法仍然可用 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 位置实参按声明顺序绑定(不必写 `谁=`): -> 问候 Marqdo +随后我们**[执行 问候](> 问候 "Marqdo")**。 具名写法仍然可用: -> 问候 谁=世界 +随后我们**[执行 问候](> 问候 谁="世界")**。 ## 问候 - + `谁` -> 打印 内容=你好 `谁`! +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 谁 | any | 必填 | 要显示在问候中的称呼 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;通过标准输出显示本函数计算的内容。 | +输入`谁`,按下方步骤使用这个值。 + +随后我们**[显示当前步骤的结果](> 打印 内容="你好 `谁`!")**。 diff --git a/public/structure/04-branch.mq.md b/public/structure/04-branch.mq.md index fb7245e..8140f15 100644 --- a/public/structure/04-branch.mq.md +++ b/public/structure/04-branch.mq.md @@ -1,18 +1,22 @@ --- markup: occlusion title: Branch -description: `+` arms; a lone `*` arm is else +description: Ordered branches select one case and retain an explicit fallback --- # main -Italic lines are statements. Branches use `+`; a head that is only `*` is the else arm. +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | -**`x` = 0** +Bold markers execute statements and single italics return a value. Ordered list items select a branch; the final asterisk condition is the fallback when earlier conditions do not match. + +We first **x = 0** for the next step. 1. `x` > 0 - > print text=positive + We now **[Display this step's result](> print text="positive")**. 2. `x` < 0 - > print text=negative + We now **[Display this step's result](> print text="negative")**. 3. * - > print text=zero + We now **[Display this step's result](> print text="zero")**. diff --git a/public/structure/04-分支.mq.md b/public/structure/04-分支.mq.md index 56f57c2..d162a36 100644 --- a/public/structure/04-分支.mq.md +++ b/public/structure/04-分支.mq.md @@ -6,13 +6,17 @@ description: `+` 各臂;单独的 `*` 臂为否则 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 斜体行是语句。分支用 `+`;表头仅为 `*` 的是否则臂。 -**`x` = 0** +我们先**x = 0**,供下一步使用。 1. `x` > 0 - > 打印 内容=正数 + 随后我们**[显示当前步骤的结果](> 打印 内容="正数")**。 2. `x` < 0 - > 打印 内容=负数 + 随后我们**[显示当前步骤的结果](> 打印 内容="负数")**。 3. * - > 打印 内容=零 + 随后我们**[显示当前步骤的结果](> 打印 内容="零")**。 diff --git a/public/structure/05-loop.mq.md b/public/structure/05-loop.mq.md index 2b6798e..b746851 100644 --- a/public/structure/05-loop.mq.md +++ b/public/structure/05-loop.mq.md @@ -6,15 +6,19 @@ description: Condition loops and table walks # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + Inside a function body, `-` starts a loop (not a parameter). Countdown: -**`n` = 3** +We first **n = 3** for the next step. - `n` > 0 - > print text=`n` - **`n` = `n` - 1** + We now **[Display this step's result](> print text=`n`)**. + We first **n = (`n` - 1)** for the next step. Walk a table (tables are collections): @@ -26,4 +30,4 @@ Walk a table (tables are collections): | pear | - [fruit](遍历 basket 为 fruit) - > print text=today `fruit` + We now **[Display this step's result](> print text="today `fruit`")**. diff --git a/public/structure/05-循环.mq.md b/public/structure/05-循环.mq.md index a137227..fcf8673 100644 --- a/public/structure/05-循环.mq.md +++ b/public/structure/05-循环.mq.md @@ -6,15 +6,19 @@ description: 条件循环与表遍历 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 在函数体里,`-` 表示循环(不是参数)。 倒数: -**`n` = 3** +我们先**n = 3**,供下一步使用。 - `n` > 0 - > 打印 内容=`n` - **`n` = `n` - 1** + 随后我们**[显示当前步骤的结果](> 打印 内容=`n`)**。 + 我们先**n = (`n` - 1)**,供下一步使用。 遍历表(表即集合): @@ -26,4 +30,4 @@ description: 条件循环与表遍历 | 梨 | - [水果](遍历 篮子 为 水果) - > 打印 内容=今天 `水果` + 随后我们**[显示当前步骤的结果](> 打印 内容="今天 `水果`")**。 diff --git a/public/structure/06-collection.mq.md b/public/structure/06-collection.mq.md index a7d7788..5e202fb 100644 --- a/public/structure/06-collection.mq.md +++ b/public/structure/06-collection.mq.md @@ -6,6 +6,10 @@ description: One-column tables are lists # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + A single-column Markdown table is a list; loop to read each item. Prefer link-index get `[1](basket)` (1-based). `basket` = @@ -17,4 +21,4 @@ A single-column Markdown table is a list; loop to read each item. Prefer link-in | peach | - [fruit](遍历 basket 为 fruit) - > print text=`fruit` + We now **[Display this step's result](> print text=`fruit`)**. diff --git a/public/structure/06-集合.mq.md b/public/structure/06-集合.mq.md index 961bad6..bf6223c 100644 --- a/public/structure/06-集合.mq.md +++ b/public/structure/06-集合.mq.md @@ -6,6 +6,10 @@ description: 单列竖表即列表 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 单列 Markdown 表是列表;用循环读每一项。按下标优先用链接取元 `[1](篮子)`(1-based)。 `篮子` = @@ -17,4 +21,4 @@ description: 单列竖表即列表 | 桃 | - [水果](遍历 篮子 为 水果) - > 打印 内容=`水果` + 随后我们**[显示当前步骤的结果](> 打印 内容=`水果`)**。 diff --git a/public/structure/07-map.mq.md b/public/structure/07-map.mq.md index 380ad0a..0f605db 100644 --- a/public/structure/07-map.mq.md +++ b/public/structure/07-map.mq.md @@ -6,6 +6,10 @@ description: Multi-column tables are maps; link-index get # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + A multi-column table with one data row is a map. Read values with `[key](map)`. `kinds` = @@ -14,10 +18,10 @@ A multi-column table with one data row is a map. Read values with `[key](map)`. |-------|----------| | fruit | vegetable | -**`k` = [apple](access(kinds, "apple"))** +We first **k = [apple](access(`kinds`, "apple"))** for the next step. -> print text=`k` +We now **[Display this step's result](> print text=`k`)**. -**`k` = [cucumber](access(kinds, "cucumber"))** +We first **k = [cucumber](access(`kinds`, "cucumber"))** for the next step. -> print text=`k` +We now **[Display this step's result](> print text=`k`)**. diff --git a/public/structure/07-字典.mq.md b/public/structure/07-字典.mq.md index 6f28c98..aa9d6a1 100644 --- a/public/structure/07-字典.mq.md +++ b/public/structure/07-字典.mq.md @@ -6,6 +6,10 @@ description: 多列表是字典;链接取元 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 多列且仅一行数据的表是字典。用 `[键](字典)` 取元。 `分类` = @@ -14,10 +18,10 @@ description: 多列表是字典;链接取元 |------|------| | 水果 | 蔬菜 | -**`种` = [苹果](access(分类, "苹果"))** +我们先**种 = [苹果](access(`分类`, "苹果"))**,供下一步使用。 -> 打印 内容=`种` +随后我们**[显示当前步骤的结果](> 打印 内容=`种`)**。 -**`种` = [黄瓜](access(分类, "黄瓜"))** +我们先**种 = [黄瓜](access(`分类`, "黄瓜"))**,供下一步使用。 -> 打印 内容=`种` +随后我们**[显示当前步骤的结果](> 打印 内容=`种`)**。 diff --git a/public/structure/08-records.mq.md b/public/structure/08-records.mq.md index b69c229..2ccdaca 100644 --- a/public/structure/08-records.mq.md +++ b/public/structure/08-records.mq.md @@ -6,6 +6,10 @@ description: First header @ / row makes a list of maps # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + When the first header is `@` or `row`, each data row is a map (marker column is not a field). Nested get: `[field]([1](orders))`. `orders` = @@ -15,10 +19,10 @@ When the first header is `@` or `row`, each data row is a map (marker column is | 1 | apple | 2 | | 2 | pear | 3 | -**`n` = [name](access([1](access(orders, "1")), "name"))** +We first **n = [name](access([1](access(`orders`, "1")), "name"))** for the next step. -> print text=`n` +We now **[Display this step's result](> print text=`n`)**. -**`q` = [qty](access([2](access(orders, "2")), "qty"))** +We first **q = [qty](access([2](access(`orders`, "2")), "qty"))** for the next step. -> print text=`q` +We now **[Display this step's result](> print text=`q`)**. diff --git a/public/structure/08-记录表.mq.md b/public/structure/08-记录表.mq.md index 7945d36..a11e68a 100644 --- a/public/structure/08-记录表.mq.md +++ b/public/structure/08-记录表.mq.md @@ -6,6 +6,14 @@ description: 首列表头「行」→ 每行一个字典 # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + +表头标记决定了这是一组行记录,而不是按列保存的字段列表。第一条记录的品名为苹果,第二条记录的数量为三;标记列只负责声明形态,不成为业务字段。读者可以先用 access 选出某一条记录,再按字段名取值,逐步核对每一步得到的是列表、记录还是标量。 + +本例保留两种字段类型:品名是文本,数量是整数,不把整张表先转成 JSON 再解析。遮蔽标签只写读取目的,真正的索引和字段名放在圆括号里;不要把标签中的数字当成另外一次索引。所有数据都来自本页,没有文件或网络访问。扩展字段时应同步更新相关函数的输入契约,让调用者知道新增列是否必填。 + 首列表头为 `行`(或 `@` / `row`)时,每行数据是一个字典;标记列不进入字段。嵌套取元:`[字段]([1](订单))`。 `订单` = @@ -15,10 +23,10 @@ description: 首列表头「行」→ 每行一个字典 | 1 | 苹果 | 2 | | 2 | 梨 | 3 | -**`名` = [品名](access([1](access(订单, "1")), "品名"))** +我们先**名 = [品名](access([1](access(`订单`, "1")), "品名"))**,供下一步使用。 -> 打印 内容=`名` +随后我们**[显示当前步骤的结果](> 打印 内容=`名`)**。 -**`量` = [数量](access([2](access(订单, "2")), "数量"))** +我们先**量 = [数量](access([2](access(`订单`, "2")), "数量"))**,供下一步使用。 -> 打印 内容=`量` +随后我们**[显示当前步骤的结果](> 打印 内容=`量`)**。 diff --git a/public/structure/09-inherit.mq.md b/public/structure/09-inherit.mq.md index 430703b..5f6efdc 100644 --- a/public/structure/09-inherit.mq.md +++ b/public/structure/09-inherit.mq.md @@ -6,25 +6,53 @@ description: "# Child = > Parent; methods walk the base chain" # Greeter -## hello - + `who` +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Object/type namespace for the child functions below; call the intended child directly | -**`msg` = "Hello, `who`!"** -*`msg`* +## hello + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| who | any | required | Recipient name inserted into the greeting | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | The value explicitly returned below; conditional returns follow the selected branch | +Input `who`, used by the steps below. + +We first **msg = "Hello, `who`!"** for the next step. +After these steps, return *msg*. # Loud = > Greeter -## hello - + `who` +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Object/type namespace for the child functions below; call the intended child directly | -**`msg` = "HELLO, `who`!"** -*`msg`* +## hello + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| who | any | required | Recipient name inserted into the greeting | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | The value explicitly returned below; conditional returns follow the selected branch | +Input `who`, used by the steps below. + +We first **msg = "HELLO, `who`!"** for the next step. +After these steps, return *msg*. # main -**`g` = > Greeter** -**`m` = > `g`.hello who="world"** -> print text=`m` -**`l` = > Loud** -**`m2` = > `l`.hello who="world"** -> print text=`m2` +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + +We first **g = [Compute g](Greeter())** for the next step. +We first **m = `g`.hello(who="world")** for the next step. +We now **[Display this step's result](> print text=`m`)**. +We first **l = [Compute l](Loud())** for the next step. +We first **m2 = `l`.hello(who="world")** for the next step. +We now **[Display this step's result](> print text=`m2`)**. diff --git a/public/structure/09-继承.mq.md b/public/structure/09-继承.mq.md index b95ed84..8f8e8bd 100644 --- a/public/structure/09-继承.mq.md +++ b/public/structure/09-继承.mq.md @@ -6,25 +6,53 @@ description: "# 子类 = > 父类;方法沿基类链查找" # 问候者 -## 你好 - + `谁` +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 供下述方法复用的对象或类型命名空间;直接调用所需的子函数。 | -**`msg` = "你好,`谁`!"** -*`msg`* +## 你好 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 谁 | any | 必填 | 要显示在问候中的称呼 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | +输入`谁`,按下方步骤使用这个值。 + +我们先**msg = "你好,`谁`!"**,供下一步使用。 +完成上述步骤后,返回*msg*。 # 大声 = > 问候者 -## 你好 - + `谁` +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 供下述方法复用的对象或类型命名空间;直接调用所需的子函数。 | -**`msg` = "你好,`谁`!!!"** -*`msg`* +## 你好 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 谁 | any | 必填 | 要显示在问候中的称呼 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | +输入`谁`,按下方步骤使用这个值。 + +我们先**msg = "你好,`谁`!!!"**,供下一步使用。 +完成上述步骤后,返回*msg*。 # main -**`g` = > 问候者** -**`m` = > `g`.你好 谁="世界"** -> 打印 内容=`m` -**`l` = > 大声** -**`m2` = > `l`.你好 谁="世界"** -> 打印 内容=`m2` +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + +我们先**g = [计算并保存 g](问候者())**,供下一步使用。 +我们先**m = `g`.你好(谁="世界")**,供下一步使用。 +随后我们**[显示当前步骤的结果](> 打印 内容=`m`)**。 +我们先**l = [计算并保存 l](大声())**,供下一步使用。 +我们先**m2 = `l`.你好(谁="世界")**,供下一步使用。 +随后我们**[显示当前步骤的结果](> 打印 内容=`m2`)**。 diff --git a/public/structure/import/main.mq.md b/public/structure/import/main.mq.md index dcdc4ed..3b8d826 100644 --- a/public/structure/import/main.mq.md +++ b/public/structure/import/main.mq.md @@ -8,12 +8,16 @@ import: # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + In the YAML header, nested `import:` with `utils: utils.mq.md` imports a sibling module and binds the library name `utils`. Bind a return value, print it, then call greet: -**`y` = [utils.add_one] n=41** +We first **y = [Compute y](utils.add_one(n=41))** for the next step. -> print text=`y` +We now **[Display this step's result](> print text=`y`)**. -> utils.greet who=Marqdo +We now **[Call utils.greet](> utils.greet who="Marqdo")**. diff --git a/public/structure/import/utils.mq.md b/public/structure/import/utils.mq.md index 7323745..7ec6a08 100644 --- a/public/structure/import/utils.mq.md +++ b/public/structure/import/utils.mq.md @@ -5,13 +5,29 @@ description: Imported by main; italic is return; print for side effects --- ## add_one - + `n` -*n + 1* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| n | any | required | Numeric input advanced or calculated by this example | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | The value explicitly returned below; conditional returns follow the selected branch | +Input `n`, used by the steps below. + +After these steps, return *(`n` + 1)*. ## greet - + `who` -> print text=Hello, `who`! +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| who | any | required | Recipient name inserted into the greeting | -*None* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; this function performs the described effects instead of returning business data | +Input `who`, used by the steps below. + +We now **[Display this step's result](> print text="Hello, `who`!")**. + +After these steps, return *None*. diff --git a/public/structure/import/主.mq.md b/public/structure/import/主.mq.md index 2328521..412251a 100644 --- a/public/structure/import/主.mq.md +++ b/public/structure/import/主.mq.md @@ -8,12 +8,16 @@ description: frontmatter 导入 bind:路径.mq.md # main +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | + 在 YAML 头里写 `导入 工具:工具.mq.md` 可导入同级模块并绑定库名「工具」。 绑定返回值、打印,再调用问候: -**`y` = [工具.加一] n=41** +我们先**y = [计算并保存 y](工具.加一(n=41))**,供下一步使用。 -> 打印 内容=`y` +随后我们**[显示当前步骤的结果](> 打印 内容=`y`)**。 -> 工具.问候 谁=Marqdo +随后我们**[执行 工具.问候](> 工具.问候 谁="Marqdo")**。 diff --git a/public/structure/import/工具.mq.md b/public/structure/import/工具.mq.md index 4dd9436..f8c6eb3 100644 --- a/public/structure/import/工具.mq.md +++ b/public/structure/import/工具.mq.md @@ -5,13 +5,29 @@ description: 被 main 导入;斜体为返回;副作用用打印 --- ## 加一 - + `n` -*n + 1* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| n | any | 必填 | Numeric input advanced or calculated by this example | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | +输入`n`,按下方步骤使用这个值。 + +完成上述步骤后,返回*(`n` + 1)*。 ## 问候 - + `谁` -> 打印 内容=你好,`谁`! +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 谁 | any | 必填 | 要显示在问候中的称呼 | -*无* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 空值;本函数通过上述操作产生效果,不返回业务数据。 | +输入`谁`,按下方步骤使用这个值。 + +随后我们**[显示当前步骤的结果](> 打印 内容="你好,`谁`!")**。 + +完成上述步骤后,返回*None*。 diff --git a/scripts/ppa-build-source.sh b/scripts/ppa-build-source.sh old mode 100755 new mode 100644 index c95a137..6982f4e --- a/scripts/ppa-build-source.sh +++ b/scripts/ppa-build-source.sh @@ -19,6 +19,19 @@ SERIES="${1:-noble}" ROOT="$(cd "$(dirname "$0")/.." && pwd)" cd "$ROOT" +# File authoring uses the interpreter being released, including in package staging. +MARQDO_TOOL="${MARQDO_BIN:-$ROOT/target/debug/marqdo}" +if [ ! -x "$MARQDO_TOOL" ]; then + MARQDO_TOOL="$ROOT/target/release/marqdo" +fi +if [ ! -x "$MARQDO_TOOL" ]; then + MARQDO_TOOL="$(command -v marqdo || true)" +fi +if [ -z "$MARQDO_TOOL" ] || [ ! -x "$MARQDO_TOOL" ]; then + echo "error: build Marqdo or set MARQDO_BIN before packaging" >&2 + exit 1 +fi + need() { command -v "$1" >/dev/null || { echo "missing tool: $1 (sudo apt install $2)"; exit 1; }; } need cargo cargo need debuild devscripts @@ -34,22 +47,11 @@ fi mkdir -p "$TMPDIR" export TMPDIR -VER="$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)" -# Debian revision comes from debian/changelog (e.g. 1.0.2-1ppa2); we append ~series. -CHG_VER="$(dpkg-parsechangelog -l debian/changelog -S Version)" -# Strip any previous ~series suffix from changelog version -BASE_DEB_VER="${CHG_VER%%~*}" -# If changelog still has old upstream, prefer Cargo VER for the upstream part -if [[ "$BASE_DEB_VER" != "$VER"-* ]]; then - # keep debian revision suffix after first '-' following VER if possible - REV="${BASE_DEB_VER#*-}" - if [[ "$BASE_DEB_VER" == *"-"* ]]; then - BASE_DEB_VER="${VER}-${REV}" - else - BASE_DEB_VER="${VER}-1ppa1" - fi -fi -DEB_VER="${BASE_DEB_VER}~${SERIES}" +# The callable handbook owns metadata parsing; stdout contains the exact text. +VER="$("$MARQDO_TOOL" call "$ROOT/skills/marqdo-release/package.mq.md" upstream \ + --require-ok --effects fs.read --fs-root "$ROOT")" +DEB_VER="$("$MARQDO_TOOL" call "$ROOT/skills/marqdo-release/package.mq.md" debian_version \ + "series=\"$SERIES\"" --require-ok --effects fs.read --fs-root "$ROOT")" PKG_ROOT="${TMPDIR}/marqdo-ppa/${VER}" BUILD_AREA="${ROOT}/../build-area" GPG_KEY="${MARQDO_PPA_GPG_KEY:-505943294D04C803}" @@ -161,43 +163,13 @@ else cd "$PKG_ROOT" echo "==> cargo vendor (Launchpad offline)" mkdir -p .cargo - cargo vendor --locked vendor >/tmp/marqdo-cargo-vendor.conf - cat > .cargo/config.toml <<'EOF' -[source.crates-io] -replace-with = "vendored-sources" - -[source.vendored-sources] -directory = "vendor" -EOF + cargo vendor --locked vendor + "$MARQDO_TOOL" call "$ROOT/skills/marqdo-release/package.mq.md" vendor_config \ + --require-ok --effects fs.write --fs-root "$PKG_ROOT" --json # dh_clean removes *.orig; drop those paths from vendor checksums so a # stray clean (or older rules) cannot break `cargo --offline` on Launchpad. - python3 - <<'PY' -from __future__ import annotations - -import json -from pathlib import Path - -root = Path("vendor") -if not root.is_dir(): - raise SystemExit("vendor/ missing after cargo vendor") -n_files = 0 -n_json = 0 -for checksum in root.rglob(".cargo-checksum.json"): - data = json.loads(checksum.read_text(encoding="utf-8")) - files = data.get("files") or {} - drop = [name for name in files if name.endswith(".orig") or name.endswith(".rej")] - if not drop: - continue - for name in drop: - del files[name] - path = checksum.parent / name - if path.is_file(): - path.unlink() - n_files += 1 - checksum.write_text(json.dumps(data, indent=4) + "\n", encoding="utf-8") - n_json += 1 -print(f"stripped {n_files} *.orig/*.rej from {n_json} vendor checksums") -PY + "$MARQDO_TOOL" call "$ROOT/skills/marqdo-release/package.mq.md" sanitize_vendor \ + --require-ok --effects fs.write --fs-root "$PKG_ROOT" --json echo "==> bundle Rust ${RUST_VER} (${RUST_TRIPLE}) for Launchpad" if [ ! -f "$RUST_TARBALL" ]; then @@ -243,21 +215,9 @@ PY fi cd "$PKG_ROOT" -python3 - <<PY -from pathlib import Path -import re -p = Path("debian/changelog") -text = p.read_text(encoding="utf-8") -text2 = re.sub( - r"^marqdo \([^)]+\) [^;]+;", - "marqdo (${DEB_VER}) ${SERIES};", - text, - count=1, - flags=re.M, -) -p.write_text(text2, encoding="utf-8") -print("changelog:", p.read_text(encoding="utf-8").splitlines()[0]) -PY +"$MARQDO_TOOL" call "$ROOT/skills/marqdo-release/package.mq.md" changelog \ + "version=\"$DEB_VER\"" "series=\"$SERIES\"" \ + --require-ok --effects fs.write --fs-root "$PKG_ROOT" --json ln -sfn "$BUILD_AREA/$ORIG_NAME" "$(dirname "$PKG_ROOT")/$ORIG_NAME" ls -lh "$BUILD_AREA/$ORIG_NAME" diff --git a/scripts/ppa-ship.sh b/scripts/ppa-ship.sh old mode 100755 new mode 100644 index 605de07..9ddc437 --- a/scripts/ppa-ship.sh +++ b/scripts/ppa-ship.sh @@ -47,7 +47,7 @@ fi PPA_TARGET="${MARQDO_PPA:-ppa:cflmy/marqdo}" PKGS=(build-essential debhelper devscripts dput lintian dpkg-dev quilt cargo rustc pkg-config libssl-dev ca-certificates - python3 xz-utils) + xz-utils) need_apt=0 for bin in debuild dput dpkg-parsechangelog cargo gpg; do @@ -72,16 +72,20 @@ fi echo "==> building source package for series=${SERIES}" run_user "$ROOT/scripts/ppa-build-source.sh" "$SERIES" -VER="$(sed -n 's/^version = "\(.*\)"/\1/p' "$ROOT/Cargo.toml" | head -1)" -BUILD_AREA="$(cd "$ROOT/.." && pwd)/build-area" -# Prefer changes matching this series; fall back to newest source.changes -CHANGES="$(ls -1t "$BUILD_AREA"/marqdo_*"~${SERIES}"_source.changes 2>/dev/null | head -1 || true)" -if [ -z "${CHANGES:-}" ]; then - CHANGES="$(ls -1t "$BUILD_AREA"/marqdo_*_source.changes 2>/dev/null | head -1 || true)" +# The native handbook selects the exact current-version artifact. +MARQDO_TOOL="${MARQDO_BIN:-$ROOT/target/debug/marqdo}" +if [ ! -x "$MARQDO_TOOL" ]; then MARQDO_TOOL="$ROOT/target/release/marqdo"; fi +if [ ! -x "$MARQDO_TOOL" ]; then MARQDO_TOOL="$(command -v marqdo || true)"; fi +if [ -z "$MARQDO_TOOL" ] || [ ! -x "$MARQDO_TOOL" ]; then + echo "error: build Marqdo or set MARQDO_BIN before packaging" >&2 + exit 1 fi -if [ -z "${CHANGES:-}" ] || [ ! -f "$CHANGES" ]; then - echo "error: no *_source.changes under $BUILD_AREA" >&2 - ls -la "$BUILD_AREA" 2>/dev/null || true +DEB_VER="$(run_user "$MARQDO_TOOL" call "$ROOT/skills/marqdo-release/package.mq.md" debian_version \ + "series=\"$SERIES\"" --require-ok --effects fs.read --fs-root "$ROOT")" +BUILD_AREA="$(cd "$ROOT/.." && pwd)/build-area" +CHANGES="$BUILD_AREA/marqdo_${DEB_VER}_source.changes" +if [ ! -f "$CHANGES" ]; then + echo "error: expected source artifact is missing: $CHANGES" >&2 exit 1 fi diff --git a/skills/marqdo-dev/SKILL.md b/skills/marqdo-dev/SKILL.md new file mode 100644 index 0000000..0769554 --- /dev/null +++ b/skills/marqdo-dev/SKILL.md @@ -0,0 +1,16 @@ +--- +name: marqdo-dev +description: Write, refactor and verify Marqdo programs, standard libraries and extensions through the executable development handbook. Use native Marqdo file tools and marqdo call; extend capability gaps through plugins or explicit external tools. +--- + +Read [the executable development entry](../marqdo-dev/index.mq.md), then [the programming guide](../../doc/library-development.mq.md). The same guide governs programs, libraries and executable SKILLs. For installed skills, resolve these paths against the Marqdo source checkout. + +Use `**statement**` to execute and `*return*` to return; write `[intent](actual code)` inside executable positions, and `access(coll, key)` to read collections. The guide provides real examples. Native file tasks live in [files.mq.md](../marqdo-dev/files.mq.md): read, bounded excerpt, write, patch, search, inventory, audit and apply. Use excerpt for long generated lines; its source locations remain one-based and clipped text is inspection evidence, not replacement source. Do not generate Python or shell programs for ordinary file operations. + +Prepare the native engineering plugin with the development entry before using its analysis or process tasks. The repository development binary is `target/debug/marqdo`; installed older binaries may need a bootstrap Cargo build through `lib/sys.mq.md exec`. All subsequent task execution uses `marqdo call`. Keep decisions and sequencing in readable mq.md; use a new extension or a documented foreign tool only for a real capability gap. + +The guide is authoritative for narrative over 50%, immediate parameter/return tables, inline statements and returns, GFM data, index.mq.md organization, recursive Markdown web components, failure evidence and verification. Read each task's contract and grant its actual effects. External processes retain their OS authority. Do not rewrite intentional test fixtures or restore removed compose_* APIs. + +Use the development entry's audit task to discover and review maintained repository sources. Its failed Result retains every finding; write_report=True saves the same evidence under .marqdo/audit. It does not execute inspected source or treat known placeholder warnings as completed logic. + +Build current WASM with the entry's build_browser task. If the system target is incompatible, call [toolchain.mq.md](../marqdo-dev/toolchain.mq.md) rust_wasm_linux and pass its returned compiler path. Prepare the workspace browser driver with prepare_browser, then run test_browser for actual SPA/history and two-tab collaboration behavior. These tasks retain native file IO and use existing compiler/browser tools only at their documented boundaries. diff --git a/skills/marqdo-dev/browser.mq.md b/skills/marqdo-dev/browser.mq.md new file mode 100644 index 0000000..ab53ed6 --- /dev/null +++ b/skills/marqdo-dev/browser.mq.md @@ -0,0 +1,108 @@ +--- +markup: occlusion +title: Real browser preparation and verification through Marqdo +import: + fs: lib/fs.mq.md + sys: lib/sys.mq.md + re: lib/re.mq.md + table: lib/table.mq.md + result: lib/result.mq.md + engineering: ext/engineering/index.mq.md +--- + +Build current browser assets through the development entry's build_browser task. This module prepares the external browser driver and runs the actual UI cases, including the native browser-effects demonstration and both complete literary sites. Files and orchestration remain native Marqdo; browser automation is a documented external capability, and no Python program performs the development workflow. + +## prepare + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | "1.65.0" | Pinned Playwright package version verified by this repository | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result of workspace-local dependency and Chromium preparation | + +Use `version`="1.65.0" to prepare the external browser-test driver under .marqdo/browser-tests. Node, npm and Playwright are explicit test-tool boundaries; the application itself remains Marqdo, and each test starts the real server through marqdo call. Native filesystem operations create the selected workspace directories. The package and browser caches stay there, with no global npm installation or Python runner. Grant plugin, process.exec and fs.write. + +Preparation is separate from verification because installing a browser does not test a page. Each command must succeed before the next one starts. The pinned version and child-only PLAYWRIGHT_BROWSERS_PATH make the driver reproducible. If a required system library is absent, preserve the actual error rather than reporting browser validation as complete. This task changes no application source or repository package manifest. + +1. not [A pinned stable package version](re.is_match(text=`version`, pattern="^[0-9]+[.][0-9]+[.][0-9]+$")) + Return *[Require an explicit stable package version](result.error(code="browser.version", message="use a pinned numeric Playwright version"))*. +We **[Create the task-owned workspace tool directory](fs.make_dirs(path=".marqdo/browser-tests"))**. +We **package = "playwright@" + version**. + +`install_args` = + +| argument | +|---| +| npm | +| install | +| "--prefix" | +| .marqdo/browser-tests | +| "--cache" | +| .marqdo/browser-tests/npm-cache | +| "--no-save" | +| "--package-lock=false" | +| `package` | + +We **installed = [Prepare the pinned external browser driver](engineering.checked(argv=`install_args`, timeout_ms=180000, max_output=65536))**. +1. not access(`installed`, "ok") + Return *installed*. +We **cache = sys.cwd() + "/.marqdo/browser-tests/browsers"** and **environment = [Keep browser downloads inside this workspace](table.put(in=None, at="PLAYWRIGHT_BROWSERS_PATH", value=`cache`))**. + +`browser_args` = + +| argument | +|---| +| node | +| .marqdo/browser-tests/node_modules/playwright/cli.js | +| install | +| chromium | + +Return *[Prepare the actual headless Chromium runtime](engineering.checked(argv=`browser_args`, env=`environment`, timeout_ms=300000, max_output=65536))*. + +## verify + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| out | text | ".marqdo/browser-handbook-assets" | Current build_browser output directory | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result from real browser effects, SPA, collaboration, bilingual network and bilingual complete-site browser cases | + +Use `out`=".marqdo/browser-handbook-assets" after build_browser has produced the current WASM and prepare has installed the pinned browser driver. This task copies only the two named generated runtime assets with native Marqdo file operations; client sources remain in their project directories. Both source artifacts must exist before any example is staged. Grant plugin, process.exec and fs.write. + +The external Node test harness supplies browser automation and process supervision only. It starts each application's callable serve function on a selected loopback port, then uses the actual WASM, DOM events, history and WebSocket transport. The browser-effects case verifies duplicate-row identity, literal labels, clipboard/download payloads, completed draft storage, timer cancellation, real history, ordered HTTP success/failure records and local WebSocket echo. SPA checks cover native list records, editing quoted text, new ids and back/forward behavior. Two tabs verify presence, remote snapshots, the first local edit after a remote update and an empty document. The English and Chinese network-site cases uses an owned database created and removed through native Marqdo file calls, verifying real echo, form-validation retry, current article data and authenticated administration. The complete English and Chinese sites also verify original theme declarations, current card/detail separation, real session navigation, the gated custom desk and logout. Their font requests are explicitly aborted so local acceptance proves declared families and fallback rendering, not external font delivery. Narrow viewport checks expose layout overflow. A saved native report retains actual failures; a source contract or constructed effect map is not substituted for a browser result. + +We **wasm = out + "/marqdo_wasm.wasm"** and **bridge = out + "/marqdo-bridge.js"**. +1. not [The current WASM exists](fs.exists(path=`wasm`)) or not [The canonical bridge exists](fs.exists(path=`bridge`)) + Return *[Require a real current browser build](result.error(code="browser.assets", message="call build_browser before browser verification"))*. + +`sites` = + +| path | +|---| +| examples/browser-app/static | +| examples/web-spa-app/static | +| examples/web-collab-doc/static | +| examples/web-net-site/public/generated | +| examples/web-net-site-zh/public/generated | + +- [Stage only the two generated browser resources](for sites as directory) + We **[Keep the static destination inside the granted root](fs.make_dirs(path=`directory`))**. + We **wasm_dest = directory + "/marqdo_wasm.wasm"** and **bridge_dest = directory + "/marqdo-bridge.js"**. + We **[Copy the actual current WASM natively](fs.copy_file(src=`wasm`, dest=`wasm_dest`))** and **[Copy the canonical bridge natively](fs.copy_file(src=`bridge`, dest=`bridge_dest`))**. +We **cache = sys.cwd() + "/.marqdo/browser-tests/browsers"** and **environment = [Use only the prepared workspace browser cache](table.put(in=None, at="PLAYWRIGHT_BROWSERS_PATH", value=`cache`))**. + +`argv` = + +| argument | +|---| +| node | +| "--test" | +| tests/browser_handbook.mjs | + +We **observed = [Run actual browser interaction tests](engineering.checked(argv=`argv`, env=`environment`, timeout_ms=150000, max_output=65536))**. +We **[Retain the actual test report with native IO](fs.write_json(path=".marqdo/browser-tests/result.json", value=`observed`))**. +Return *observed*. diff --git a/skills/marqdo-dev/data.mq.md b/skills/marqdo-dev/data.mq.md new file mode 100644 index 0000000..77fb145 --- /dev/null +++ b/skills/marqdo-dev/data.mq.md @@ -0,0 +1,73 @@ +--- +markup: occlusion +title: Native verification for Markdown data refactors +import: + document: lib/document.mq.md + table: lib/table.mq.md + result: lib/result.mq.md +--- + +Extract static literal tables into readable Markdown data leaves while callable sources explain their use. Compare actual old function values with the new native parser before applying source changes. These pure tasks do not execute the supplied data as a program or mutate files. + +## literal_tables + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| specifications | list | required | Records with a unique key and literal Markdown table text | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result containing ordered key/value records for all selected literal tables | + +Use `specifications` to inspect a planned Markdown data split before writing it. Each key identifies the original file and function, while text carries that table's exact source. The standard document parser preserves native literal types and shapes and refuses dynamic expressions. No file, import, process or code fence is executed. Duplicate identities are a failed Result rather than an overwritten observation, and parser diagnostics retain their actual failure. This task is pure; it supplies data evidence, not permission to replace source. + +We **rows = [Start the ordered literal evidence](table.empty_list())** and **keys = [Track exact source identities](table.empty_list())**. +- [Read every explicitly selected literal table](for specifications as specification) + We **key = [Read its source identity](access(`specification`, "key"))** and **source = [Read its exact table source](access(`specification`, "text"))**. + 1. [This identity was already observed](table.contains(list=`keys`, item=`key`)) + Return *[Keep duplicate source identity explicit](result.error(code="data.duplicate", message=`key`, operation="literal_tables"))*. + We **value = [Use the native literal table parser](document.table(text=`source`))** and **keys = [Retain this identity](table.append(list=`keys`, item=`key`))**. + + `row` = + + | key | value | + |---|---| + | `key` | `value` | + + We **rows = [Keep the complete native value](table.append(list=`rows`, item=`row`))**. +Return *[Expose ordered immutable data evidence](result.ok(value=`rows`))*. + +## compare + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| expected | list | required | Baseline key/value records obtained from actual original functions | +| actual | list | required | Key/value records obtained from the proposed literal data | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with exact count and the source keys whose native values differ | + +Use `expected` and `actual` for a data-only refactor review. Identities and cardinality are checked before any source mutation, then values are compared through native equality. A boolean must remain a boolean, and row/column/list structure must remain the same. The failed Result keeps mismatched identities in value, allowing --require-ok to stop a migration without losing evidence. This task neither writes files nor declares a later behavioral change equivalent; deliberate content edits need their own review. + +We **mismatched = [Start actual data differences](table.empty_list())** and **expected_keys = [Read baseline identities](table.pluck(list=`expected`, key="key"))** and **actual_keys = [Read proposed identities](table.pluck(list=`actual`, key="key"))**. +1. len(`expected`) != len(`actual`) or len(table.unique(list=`expected_keys`)) != len(`expected`) or len(table.unique(list=`actual_keys`)) != len(`actual`) + Return *[Reject missing or repeated data identities](result.error(code="data.identities", message="baseline and actual must have equal counts and unique keys", operation="compare"))*. +- [Compare each source's actual native value](for expected as row) + We **key = [Read its identity](access(`row`, "key"))** and **found = [Find the corresponding proposed value](table.find(list=`actual`, key="key", value=`key`))** and **same = False**. + 1. `found` != None + We **same = [Compare original and proposed types and shapes](access(row, "value") == access(found, "value"))**. + 1. not `same` + We **mismatched = [Retain the differing source identity](table.append(list=`mismatched`, item=`key`))**. +We **count = [Keep the actual baseline count](len(expected))**. + +`evidence` = + +| count | mismatched | +|---|---| +| `count` | `mismatched` | + +1. len(`mismatched`) == 0 + Return *[Retain the unchanged data evidence](result.ok(value=`evidence`))*. +We **failed = [Keep the refactor incomplete](result.error(code="data.value_drift", message="inspect the mismatched source keys", operation="compare"))**. +Return *[Preserve differences on failure](table.put(in=`failed`, at="value", value=`evidence`))*. diff --git a/skills/marqdo-dev/files.mq.md b/skills/marqdo-dev/files.mq.md new file mode 100644 index 0000000..52fccf3 --- /dev/null +++ b/skills/marqdo-dev/files.mq.md @@ -0,0 +1,476 @@ +--- +markup: occlusion +title: Native repository file operations +import: + fs: lib/fs.mq.md + re: lib/re.mq.md + hash: lib/hash.mq.md + table: lib/table.mq.md + result: lib/result.mq.md + engineering: ext/engineering/index.mq.md +--- + +Repository development reads and writes through Marqdo's own filesystem tools. +These functions are the same operations used by the handbooks, not shell text +that another agent must regenerate. Paths stay under the granted filesystem +root; pass --fs-root . at the checkout root. read/search need fs.read, while +write/patch need fs.write. Writes imply reads but grant no process or network IO. + +A write is an explicit edit requested by the caller. Read the current file and +review the intended change before writing; these functions do not decide which +files belong to a task. Patch is useful for a unique bounded change; write is +useful for an explicitly reviewed complete artifact. Neither creates parent +directories implicitly, and neither promises a transaction across multiple files. + +## read + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | UTF-8 source path under --fs-root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| source | text | Exact UTF-8 file contents without interpretation | + +Use `path` to read a source document before editing it. The returned text is +data: embedded bold, returns, imports and shell-looking content are not run. +A missing path, invalid UTF-8 or root escape produces the native filesystem +diagnostic. For binary data use lib/fs.read_bytes or read_chunk instead. + +After selecting the source we return *[Read the actual UTF-8 artifact](fs.read_text(path=`path`))*. + +## write + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Destination under --fs-root; parent must exist | +| source | text | required | Reviewed complete UTF-8 content, including intentional newlines | + +| 返回 | 类型 | 说明 | +|---|---|---| +| sha256 | text | SHA256 of the bytes actually written | + +Use `path` and `source` for an explicit authored artifact. JSON argument input +carries quotes, Unicode, literal dollar signs and newlines without generating +a program in another language. Existing files are replaced only because the +caller selected write. A single-file atomic replacement does not turn a batch +of writes into a transaction or erase unrelated work on failure. + +We **written = [Atomically replace this selected UTF-8 artifact](fs.atomic_write(path=`path`, text=`source`))**. +After writing, return *[Hash the actual resulting file](fs.file_hash(path=`path`))*. + +## patch + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Existing UTF-8 file under --fs-root | +| find | text | required | Exact nonempty fragment that occurs once | +| replace | text | required | Reviewed replacement fragment | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Native patch result; missing/ambiguous matches are diagnostics | + +Use `path`, `find` and `replace` when changing one known part of a file. +The exact-match requirement catches drift between reading and editing, though +it is not a concurrent kernel compare-and-swap. A whole-file replacement belongs +to write. This helper never falls back to a model-generated search-and-replace +program when the old fragment no longer matches. + +Once the bounded change is reviewed, return *[Apply one exact native text patch](fs.text_patch(path=`path`, find=`find`, replace=`replace`))*. + +## search + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | "." | Selected source directory under --fs-root | +| pattern | text | required | Unicode regex applied to each source line | +| glob | text | "**/*.mq.md" | File pattern; choose **/*.rs for runtime code | + +| 返回 | 类型 | 说明 | +|---|---|---| +| matches | list | Records with path, one-based line and original text | + +Use `path`=".", `pattern` and `glob`="**/*.mq.md" to search actual sources. +The native walker does not traverse symlinks and prunes generated/cache trees. +Reading remains UTF-8 and bounded by the filesystem implementation. Each result +retains its source path and line so an agent can read that artifact rather than +guessing from a detached snippet. This is a source query, not a code execution. + +`excluded` = + +| pattern | +|---| +| .git/** | +| **/target/** | +| **/node_modules/** | +| **/.marqdo/** | +| **/vendor/** | +| **/__pycache__/** | + +We **paths = [Find source files through the native filesystem](fs.find(path=`path`, pattern=`glob`, exclude=`excluded`))** and +**matches = [Start the source-location result list](table.empty_list())**. +- [Read each selected text source](for paths as file) + We **actual_path = path + "/" + file** and + **lines = [Read its UTF-8 lines](fs.read_lines(path=`actual_path`))** and **number = 0**. + - [Test the requested expression against each line](for lines as source) + We **number = number + 1** to retain one-based source coordinates. + 1. [This line matches the requested source query](re.is_match(text=`source`, pattern=`pattern`)) + + `hit` = + + | path | line | text | + |---|---|---| + | `actual_path` | `number` | `source` | + + We **matches = [Retain this source location](table.append(list=`matches`, item=`hit`))**. + +When the selected sources are exhausted we return *matches*. +## read_many + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| paths | list | required | Explicit UTF-8 source paths selected for one review batch | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Sources and hashes for the exact requested files | + +Use `paths` when reviewing a small related batch. Native filesystem reads +preserve the full UTF-8 text; hashes identify the exact returned source used to prepare a patch. The digest is +computed from that text, so a later filesystem change cannot pair new bytes with +an older source in the same record. +Reading does not run imports, main or embedded code. Choose a bounded batch so +the returned source remains useful to the agent rather than dumping a whole +repository into one response. Any missing or escaping path is a native error. +The same path/hash pair can be passed to apply for a preflight drift check. + +We **records = [Start the source review batch](table.empty_list())**. +- [Read only the selected artifacts](for paths as path) + We **source = [Read the exact UTF-8 source](fs.read_text(path=`path`))** and + **sha256 = [Identify the bytes used for this review](hash.sha256(text=`source`))**. + + + `record` = + + | path | source | sha256 | + |---|---|---| + | `path` | `source` | `sha256` | + + We **records = [Retain the source and its observed identity](table.append(list=`records`, item=`record`))**. +Return *records* after reading the selected batch. + +## inventory + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| paths | list | required | Explicit source paths to inspect without executing | +| include_body | bool | False | Include compiler AST debug evidence for a migration | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Source, hash and actual compiler analysis for each selected artifact | + +Use `paths` and `include_body`=False for an authored source review. +Marqdo reads each file through lib/fs, then sends its text to the compiler-backed +extension analyzer. The analyzer parses the same language, supplies real +parameters/defaults/contracts and measures each function's narrative ratio. +Imports are not executed or followed by this text inspection; full program checks +still use marqdo check. It needs fs.read and the engineering plugin, and makes no +network request or edit. A parse failure stays attached to that file as a Result +instead of making the rest of the inventory disappear. + +We **records = [Start the executable source inventory](table.empty_list())**. +- [Inspect the selected source with its actual compiler](for paths as path) + We **source = [Read the original source through the native filesystem](fs.read_text(path=`path`))** and + **sha256 = [Retain its observed byte identity](hash.sha256(text=`source`))** and + **analysis = [Parse contracts and statements without running them](engineering.analyze(source=`source`, include_body=`include_body`))**. + + `record` = + + | path | source | sha256 | analysis | + |---|---|---|---| + | `path` | `source` | `sha256` | `analysis` | + + We **records = [Keep the actual per-file evidence](table.append(list=`records`, item=`record`))**. +Return *records* after the requested source inventory. + +## apply + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| updates | list | required | Reviewed records containing path/source and optional expected_sha256 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result containing paths and SHA256 values actually written | + +Use `updates` to apply a reviewed batch through native file IO. Each record +selects its path and complete source; expected_sha256 optionally ties that edit +to the previously read version. All supplied digests and duplicate destinations +are checked before the first write, preventing an ordinary stale review from +partially changing the batch. Path access checks also happen before writing. + +This is still not a multi-file transaction or a kernel CAS. Each file replacement +is atomic on its own; a later disk failure can leave earlier reviewed files +written. Parent directories must already exist. A deliberate new file can omit +expected_sha256, while updating an observed file should retain its hash. +The result lists actual file hashes rather than claiming compliance with a style +rule. Call the static and behavioral checks after applying the batch. + +We **seen = [Start the destination preflight list](table.empty_list())**. +- [Preflight every reviewed destination before writing](for updates as update) + We **path = [Read the selected destination](access(update, "path"))** and + **exists = [Apply the native root policy before any write](fs.exists(path=`path`))** and + **expected = [Read its optional reviewed source identity](table.get(map=`update`, key="expected_sha256"))**. + 1. [This destination occurs twice](table.contains(list=`seen`, item=`path`)) + Return *[Reject duplicate writes in one batch](result.error(code="authoring.duplicate", message=`path`, operation="files.apply"))*. + 1. `expected` != None + 1. not `exists` + Return *[Keep a missing reviewed artifact visible](result.error(code="authoring.missing", message=`path`, operation="files.apply"))*. + 1. fs.file_hash(path=`path`) != `expected` + Return *[Refuse a stale reviewed update](result.error(code="authoring.changed", message=`path`, operation="files.apply"))*. + We **seen = [Retain this checked destination](table.append(list=`seen`, item=`path`))**. +We **written = [Start the actual write evidence list](table.empty_list())**. +- [Write each explicit reviewed artifact through Marqdo](for updates as update) + We **path = [Read its checked destination](access(update, "path"))** and + **saved = [Atomically replace the selected UTF-8 content](fs.atomic_write(path=`path`, text=access(update, "source")))** and + **sha256 = [Identify the bytes that were actually written](fs.file_hash(path=`path`))**. + + `evidence` = + + | path | sha256 | + |---|---| + | `path` | `sha256` | + + We **written = [Retain this actual file result](table.append(list=`written`, item=`evidence`))**. +Return *[The completed native edit batch](result.ok(value=`written`))*. + +## analyze_updates + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| updates | list | required | Proposed path/source records; no filesystem mutation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Compiler metadata for each proposed artifact | + +Use `updates` before applying an authored batch. Each proposal is analyzed +as text by the real compiler without replacing the current file or executing +the proposal. The path is an identity label for the report; no untrusted path +is opened here. Parameter order/defaults and statement projections allow a +reviewer to distinguish documentation changes from behavioral changes. + +The projection deliberately omits source locations and occlusion labels from +executable statements; it is review evidence, not a proof of all runtime behavior. +Keep real golden calls and backend tests for observable behavior. Parse failures +remain per-file Results so another proposal's valid syntax cannot mask them. + +We **reports = [Start the proposed-source review](table.empty_list())**. +- [Analyze one proposed artifact without writing it](for updates as update) + We **path = [Retain its intended destination label](access(update, "path"))** and + **source = [Read the proposed UTF-8 value](access(update, "source"))** and + **analysis = [Use the actual parser and contract checker](engineering.analyze(source=`source`))**. + + `report` = + + | path | analysis | + |---|---| + | `path` | `analysis` | + + We **reports = [Retain the actual compile evidence](table.append(list=`reports`, item=`report`))**. +Return *reports* after analyzing all proposals. + + +## _missing_contracts + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| functions | list | required | Compiler-projected function tree from engineering.analyze | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Executable functions whose return contract is missing | + +Use `functions` from the compiler projection; never infer functions by scanning +hash-prefixed source lines. Content-only headings have no executable statements +and are omitted, so a prose section does not acquire a fictional return table. +Nested functions are inspected recursively and retain compiler source lines. + +This is a pure structural check. The compiler separately checks declared +parameter names and types. A return table's presence is not proof that prose is +accurate or that an effectful function behaves correctly. Keep runtime tests for +those properties. The source tree is ordinary data and no imports are executed. + +We **missing = [Start the actual missing-contract findings](table.empty_list())**. +- [Inspect real callable units and their nested definitions](for functions as function) + We **contract = [Read its parsed public contract](access(function, "contract"))** and + **active = [Distinguish executable units from content-only headings](len(access(function, "semantic")) > 0)**. + We **missing_return = True** until an actual return contract is observed. + 1. `contract` != None + We **missing_return = [Inspect the existing contract without indexing None](access(contract, "returns") == None)**. + 1. `active` and `missing_return` + We **name = [Keep the exact callable name](access(function, "name"))** and **line = [Keep its source location](access(function, "line"))**. + + `finding` = + + | name | line | issue | + |---|---|---| + | `name` | `line` | "missing return contract" | + + We **missing = [Retain the source-based finding](table.append(list=`missing`, item=`finding`))**. + We **nested = [Inspect child definitions by the same rule](_missing_contracts(functions=access(function, "children")))** and + **missing = [Combine findings without executing a function](table.concat(a=`missing`, b=`nested`))**. +Return *missing* for the caller's report. + +## _active_lines + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| functions | list | required | Compiler-projected function tree | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Source heading lines belonging to executable units | + +Use `functions` from the compiler projection. An executable statement or a +declared parameter makes a unit part of the callable audit; a plain content +heading is not a zero-length program. This distinction also covers field-only +object schemas, which use field contracts rather than fictional return tables. + +The walk includes nested definitions and retains their actual heading lines. +It is a pure projection, not a source-text pattern or an import traversal. +An explicit return of None and an empty-payload assignment are still statements, +so intentionally unfinished callable code stays visible to the authoring checks. +The compiler's narrative measurements are used unchanged for every selected unit. + +We **lines = [Start the actual executable heading locations](table.empty_list())**. +- [Inspect real declarations and their nested definitions](for functions as function) + 1. len(access(`function`, "semantic")) > 0 or len(access(`function`, "params")) > 0 + We **lines = [Retain this executable source unit](table.append(list=`lines`, item=access(function, "line")))**. + We **nested = [Inspect nested source units by the same rule](_active_lines(functions=access(function, "children")))** and + **lines = [Keep the combined executable locations](table.concat(a=`lines`, b=`nested`))**. +Return *lines* for matching the unchanged narrative measurements. + +## audit + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| paths | list | required | Explicit maintained source paths; exclude intentional invalid fixtures | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with compact per-file parser, narrative and contract findings | + +Use `paths` for a selected maintained source batch. The same compiler that +runs Marqdo parses each source, checks declared contracts and measures narrative +per function. This task reads through the native filesystem and gives the plugin +only source text. It neither executes imports nor writes files. Requires +fs.read and plugin; it performs no network request. + +A ratio at or below one half is a finding, including a data-heavy callable. +Do not solve findings by adding repeated filler or inventing return values for +pure content. Reorganize large code/data into useful modules and explain actual +inputs, decisions and limits. This structural audit is an editing aid; run check +for dependency validation and real cases for behavioral and visual results. + +Pure content headings are excluded from callable ratios. Compiler warnings stay +in diagnostics for review; errors, parser failures and authoring gaps make the +batch incomplete. This allows a documented empty-payload demonstration to retain +its warning without replacing the example with fake business logic. + +The result retains all selected file findings even if one fails parsing. A +complete batch returns ok=true. An incomplete batch returns ok=false with the +same evidence in value, so --require-ok can stop automation without discarding +the review report. Missing files or root violations remain native diagnostics. +Newline-bearing paths have no special meaning here; they are ordinary input data. + +We **reports = [Start the compact source review](table.empty_list())** and **complete = True**. +- [Audit every explicitly selected source without running it](for paths as path) + We **source = [Read the source using native Marqdo IO](fs.read_text(path=`path`))** and + **analysis = [Use the actual compiler projection](engineering.analyze(source=`source`))** and + **parse_ok = [Retain whether parsing succeeded](access(analysis, "ok"))** and + **diagnostics = [Start this file diagnostic list](table.empty_list())** and + **ratio_gaps = [Start this file narrative findings](table.empty_list())** and + **missing_contracts = [Start this file contract findings](table.empty_list())**. + 1. `parse_ok` + We **data = [Read the successful source projection](access(analysis, "value"))** and + **diagnostics = [Retain genuine contract diagnostics](access(data, "diagnostics"))** and + **missing_contracts = [Inspect executable units recursively](_missing_contracts(functions=access(data, "functions")))**. + We **ratios = [Read the measured function units](access(data, "ratios"))** and **active_lines = [Identify actual executable units](_active_lines(functions=access(data, "functions")))**. + - [Review the narrative measure of each unit](for ratios as ratio) + We **line = [Read the measured source heading location](access(ratio, "line"))**. + 1. [This is an executable source unit](table.contains(list=`active_lines`, item=`line`)) and access(`ratio`, "ratio") <= 0.5 + We **ratio_gaps = [Retain this function and its actual measured ratio](table.append(list=`ratio_gaps`, item=`ratio`))**. + 1. not `parse_ok` + We **diagnostics = [Retain the real parser failure](table.append(list=`diagnostics`, item=access(analysis, "error")))**. + We **errors = 0** before examining the diagnostic severities. + - [Keep errors separate from expected illustrative warnings](for diagnostics as diagnostic) + We **severity = [Read a diagnostic severity when provided](table.get(map=`diagnostic`, key="severity"))**. + 1. `severity` == "error" + We **errors = errors + 1**. + We **ok = [Require all structural checks for this file](parse_ok and errors == 0 and len(ratio_gaps) == 0 and len(missing_contracts) == 0)**. + 1. not `ok` + We **complete = False** to retain the incomplete batch state. + + `report` = + + | path | ok | diagnostics | ratio_gaps | missing_contracts | + |---|---|---|---|---| + | `path` | `ok` | `diagnostics` | `ratio_gaps` | `missing_contracts` | + + We **reports = [Retain this file evidence without its full source dump](table.append(list=`reports`, item=`report`))**. +We **count = [Retain the actual number of selected sources](len(`paths`))**. + +`evidence` = + +| complete | count | reports | +|---|---|---| +| `complete` | `count` | `reports` | + +1. `complete` + Return *[The complete structural evidence](result.ok(value=`evidence`))*. +We **failed = [Retain the incomplete authoring result](result.error(code="authoring.incomplete", message="inspect the per-file findings in value", operation="files.audit"))**. +Return *[Keep the report available on failure](table.put(in=`failed`, at="value", value=`evidence`))*. + + +## excerpt + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | UTF-8 artifact under --fs-root | +| start | number | 1 | First one-based line to inspect | +| count | number | 40 | Number of lines, from 1 through 200 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | A record with total_lines and selected {line,text} records; each line is clipped to 2000 characters | + +Use `path`, `start`=1 and `count`=40 when a generated HTML line or a large source file would overflow the agent's output window. Line numbers refer to the original file, so the excerpt can guide a precise later read or patch. This is a bounded inspection view: clipping does not alter the file or turn a truncated excerpt into suitable replacement source. Start and count must be positive integral numbers; selection past the end returns no lines. The native reader still validates UTF-8 and the granted filesystem root. + +We **lines = [Read UTF-8 lines through the native filesystem](fs.read_lines(path=`path`))**. +1. `start` < 1 or `count` < 1 or `count` > 200 + Return *[Explain the supported inspection window](result.error(code="files.excerpt_window", message="start >= 1; count must be 1..200"))*. +We **selected = [Select only the requested line range](table.slice(list=`lines`, start=(`start` - 1), end=(`start` - 1 + `count`)))** and **records = [Start the source-location list](table.empty_list())**. +We **number = [Keep the original first line number](start)**. +- [Inspect each selected line](for selected as line) + We **visible = [Limit one generated line to 2000 characters](re.replace(text=`line`, pattern="(?s)\\A(.{0,2000}).*\\z", with="$1"))**. + + `record` = + + | line | text | + |---|---| + | `number` | `visible` | + + We **records = [Retain the original location and readable text](table.append(list=`records`, item=`record`))**. + We **number = [Advance the original line number](number + 1)**. +We **total = [Count the actual source lines](len(lines))**. + +`window` = + +| total_lines | lines | +|---|---| +| `total` | `records` | + +After selecting this window, return *window*. diff --git a/skills/marqdo-dev/index.mq.md b/skills/marqdo-dev/index.mq.md new file mode 100644 index 0000000..017fbdb --- /dev/null +++ b/skills/marqdo-dev/index.mq.md @@ -0,0 +1,225 @@ +--- +markup: occlusion +title: 以 Marqdo 本身开发和验证 Marqdo +import: + files: ./files.mq.md + browser_tools: ./browser.mq.md + fs: lib/fs.mq.md + repository: ./repository.mq.md + table: lib/table.mq.md + text: lib/text.mq.md + sys: lib/sys.mq.md + result: lib/result.mq.md + engineering: ext/engineering/index.mq.md +--- + +本目录是开发智能体的可执行手册。先阅读 [编程规范](../../doc/library-development.mq.md),再按具体任务调用本目录的函数。单文件标准库本身就是手册;只有多文件库或工程才需要 index.mq.md 组织入口。叙述应解释任务、数据、失败和限制,不能靠重复句子凑比例。 + +日常读写通过 files.mq.md 的 read、excerpt、write、patch、search、inventory 和 apply 完成。批量写入前可携带 expected_sha256,防止覆盖已经变化的源码。大段文本使用 CLI 的 --args-json 文件或标准输入传送;它保留换行、引号、中文和以美元符号开头的字面数据。不要为了搬运源码再生成 Python 或 shell 程序。 + +原生库能完成的计算和文件操作直接使用 lib。缺少可复用能力时新增拓展库;需要现有操作系统工具时使用 engineering.run 的参数数组。编排、条件、重试和结果判断留在 mq.md 中。process.exec 与 plugin 是真实的外部能力授权,fs-root 不能限制外部进程自己的权限。 + +调用示例:marqdo call skills/marqdo-dev/index.mq.md prepare_engineering --effects process.exec --fs-root . --json。读取文件可调用 files.mq.md read 并传入 path;修订现有文件优先使用 patch 或带哈希的 apply。每个真实函数标题下都应先给出参数和返回值表,然后是能够独立指导调用者的叙述。 + +## prepare_engineering + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result:构建工程插件,失败时保留 Cargo 输出 | + +第一次使用工程拓展前执行此任务。这里通过已有 sys.exec 引导 Cargo 构建本仓库的原生插件,之后开发和发布流程都可以使用同一份工程拓展。构建需要本机 Rust 工具链和已经可用的依赖缓存;不会安装 Python,也不修改版本或发布远端资源。 + +调用需要 process.exec。子进程退出不为零时返回失败,调用者应查看真实 stderr 并修复编译问题;成功只表示本机插件已构建,不意味着其他平台包已验证。依赖尚未缓存时应按仓库工具链配置获取依赖,再运行同一任务。 + +`args` = + +| argument | +|---| +| "build" | +| "-p" | +| "marqdo" | +| "-p" | +| "marqdo_plugin_engineering" | +| "--offline" | + +We **built = [构建已维护的工程边界插件](sys.exec(cmd="cargo", args=`args`, capture=True))**。 +1. access(`built`, "code") != 0 + 返回*[保留构建错误](result.error(code="dev.plugin_build", message=str(`built`), operation="prepare_engineering"))*。 +构建完成后返回*[真实 Cargo 证据](result.ok(value=`built`))*。 + +## check + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | 需要完整检查依赖的真实文件路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result:编译检查和逐函数叙述比例检查的进程证据 | + +使用 `path` 指定本次修改的入口或单文件库。从仓库根目录调用,并授权 plugin。检查器加载真实依赖,验证契约、参数与调用,同时要求函数的叙述比例超过一半。故意损坏的测试夹具和明确标记禁止修改的人工测试不应当被这项作者任务批量改写。 + +检查通过不能证明页面视觉效果、网络服务或发布凭据正确。根据变更运行实际用例:纯函数比较返回值,文件操作使用临时目录,外部发布操作使用隔离服务夹具。失败时先修复实际问题,保留诊断位置,不通过删除业务能力或补空话来消除告警。 + +`argv` = + +| argument | +|---| +| "target/debug/marqdo" | +| "check" | +| `path` | +| "--narrative-ratio" | + +We **checked = [检查真实文件及其可读性](engineering.run(argv=`argv`))**。 +检查结束后返回*[按实际退出状态保留通过或失败证据](engineering.check_exit(outcome=`checked`))*。 + +## audit + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| write_report | bool | False | 保存同一份真实报告到忽略目录 .marqdo/audit | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result:实际发现的维护源码与逐文件问题清单 | + +使用 `write_report`=False,在仓库根目录授权 plugin 和 fs.read,即可发现维护中的源码并逐个审查。文件枚举、读取和报告写入都由固有能力完成;分析使用真实编译器,不会运行被审查程序或其导入。需要保留证据时传 True 并增加 fs.write。 + +测试夹具、人工保护样例和历史兼容文件保留既有语义。占位演示的 warning 留在报告中供阅读,不伪造实现以消除提示。失败 Result 仍携带完整清单,因此可结合 --require-ok 阻止后续自动化;比例与契约通过后还应执行实际用例,不能把结构审查当成运行成功。 + +审查完成后返回*[实际仓库源码的完整观察结果](repository.audit(write_report=`write_report`))*。 + + +## test + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| targets | list | required | 明确选择的 Rust 集成测试目标名称 | +| filter | any | None | 可选测试名称过滤文本;不是 Cargo 命令选项 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result:真实 Cargo 退出状态、标准输出与错误输出 | + +使用 `targets` 和可选的 `filter`=None,在仓库根目录授权 plugin。目标清单转成逐个 --test 参数,Cargo 在离线模式下执行;这里不会安装依赖、调用 Python 或生成 shell 程序。需要先完成工具链与插件引导,测试使用的本地服务或其他依赖仍按各目标的实际要求准备。 + +传入的是测试目标名称和可选名称过滤器,不能用空目标清单或把命令选项伪装成过滤文本。构建错误、断言失败、超时与启动失败都返回失败结果;失败仍携带真实执行证据,便于定位哪个用例没有通过。成功只说明所选测试通过,不覆盖未运行的目标,更不能替代发布服务的实际状态验证。名称过滤只缩小用例集合;检查输出中的实际运行数量,避免过滤器没有命中却被当作完成验收。 + +这个入口把重复的测试命令收进源码手册。修改相关模块后运行对应目标,已通过后只有新改动、失败或未解决的疑问才扩大或重复检查。外部进程保留操作系统权限,--fs-root 不是 Cargo 子进程的沙箱。 + +1. len(`targets`) == 0 + Return *[要求明确的验收范围](result.error(code="dev.test_targets", message="select at least one integration test target", operation="test"))*. +1. `filter` != None + 1. [过滤器不能冒充 Cargo 选项](text.starts_with(text=`filter`, prefix="-")) + Return *[拒绝选项形式的过滤文本](result.error(code="dev.test_filter", message="filter is a test name, not an option", operation="test"))*. + +`argv` = + +| argument | +|---| +| "cargo" | +| "test" | +| "--offline" | + +- [将每个目标作为独立参数交给测试工具](for targets as target) + 1. [测试目标不能冒充命令选项](text.starts_with(text=`target`, prefix="-")) + Return *[保留错误目标的诊断](result.error(code="dev.test_targets", message=`target`, operation="test"))*. + We **argv = [增加明确的集成测试选择标记](table.append(list=`argv`, item="--test"))** and **argv = [增加原样传入的目标名称](table.append(list=`argv`, item=`target`))**. +1. `filter` != None + We **argv = [追加可选的用例名称过滤器](table.append(list=`argv`, item=`filter`))**. +We **checked = [执行实际离线构建与验收](engineering.run(argv=`argv`, timeout_ms=300000, max_output=2097152))**. +验收结束后返回*[按真实退出状态判断结果并保留输出](engineering.check_exit(outcome=`checked`))*。 + +## build_browser + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| out | text | ".marqdo/browser-handbook-assets" | Workspace output directory for current WASM and canonical bridge | +| compiler | any | None | Optional absolute rustc path from toolchain.rust_wasm_linux | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with native artifact hashes and the actual bounded build report path | + +Use `out`=".marqdo/browser-handbook-assets" and `compiler`=None from the checkout root. This task calls Marqdo's own wasm build operation through the explicit engineering process boundary, then hashes its real outputs with native filesystem tools. If the system compiler lacks a compatible WASM target, first call [the workspace toolchain task](toolchain.mq.md) and pass its returned compiler path. That override applies only to this child process, with no global environment or system installation change. + +Grant plugin, process.exec and fs.write. Native directory validation runs before the external build and keeps selected output under the granted root. Compiler logs are bounded and saved natively to .marqdo/build/browser.json; the CLI returns compact evidence so an oversized log does not hide the error. A failed Result remains failed for --require-ok and points to that report. Success includes the hashes of both generated files, not an assumption based on Cargo's exit code. Browser interaction and real HTTP mounting still need their own tests after this build. + +We **[Validate and create the selected native output directory](fs.make_dirs(path=`out`))** and **[Create the native build-report directory](fs.make_dirs(path=".marqdo/build"))** and **environment = None**. +1. `compiler` != None + We **environment = [Select this compiler for one child process](table.put(in=None, at="RUSTC", value=`compiler`))**. + +`argv` = + +| argument | +|---| +| "target/debug/marqdo" | +| wasm | +| build | +| "-o" | +| `out` | + +We **execution = [Build the current official browser artifact](engineering.run(argv=`argv`, env=`environment`, timeout_ms=300000, max_output=65536))** and **checked = [Retain actual build success or failure](engineering.check_exit(outcome=`execution`))**. +We **[Save bounded compiler evidence through native IO](fs.write_json(path=".marqdo/build/browser.json", value=`checked`))**. +1. not access(`checked`, "ok") + We **failed = [Keep this build incomplete](result.error(code="dev.browser_build", message="inspect .marqdo/build/browser.json", operation="build_browser"))**. + Return *failed*. +We **wasm = out + "/marqdo_wasm.wasm"** and **bridge = out + "/marqdo-bridge.js"** and **wasm_sha256 = [Hash the actual new WASM](fs.file_hash(path=`wasm`))** and **bridge_sha256 = [Hash the actual canonical bridge](fs.file_hash(path=`bridge`))**. + +`receipt` = + +| out | wasm_sha256 | bridge_sha256 | report | +|---|---|---|---| +| `out` | `wasm_sha256` | `bridge_sha256` | .marqdo/build/browser.json | + +Return *[Expose real browser build evidence](result.ok(value=`receipt`))*. + + +## prepare_browser + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | "1.65.0" | Pinned Playwright driver version | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result of workspace-local browser driver preparation | + +Use `version`="1.65.0" when preparing actual browser tests. The browser handbook keeps dependency installation and browser caches inside the workspace, using native directory operations and explicit existing npm/Playwright tools. Grant plugin, process.exec and fs.write. This prepares a driver only; call build_browser for current runtime artifacts and test_browser for actual behavior. No Python runner or global npm package is required. + +Return *[Prepare the pinned external browser capability](browser_tools.prepare(version=`version`))*. + + +## test_browser + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| out | text | ".marqdo/browser-handbook-assets" | Current native browser build output | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result from actual browser-effects, SPA, collaboration and bilingual network/complete-site browser tests | + +Use `out`=".marqdo/browser-handbook-assets" after prepare_browser and build_browser. The browser handbook stages the named runtime files with native IO, then supervises real callable servers and drives current WASM through the official bridge. The test result includes actual failures and is saved under .marqdo/browser-tests. Grant plugin, process.exec and fs.write; use --require-ok to stop a later task when a browser case fails. Constructed effects and source audit results remain separate evidence. + +Return *[Verify the actual callable sites in a real browser](browser_tools.verify(out=`out`))*. + + +## prepare_web + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result:当前 Go Web 插件构建的真实退出状态和日志 | + +先完成 prepare_engineering,再从仓库根调用并授权 plugin。既有构建脚本负责调用 Go/cgo 编译本仓库的原生 Web 实现,并把编译产物放到插件解析器使用的构建目录。需要本机 Go 与 C 编译工具链;这里不安装工具、不更改全局环境,也不选择新的发布版本。Windows 构建仍须具备脚本要求的 cgo 工具链,Linux 的通过不能替代 Windows 验证。 + +这个入口把常用插件准备动作保存在可执行手册中。工程边界为子进程传递本仓库的 Git 信任配置,避免 Go 的 VCS 检查因不同文件所有者失败;该配置不写入全局 Git 设置,也不关闭 VCS 来源记录。只有编译和编译产物处理外联维护中的构建工具;日常源码读写仍使用原生文件任务。缺少工具、编译错误或非零退出会保留实际日志并返回失败,不能继续把旧插件当成本轮实现。成功只证明当前平台的插件已构建,随后还需运行对应 HTTP 与浏览器用例。 + +`argv` = + +| argument | +|---| +| bash | +| scripts/build-web-plugin.sh | + +构建结束后返回 *[在保留来源记录的受控进程边界编译当前插件](engineering.checked(argv=`argv`, timeout_ms=300000, max_output=65536))*。 diff --git a/skills/marqdo-dev/repository.mq.md b/skills/marqdo-dev/repository.mq.md new file mode 100644 index 0000000..8cb4e4b --- /dev/null +++ b/skills/marqdo-dev/repository.mq.md @@ -0,0 +1,80 @@ +--- +markup: occlusion +title: Native audit of the maintained Marqdo repository +import: + files: ./files.mq.md + fs: lib/fs.mq.md + table: lib/table.mq.md + text: lib/text.mq.md +--- + +This repository task discovers the maintained source scope using native file +operations and passes it to the compiler-backed audit. It is an actual callable +workflow, not a generated inventory script. Read the development index for +bootstrap and the programming guide for how to resolve findings. + +Only lib, ext, public, examples, skills and doc are selected. Intentional invalid +tests and protected man-test programs are outside this scope. Historical +.compat.mq.md examples remain compatibility evidence. Compiler warnings on +documented placeholders stay in the report; they do not turn into fake logic. +A report records the current source state, not a promise that the task is done. + +## audit + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| write_report | bool | False | Also write the actual Result to .marqdo/audit/handbooks.json | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Actual repository source audit, with evidence retained on failure | + +Use `write_report`=False from the checkout root with plugin and fs.read. +Each selected directory is discovered natively; no Python, shell enumeration or +maintained list of hundreds of filenames is needed. Hidden staging trees, +dependency installs and build outputs are pruned. The historical compatibility +suffix is the only source-name exclusion within this maintained scope. + +The audit does not run found programs or load their imports. It reports source +parser/contract errors, missing callable return contracts and executable-unit +narrative gaps. Actual dependency checks, behavior, rendering and service +publication require their own workflow tests. An incomplete source report is +returned as a failed Result so --require-ok stops automation. + +Set write_report=True and grant fs.write to retain the same actual evidence +under the ignored audit directory. This intentionally replaces that generated +report; it never rewrites a program to silence a finding. A later audit reflects +later files, and a historical report does not establish compliance of new edits. +Missing selected directories retain a native error rather than silently narrowing +the task to make it appear complete. + +`directories` = + +| path | +|---| +| "lib" | +| "ext" | +| "public" | +| "examples" | +| "skills" | +| "doc" | + +`excluded` = + +| pattern | +|---| +| "**/.marqdo/**" | +| "**/node_modules/**" | +| "**/target/**" | + +We **paths = [Start the currently discovered source scope](table.empty_list())**. +- [Discover maintained modules through native file operations](for directories as directory) + We **names = [Discover actual Marqdo source files](fs.find(path=`directory`, pattern="**/*.mq.md", exclude=`excluded`))**. + - [Keep current sources while preserving historical compatibility examples](for names as relative) + 1. not [This file is an explicitly historical compatibility source](text.ends_with(text=`relative`, suffix=".compat.mq.md")) + We **path = directory + "/" + relative** and **paths = [Retain this actual maintained source](table.append(list=`paths`, item=`path`))**. +We **observed = [Audit the actual discovered sources without executing them](files.audit(paths=`paths`))**. +1. `write_report` + We **directory = [Prepare only the ignored generated audit directory](fs.make_dirs(path=".marqdo/audit"))** and + **saved = [Retain the same real success or failure evidence](fs.write_json(path=".marqdo/audit/handbooks.json", value=`observed`))**. +Return *observed* with all incomplete findings intact. diff --git a/skills/marqdo-dev/toolchain.mq.md b/skills/marqdo-dev/toolchain.mq.md new file mode 100644 index 0000000..6ab4b58 --- /dev/null +++ b/skills/marqdo-dev/toolchain.mq.md @@ -0,0 +1,134 @@ +--- +markup: occlusion +title: Workspace-only Rust toolchain for real WASM validation +import: + fs: lib/fs.mq.md + net: lib/net.mq.md + re: lib/re.mq.md + text: lib/text.mq.md + table: lib/table.mq.md + sys: lib/sys.mq.md + result: lib/result.mq.md + engineering: ext/engineering/index.mq.md +--- + +This development tool handles one concrete environment gap: a compatible Linux x86 compiler and WASM standard library. Native Marqdo handles files, HTTP, SHA256 and decisions; the existing tar executable handles the official xz archive format. Call rust_wasm_linux, then pass its compiler path as the child RUSTC for the ordinary Marqdo wasm build command. Other operating systems use their own supported toolchain setup. + +## rust_wasm_linux + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | "1.93.1" | Pinned stable Rust version for the isolated Linux x86 toolchain | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with compiler path, matching host/WASM standard libraries and native digest receipts | + +Use `version`="1.93.1" on Linux x86 when the current compiler has no compatible wasm32-unknown-unknown standard library. The task prepares a complete official compiler plus its matching host and WASM standard libraries in the reserved .marqdo/toolchain cache. A distribution compiler rebuilt from source can reject official precompiled metadata even when its visible release number is identical; installing only one target archive is therefore insufficient in that case. This task changes no system compiler, global environment, shell profile or Python setup. The returned compiler path can be passed as RUSTC in a single engineering process environment. + +Run from the checkout root with plugin, process.exec, fs.read, fs.write and network.read. Each download is bounded and verified against its official checksum before tar extracts a component. Failures preserve their real evidence and stop the remaining sequence. Repeating the task rechecks cached bytes rather than assuming an existing filename is valid. The final compiler probe must report the requested version before a manifest is written. The result proves toolchain preparation; a separate wasm build and browser test must still verify this repository's artifact. + +1. not [A stable numeric release](re.is_match(text=`version`, pattern="^[0-9]+[.][0-9]+[.][0-9]+$")) + Return *[Explain the required version shape](result.error(code="toolchain.version", message="use a stable numeric Rust release"))*. +We **directory = ".marqdo/toolchain/rust-linux-x86-" + version** and **receipts = [Start verified distribution receipts](table.empty_list())**. +We **[Create this task-owned workspace directory](fs.make_dirs(path=`directory`))**. + +`components` = + +| @ | component | target | +|---|---|---| +| 1 | rustc | x86_64-unknown-linux-gnu | +| 2 | rust-std | x86_64-unknown-linux-gnu | +| 3 | rust-std | wasm32-unknown-unknown | + +- [Prepare matching compiler and target components](for components as specification) + We **installed = [Download, verify and extract this exact component](_component(version=`version`, component=access(specification, "component"), target=access(specification, "target"), directory=`directory`))**. + 1. not access(`installed`, "ok") + Return *installed*. + We **receipts = [Retain its native digest receipt](table.append(list=`receipts`, item=access(installed, "value")))**. +We **compiler = sys.cwd() + "/" + directory + "/bin/rustc"** and **probed = [Verify the extracted compiler actually starts](engineering.checked(argv=table.append(list=table.append(list=table.empty_list(), item=`compiler`), item="--version"), timeout_ms=30000, max_output=32768))**. +1. not access(`probed`, "ok") + Return *probed*. +We **reported = [Read the actual compiler version](access(access(`probed`, "value"), "stdout"))**. +1. not [The requested release was installed](text.starts_with(text=`reported`, prefix=("rustc " + `version` + " "))) + Return *[Retain the unexpected compiler identity](result.error(code="toolchain.compiler", message=`reported`))*. + +`manifest` = + +| version | compiler | components | +|---|---|---| +| `version` | `compiler` | `receipts` | + +We **[Save the verified workspace toolchain receipt](fs.write_json(path=(directory + "/manifest.json"), value=`manifest`))**. +Return *[Expose the compiler for an explicit child environment](result.ok(value=`manifest`))*. + +## _component + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | Stable numeric Rust release | +| component | text | required | rustc or rust-std | +| target | text | required | x86_64-unknown-linux-gnu or wasm32-unknown-unknown | +| directory | text | required | Task-owned workspace toolchain directory | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with the verified component digest and extraction evidence | + +Use `version`, `component`, `target` and `directory` only for the fixed compiler/standard-library components selected by rust_wasm_linux. Source bytes and checksums come from the official Rust distribution over HTTPS. A cached archive is reused only after its current native SHA256 matches the fetched checksum. A truncated transfer or HTTP failure is preserved as a failed Result; extraction never runs on an unchecked archive. Downloading, hashing and directory creation use native Marqdo. Tar is the explicit system boundary for the xz distribution format, with an argument array rather than generated shell code. Extraction is restricted to this component's own archive subtree and the selected workspace directory. No Python interpreter or system installation directory participates. + +The extracted files retain their official executable modes, while --no-same-owner keeps archive ownership out of this workspace installation. The tar installer script is not executed. Component receipts identify the checked archive bytes; only the later compiler probe and repository build establish that those files work together. A failed extraction leaves the task-owned cache available for a verified retry. The caller's operating system still governs the external tar process, so this helper uses the fixed official component subtree rather than a caller-supplied archive member. + +1. not [A stable numeric release](re.is_match(text=`version`, pattern="^[0-9]+[.][0-9]+[.][0-9]+$")) + Return *[Reject an invalid release name](result.error(code="toolchain.version", message="stable numeric Rust release required"))*. +1. (`component` != "rustc" and `component` != "rust-std") or (`target` != "x86_64-unknown-linux-gnu" and `target` != "wasm32-unknown-unknown") or (`component` == "rustc" and `target` != "x86_64-unknown-linux-gnu") + Return *[Reject an unsupported component](result.error(code="toolchain.component", message="this task supports the Linux x86 compiler and its host/WASM standard libraries"))*. +We **package = component + "-" + version + "-" + target** and **url = "https://static.rust-lang.org/dist/" + package + ".tar.xz"** and **cache = directory + "/downloads"**. +We **[Create the native download cache](fs.make_dirs(path=`cache`))**. +We **archive = cache + "/" + package + ".tar.xz"** and **checksum = [Read the official bounded checksum](net.get(url=(url + ".sha256"), max_bytes=4096))**. +1. not access(`checksum`, "ok") + Return *checksum*. +We **body = [Read the checksum text](access(access(`checksum`, "value"), "body"))** and **expected = [Select its SHA256 field](table.first(list=text.str_split(s=text.str_trim(s=`body`), sep=" ")))**. +1. not [A complete SHA256 was returned](re.is_match(text=`expected`, pattern="^[a-f0-9]{64}$")) + Return *[Retain the invalid checksum response](result.error(code="toolchain.checksum", message="official checksum is not a SHA256 digest"))*. +We **ready = False** before inspecting this cache entry. +1. [The selected archive is already cached](fs.exists(path=`archive`)) + We **actual = [Hash its actual cached bytes](fs.file_hash(path=`archive`))** and **ready = actual == expected**. +1. not `ready` + We **downloaded = [Stream the official component into its cache path](net.download(url=`url`, path=`archive`, timeout_ms=120000, max_bytes=268435456))**. + 1. not access(`downloaded`, "ok") + Return *downloaded*. +We **actual = [Verify the bytes before extraction](fs.file_hash(path=`archive`))**. +1. `actual` != `expected` + Return *[Stop on a mismatching component](result.error(code="toolchain.digest", message="downloaded Rust component SHA256 differs from the official checksum"))*. +We **member = component**. +1. `component` == "rust-std" + We **member = "rust-std-" + target**. +We **subtree = [Select the verified component path](package + "/" + member)**. + +`argv` = + +| argument | +|---| +| tar | +| "--extract" | +| "--xz" | +| "--no-same-owner" | +| "--file" | +| `archive` | +| "--directory" | +| `directory` | +| "--strip-components=2" | +| `subtree` | + +We **extracted = [Extract only this verified distribution component](engineering.checked(argv=`argv`, timeout_ms=120000, max_output=32768))**. +1. not access(`extracted`, "ok") + Return *extracted*. + +`receipt` = + +| package | sha256 | +|---|---| +| `package` | `actual` | + +Return *[Retain the verified component identity](result.ok(value=`receipt`))*. diff --git a/skills/marqdo-release/SKILL.md b/skills/marqdo-release/SKILL.md new file mode 100644 index 0000000..a9948a9 --- /dev/null +++ b/skills/marqdo-release/SKILL.md @@ -0,0 +1,14 @@ +--- +name: marqdo-release +description: Prepare, publish and verify a user-authorized Marqdo full, cli or extension release through its executable mq.md handbook. Use for release versioning, immutable tags, matching CI gates, GitHub/R2 parity and Ubuntu PPA publication. +--- + +Read [the executable release entry](../marqdo-release/index.mq.md) and use its task routing. Version and mode come from the user; an already stated choice remains authorized. Inspection of an old release does not authorize republishing it. Never infer a new version, replace a tag, force-push or bypass hooks. + +Use `marqdo call` on the actual handbook headings. The repository development binary is `target/debug/marqdo`; prepare its engineering plugin through [the development entry](../marqdo-dev/index.mq.md). File reading and authoring use native [file tools](../marqdo-dev/files.mq.md). No Python release orchestrator is required. New OS/service capabilities belong at explicit plugin or external-tool boundaries; version decisions, retries and publication order remain readable mq.md. + +The entry preserves full/cli/ext deliverables, separate editor sources, clean-main tagging, bilingual authored notes, exact-commit Release and EK gates, both native platforms, GitHub/R2 identical bytes, VERSION-after-ZIP ordering and Ubuntu source/build/apt evidence. Every applicable obligation must be verified before declaring completion. Default full/cli work includes PPA; gh-pages deployment needs its own instruction. + +Read-only status and verification are separate from publication. Grant effects stated by each task. Inspect Result.ok before value; use --require-ok when an external automation must stop on a failed Result. Credentials stay in their existing private stores. Interactive sudo/GPG/dput or a failed service request remains incomplete: report the concrete failure and the exact handbook recovery call, preserving local evidence. + +Independent extension releases commit reviewed bilingual notes at doc/releases/ext-X.Y.Z.md before tagging. The [pack handbook](../../skills/marqdo-release/packs.mq.md) and extension-release.yml run native staging, both platform builds, exact-tag release creation and non-clobbering gh asset upload through marqdo call. An existing upload is inspected rather than replaced. Windows execution remains a CI obligation; a local Linux ZIP cannot prove it. diff --git a/skills/marqdo-release/_bridge.mq.md b/skills/marqdo-release/_bridge.mq.md new file mode 100644 index 0000000..ab45cac --- /dev/null +++ b/skills/marqdo-release/_bridge.mq.md @@ -0,0 +1,47 @@ +--- +markup: occlusion +title: Native release boundary +import: + engineering: ext/engineering/index.mq.md + result: lib/result.mq.md +--- + +The release handbook composes native Marqdo libraries and this narrow extension +boundary. Ordinary file reads/writes, version decisions, asset lists and state +checks stay in Marqdo. Authenticated service requests, bounded OS commands and +ZIP-format inspection use the engineering native plugin. No Python loader, +generated command program or duplicate release orchestrator is involved. + +A native plugin has the calling OS user's authority. Root is a working/artifact +location and cannot be described as an OS sandbox. These calls need plugin +effects; their public task contracts additionally declare any native filesystem, +network or environment operations they perform. Reading the handbook authorizes +none of its external publication steps. + +## request + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| operation | text | required | Native boundary operation selected by the task | +| payload | map | required | Structured arguments; never credentials | +| root | text | "." | Existing checkout/artifact root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Actual boundary Result; failed child exit stays failed | + +Use `operation`, `payload` and `root`="." for a documented external boundary. +The extension reports transport success separately from a child's exit code. +Release commands require code zero and no timeout, so convert a completed but +failed child into a release failure before another phase can continue. Stdout +and stderr retain bounded diagnostic evidence with known credentials redacted. +Other operations preserve their own Result without manufacturing success. + +We **answer = [Invoke the maintained native engineering boundary](engineering.request(operation=`operation`, payload=`payload`, root=`root`))**. +1. not access(`answer`, "ok") + Return *answer* with its original error. +1. `operation` == "command" + We **execution = [Read the bounded child result](access(answer, "value"))**. + 1. access(`execution`, "code") != 0 or access(`execution`, "timed_out") + Return *[Keep the unsuccessful child visible](result.error(code="release.command_failed", message=str(`execution`), operation="command"))*. +Return *answer* when this requested boundary completed successfully. diff --git a/skills/marqdo-release/asset_io.mq.md b/skills/marqdo-release/asset_io.mq.md new file mode 100644 index 0000000..1c488ad --- /dev/null +++ b/skills/marqdo-release/asset_io.mq.md @@ -0,0 +1,228 @@ +--- +markup: occlusion +title: Native artifact IO for the release handbook +import: + engineering: ext/engineering/index.mq.md + fs: lib/fs.mq.md + net: lib/net.mq.md + table: lib/table.mq.md + result: lib/result.mq.md + text: lib/text.mq.md + re: lib/re.mq.md + uuid: lib/uuid.mq.md + sys: lib/sys.mq.md +--- + +These functions are the concrete IO used by assets.mq.md. Native Marqdo libraries read, hash, download, stage and clean files. The extension handles authenticated R2 writes and ZIP-format inspection. Source identity, release completeness and publication ordering remain visible Marqdo dataflow. + +## verify + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| asset | map | required | Exact GitHub asset record including size and digest | +| path | text | required | Local file selected inside the granted filesystem root | +| root | text | "." | Checkout root matching --fs-root; relative to the granted runtime cwd | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with native hash evidence and validated archive metadata | + +Use `asset`, `path` and `root`="." to verify local bytes before publication. +Size and SHA256 come from lib/fs; a GitHub digest, when supplied, must match. +The native engineering extension inspects only the ZIP/VSIX format and CRCs. +Ordinary file facts stay in Marqdo instead of an external script. A mismatched +length or hash remains a failed Result and cannot advance the CDN pointer. + +The format layer rejects escaping entries, duplicate names, symlinks and excessive +expansion. It does not extract or execute a CLI. Source pack version, native file +roles and VSIX version are checked by assets.content after this byte-level stage. +This function requires fs.read and plugin; executable-only assets use the same +size/hash checks without pretending they contain an archive. + +We **information = [Read the native file information](fs.stat(path=`path`))** and +**size = [Read its actual byte count](access(information, "size"))** and +**sha256 = [Hash the actual file through the native filesystem](fs.file_hash(path=`path`))** and +**expected = [Read GitHub's optional digest metadata](table.get(map=`asset`, key="digest"))** and +**name = [Retain the asset's exact filename](access(asset, "name"))**. +1. `size` != access(`asset`, "size") or (`expected` != None and `expected` != "sha256:" + `sha256`) + Return *[Reject bytes that differ from GitHub metadata](result.error(code="release.asset_digest", message=`name`, operation="asset_io.verify"))*. + +`record` = + +| name | size | sha256 | +|---|---|---| +| `name` | `size` | `sha256` | + +1. [This asset is an archive format](text.ends_with(text=`name`, suffix=".zip") or text.ends_with(text=`name`, suffix=".vsix")) + We **archive = [Inspect ZIP entries and their CRCs without extraction](engineering.inspect_zip(path=`path`, root=`root`))**. + 1. not access(`archive`, "ok") + Return *archive* with the actual format error. + We **record = [Retain the inspected format evidence](table.merge(a=`record`, b=access(archive, "value")))**. +Return *[The verified local byte identity](result.ok(value=`record`))*. + +## fetch + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| asset | map | required | GitHub asset record chosen by the release catalog | +| directory | text | required | Release-specific destination under --fs-root | +| root | text | "." | Checkout root matching --fs-root; relative to the granted runtime cwd | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with a reused or freshly downloaded verified local artifact | + +Use `asset`, `directory` and `root`="." after assets.catalog has checked all +required filenames. A local file is reused only after its size, hash and archive +format are verified again. Otherwise native net.download streams into an atomic +replacement under the granted filesystem root. Failed HTTP transfers do not +replace an existing destination. The proxy route is tried before the original +GitHub asset URL; explicit fixture URLs remain visible in test metadata. + +Downloads have a 64 MiB per-file limit and a 90-second request timeout here. +These limits cover the current release matrix; a larger future artifact needs +a deliberate documented limit change. No credential is put into a URL or native +download header. Role-specific contents are checked by the calling task. + +We **name = [Read the exact catalog filename](access(asset, "name"))** and +**path = directory + "/" + name** and **prepared = [Create the explicit staging directory](fs.make_dirs(path=`directory`))**. +1. [A local candidate already exists](fs.exists(path=`path`)) + We **existing = [Recheck its actual byte identity](verify(asset=`asset`, path=`path`, root=`root`))**. + 1. access(`existing`, "ok") + Return *existing* without downloading it again. +We **original = [Read the selected asset's original URL](access(asset, "browser_download_url"))** and +**proxy = [Select the documented GitHub mirror](text.replace(text=`original`, old="https://github.com/", new="https://proxy.cflmy.top/github.com/"))**. + +`urls` = + +| url | +|---| +| `proxy` | +| `original` | + +We **headers = [Identify this public verification download](table.put(in=None, at="User-Agent", value="marqdo-engineering"))**. + +We **last = [Start with no completed transfer](result.error(code="release.download", message=`name`, operation="asset_io.fetch"))**. +- [Try the bounded public download routes](for urls as url) + We **downloaded = [Stream the official artifact through native IO](net.download(url=`url`, path=`path`, headers=`headers`, timeout_ms=90000, max_bytes=67108864))**. + 1. access(`downloaded`, "ok") + We **last = [Check the downloaded bytes and archive format](verify(asset=`asset`, path=`path`, root=`root`))**. + 1. access(`last`, "ok") + Return *last* with its real evidence. + 2. * + We **last = downloaded** to preserve the last transport failure. +Return *last* when neither route produced a verified artifact. + +## cdn + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Versioned or latest VERSION/pack path from the release model | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result containing public pointer text or native download hash | + +Use `path` only for a modeled CDN object. The public base is ext.marqdo.com +unless an explicit fixture override is configured. VERSION is read as UTF-8; +binary packs use native net.download, fs.file_hash and native cleanup in a +UUID-named directory under .marqdo/release-check. No Python body reader or local +file writer participates. A handled network failure cleans its owned directory. + +A successful HTTP request proves only that URL's bytes; the caller compares the +hash with GitHub and decides whether the release is complete. Edge-cache delay +remains visible. Unexpected filesystem diagnostics may leave the uniquely owned +staging directory for inspection; no unrelated directory is removed. +This task needs network.read, fs.write, environment.read and random.read. + +We **valid = [Accept only modeled public artifact paths](re.is_match(text=`path`, pattern="^(latest|v[0-9]+\\.[0-9]+\\.[0-9]+)/(VERSION|marqdo-[A-Za-z0-9._-]+\\.zip)$"))**. +1. not `valid` + Return *[Reject an arbitrary CDN cache path](result.error(code="release.cdn_path", message="expected a modeled release path", operation="asset_io.cdn"))*. +We **base = [Read the explicit fixture override if configured](sys.env_get(name="MARQDO_RELEASE_CDN"))**. +1. `base` == None + We **base = "https://ext.marqdo.com"** for normal public verification. +We **url = base + "/" + path**. + +We **headers = [Identify this public verification download](table.put(in=None, at="User-Agent", value="marqdo-engineering"))**. + +1. [This object is a version pointer](text.ends_with(text=`path`, suffix="/VERSION")) + We **read = [Read the public UTF-8 version pointer](net.get(url=`url`, headers=`headers`, timeout_ms=30000))**. + 1. not access(`read`, "ok") + Return *read* with its actual network error. + We **response = [Read the HTTP result](access(read, "value"))**. + 1. access(`response`, "status") != 200 + Return *[Keep the public pointer HTTP failure](result.error(code="release.cdn_http", message=str(access(response, "status")), operation="asset_io.cdn"))*. + We **version = [Trim only the pointer's outer whitespace](text.str_trim(s=access(response, "body")))**. + + We **pointer = [Keep the version as one named result field](table.put(in=None, at="version", value=`version`))**. + + Return *[The actual public version pointer](result.ok(value=`pointer`))*. +We **parent = [Prepare the ignored verification area](fs.make_dirs(path=".marqdo/release-check"))** and +**identifier = [Choose an independent staging identity](uuid.v4())** and **directory = ".marqdo/release-check/" + identifier** and +**created = [Reserve this verification directory](fs.make_dir(path=`directory`))** and **destination = directory + "/artifact.zip"**. +We **downloaded = [Stream public bytes into this owned native stage](net.download(url=`url`, path=`destination`, headers=`headers`, timeout_ms=90000, max_bytes=67108864))**. +1. not access(`downloaded`, "ok") + We **removed = [Clean only this failed request's owned stage](fs.remove_tree(path=`directory`))**. + Return *downloaded* with its real transport failure. +We **sha256 = [Hash the actual public bytes](fs.file_hash(path=`destination`))** and +**information = [Read the downloaded file information](fs.stat(path=`destination`))** and +**size = [Read their actual byte count](access(information, "size"))** and +**removed = [Remove this completed request's owned stage](fs.remove_tree(path=`directory`))**. + +`evidence` = + +| size | sha256 | +|---|---| +| `size` | `sha256` | + +Return *[The measured public object identity](result.ok(value=`evidence`))*. + +## upload + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | Stable X.Y.Z explicitly chosen by the user | +| files | list | required | Exactly three verified path/name/sha256 records | +| root | text | "." | Checkout root matching --fs-root; relative to the granted runtime cwd | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result containing the actual R2 write evidence | + +Use `version`, `files` and `root`="." only for the release already authorized +by the user. The caller has checked all three source/native files against +GitHub before this operation begins. Marqdo controls the write order explicitly: +versioned and latest pack objects first, both VERSION pointers last. Private R2 +signing is the only native service boundary. No whole-directory sweep occurs. + +An interrupted upload keeps the old pointer until every required pack has +succeeded. Existing older versions are never deleted. The tool returns an error +on the first failed write and preserves already-written object evidence through +the service itself; it does not call a partial batch complete. Public byte-parity +checks still follow in assets.status. + +We **count = [Require the source pack and both platform packs](len(`files`))**. +1. `count` != 3 + Return *[Reject an incomplete CDN upload set](result.error(code="release.cdn_files", message="exactly three verified packs are required", operation="asset_io.upload"))*. + +`prefixes` = + +| prefix | +|---| +| "v`version`" | +| latest | + +We **written = [Start the service write evidence](table.empty_list())**. +- [Write both public pack namespaces before pointers](for prefixes as prefix) + - [Upload only the preverified pack set](for files as file) + We **key = prefix + "/" + access(file, "name")** and + **uploaded = [Sign and upload the exact checked local bytes](engineering.put_file(path=access(file, "path"), key=`key`, sha256=access(file, "sha256"), root=`root`))**. + 1. not access(`uploaded`, "ok") + Return *uploaded* before changing any VERSION pointer. + We **written = [Retain the completed object identity](table.append(list=`written`, item=access(uploaded, "value")))**. +- [Advance pointers only after all six pack writes succeeded](for prefixes as prefix) + We **uploaded = [Write the explicit version pointer](engineering.put_text(key=`prefix` + "/VERSION", text=`version` + "\n", root=`root`))**. + 1. not access(`uploaded`, "ok") + Return *uploaded* with the actual pointer failure. + We **written = [Retain this pointer write](table.append(list=`written`, item=access(uploaded, "value")))**. +Return *[All completed service writes](result.ok(value=`written`))*. diff --git a/skills/marqdo-release/assets.mq.md b/skills/marqdo-release/assets.mq.md new file mode 100644 index 0000000..8c45f66 --- /dev/null +++ b/skills/marqdo-release/assets.mq.md @@ -0,0 +1,590 @@ +--- +markup: occlusion +title: Release assets: bytes, contents and CDN parity +import: + bridge: ./_bridge.mq.md + native: ./asset_io.mq.md + github: ./github.mq.md + model: ./model.mq.md + result: lib/result.mq.md + table: lib/table.mq.md + text: lib/text.mq.md + json: lib/json.mq.md + toml: lib/toml.mq.md +--- + +Artifacts have a lifecycle: discover the exact GitHub metadata, download to a +release-specific directory, verify bytes and package role, publish only the +three extension packs, then compare every public copy. Full mode requires ten +GitHub assets; Linux CLI and Linux native packages are separate obligations. + +The local staging directory is dist/release-X.Y.Z by default. Downloads use +atomic .partial replacement and bounded retries. Verification reads ZIP entries +without extraction. Existing verified files are reusable; a failed operation +never changes an old tag or treats an incomplete upload as completion. + +Read-only public checks and local downloads use plugin,fs.write,network.read,environment.read because the checked-in +native transport owns those service and filesystem operations. Publishing is an +explicit external mutation authorized by a release request. Credentials remain +in existing environment or ~/.marqdo/r2.env stores and are not call arguments. + +```sh +marqdo call skills/marqdo-release/assets.mq.md download 'version="2.6.0"' --effects plugin,fs.write,network.read,environment.read --fs-root . --json +marqdo call skills/marqdo-release/assets.mq.md status 'version="2.6.0"' --effects plugin,fs.write,network.read,environment.read --fs-root . --json +``` + +These commands inspect the existing release; they do not republish it. Use +publish only for the version and mode actually authorized. On missing keys, +configure the documented local credential store and call publish again. Never +put credentials in a parameter, notes file, source tree or session binding. + +## named + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| assets | list | required | GitHub asset records from one exact release | +| name | text | required | Exact filename to look up | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Matching asset record or None | + +Use `assets` and `name` to find one exact release artifact. Prefix matches +are insufficient because source packs, CLI bundles and native packs serve +different roles. This pure helper preserves the GitHub-provided size, digest and +download URL together. It neither creates an asset nor substitutes a file from +a previous release. None means the caller must keep the release incomplete, +even if other files are already downloadable. + +- [Find the exact filename in this release](for assets as asset) + 1. access(`asset`, "name") == `name` + Return *asset* with its original metadata. +Return *None* when no asset has that exact name. + +## catalog + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | Stable X.Y.Z explicitly chosen by the user | +| mode | text | "full" | full, cli or ext; determines the deliverable contract | +| root | text | "." | Checkout directory; pass --fs-root . from its root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result containing the accepted plan and complete GitHub asset records | + +Use `version`, `mode`="full" and `root`="." before downloading or publishing. +All required names are checked first, so an incomplete release cannot partially +advance the CDN pointer. Extra GitHub assets are allowed; they do not replace +any required filename. A missing release and a missing platform pack have +separate error codes. Only metadata is fetched here; no local archive is trusted +merely because it has the right filename. Content and digest checks occur next. +For ext mode the same rule requires source, Windows native and Linux native packs. + +We **planned = [Read the exact deliverable contract](model.plan(version=`version`, mode=`mode`))**. +1. not access(`planned`, "ok") + Return *planned* with its failure intact. + +We **published = [Read this tag's actual GitHub assets](github.release(version=`version`, mode=`mode`, root=`root`))**. +1. not access(`published`, "ok") + Return *published* with its failure intact. + +We **release_data = [Read published metadata or None](access(published, "value"))**. +1. `release_data` == None + Return *[Keep a missing release visible](result.error(code="release.missing", message="GitHub release is not published", operation="assets.catalog"))*. +We **plan_data = [Keep the validated mode and names](access(planned, "value"))** and +**assets = [Read GitHub asset records](access(release_data, "assets"))** and +**required = [Read the required filenames](access(plan_data, "required"))**. +- [Require every declared deliverable before continuing](for required as name) + We **asset = [Find this exact artifact](named(assets=`assets`, name=`name`))**. + 1. `asset` == None + Return *[Report the missing deliverable](result.error(code="release.asset_missing", message=`name`, operation="assets.catalog"))*. + +`catalog_data` = + +| plan | release | assets | +|---|---|---| +| `plan_data` | `release_data` | `assets` | + +Return *[The complete metadata catalog](result.ok(value=`catalog_data`))*. + +## bundle_content + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| entries | list | required | Validated archive entry names | +| platform | text | required | windows or linux, chosen from the catalog filename | +| name | text | required | Exact bundle filename retained in errors | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result confirming CLI, readable libraries and every embedded native plugin | + +Use `entries`, `platform` and `name` for an already CRC-checked CLI bundle. +A standalone executable has a different role: the bundle must also carry its +readable standard and extension sources. This task requires the interpreter, +file/table libraries, extension version, web/quantum handbooks and all baseline +native libraries. When engineering sources are present, its native library is +required in the same bundle. + +Platform names are explicit data. Windows uses marqdo.exe and DLL names, Linux +uses marqdo and lib-prefixed shared objects. A missing library cannot be excused +by success on the other platform. Archive paths use their portable forward-slash +representation; no extraction or ABI execution happens in this pure layer. + +Hash/size/CRC identity comes from the earlier byte check, and the correct-commit +CI gate proves the platform build. This function verifies packaging coherence, +not scientific correctness, loader ABI compatibility or a machine's installed +system dependencies. Its successful Result means every listed bundle obligation +was observed in these actual entry names. + +We **binary = "marqdo"** and **prefix = "lib"** and **suffix = ".so"** for Linux. +1. `platform` == "windows" + We **binary = "marqdo.exe"** and **prefix = ""** and **suffix = ".dll"**. +2. `platform` != "linux" + Return *[Reject an unknown bundle platform](result.error(code="release.platform", message=`platform`, operation="bundle_content"))*. + +`required` = + +| entry | +|---| +| `binary` | +| "lib/fs.mq.md" | +| "lib/table.mq.md" | +| "ext/VERSION" | +| "ext/web/index.mq.md" | +| "ext/quantum/index.mq.md" | + +`plugins` = + +| plugin | +|---| +| "agent" | +| "linalg" | +| "llm" | +| "quantum" | +| "web" | + +1. [This bundle includes engineering sources](table.contains(list=`entries`, item="ext/engineering/index.mq.md")) + We **plugins = [Require the same new native capability](table.append(list=`plugins`, item="engineering"))**. +- [Add each embedded native dependency](for plugins as plugin) + We **required = [Retain the platform-specific native path](table.append(list=`required`, item="ext/native/" + prefix + plugin + suffix))**. +- [Check each actual bundle obligation](for required as entry) + 1. not [The bundle contains this required file](table.contains(list=`entries`, item=`entry`)) + Return *[Retain the missing packaging entry](result.error(code="release.bundle_content", message=`name` + ": " + `entry`, operation="bundle_content"))*. +Return *[The actual packaging checks passed](result.ok(value=True))*. + + +## matrix + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| records | list | required | Complete catalog-selected records after individual size/digest/role checks | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result retaining records only when declared engineering sources have both native platforms | + +Use `records` after individual content checks on the complete release set. +The source pack declares which extension sources it actually ships. If it contains +engineering/index.mq.md, both native packs must contain that capability too. +A new source pack combined with older native packs would otherwise pass separate +filename checks and fail only when an agent tries to load its new tool. + +This check follows package contents rather than guessing a version threshold. +Historical packs without engineering sources retain their original five-plugin +contract. CLI bundles are checked independently by bundle_content, including +their embedded source/native correspondence. The release model and catalog still +own the complete filename matrix for full/cli/ext; this helper does not turn an +arbitrary partial list into proof of an entire release. + +The function is pure. It neither downloads, extracts nor executes an archive. +Missing new native capability remains a failed Result before publication, and +a successful result preserves all previously verified records for summarization. + +We **engineering = False** and **windows = False** and **linux = False** before inspecting the declared source footprint. +- [Read capability declarations from the source pack](for records as record) + We **name = [Read this verified filename](access(record, "name"))**. + 1. [This is the extension source pack](text.ends_with(text=`name`, suffix="-ext.zip")) + We **engineering = [Observe whether engineering sources actually ship](table.contains(list=access(record, "entries"), item="ext/engineering/index.mq.md"))**. +1. not `engineering` + Return *[Keep the historical source/native contract](result.ok(value=`records`))*. +- [Require new capability on each native platform](for records as record) + We **name = [Read this native candidate's filename](access(record, "name"))** and **required = None**. + 1. [This is the Windows native pack](text.ends_with(text=`name`, suffix="-native-x86_64-pc-windows-msvc.zip")) + We **windows = True** and **required = "native/engineering.dll"**. + 1. [This is the Linux native pack](text.ends_with(text=`name`, suffix="-native-x86_64-unknown-linux-gnu.zip")) + We **linux = True** and **required = "native/libengineering.so"**. + 1. `required` != None + 1. not [This platform contains its declared engineering library](table.contains(list=access(`record`, "entries"), item=`required`)) + Return *[Reject source/native capability drift](result.error(code="release.native_capability", message=`name`, operation="assets.matrix"))*. +1. not `windows` or not `linux` + Return *[Require both native platforms](result.error(code="release.native_platform", message="engineering sources require Windows and Linux native packs", operation="assets.matrix"))*. +Return *[The consistent source/native records](result.ok(value=`records`))*. + + +## summaries + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| records | list | required | Verified records retained after matrix checks | +| directory | text | required | Actual local staging directory | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Compact name/path/size/SHA256/entry-count evidence rows | + +Use `records` and `directory` after verification, not as a replacement for it. +An archive can contain thousands of source paths. Returning every path and full +package metadata at the end of a release obscures the handful of facts an agent +needs to act: exact local path, byte length, digest and entry count. + +This pure projection keeps those observed facts in one row per artifact. +It does not invent a verified flag, rehash a file or silently discard an earlier +failure. Executable-only files have zero archive entries. Detailed inspection +remains available from asset_io.verify and engineering.inspect_zip when needed. +The reduced final evidence is also suitable for saving through native fs.write_json, +without requiring another language to parse command output or reconstruct a report. + +We **rows = [Start concise artifact evidence](table.empty_list())**. +- [Project already-checked artifacts into readable rows](for records as record) + We **name = [Keep the exact filename](access(record, "name"))** and **size = [Keep the measured size](access(record, "size"))** and **sha256 = [Keep the measured digest](access(record, "sha256"))** and **entries = [Read optional archive details](table.get(map=`record`, key="entries"))** and **entry_count = 0** and **path = directory + "/" + name**. + 1. `entries` != None + We **entry_count = [Count the inspected entries](len(entries))**. + + `row` = + + | name | path | size | sha256 | entry_count | + |---|---|---|---|---| + | `name` | `path` | `size` | `sha256` | `entry_count` | + + We **rows = [Retain this measured artifact](table.append(list=`rows`, item=`row`))**. +Return *rows* after projecting each verified record. + + +## content + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| record | map | required | Verified archive record produced by the byte transport | +| version | text | required | Stable X.Y.Z explicitly chosen by the user | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result retaining archive evidence after role-specific content checks | + +Use `record` and `version` after a SHA256/size/CRC check. This second layer +checks useful contents: extension sources identify their pack version; native +packs retain their baseline plugins and source-declared new capabilities; bundles include the embedded-library +sources and a CLI; VSIX metadata declares its editor version; the source archive +contains the tagged Cargo version. These checks complement CI and do not claim +to prove ABI compatibility or scientific correctness of every plugin. +An executable-only asset has no ZIP entries and relies on its GitHub digest and +build evidence. A source pack without either handbook entry is unusable for the +document-first workflow even when it decompresses correctly. Native filenames +are checked individually because one missing shared library would otherwise +surface only after installation, far from the publication step that caused it. No archive is extracted or executed while reading its metadata. + +Version text is trimmed for comparison, so Windows CRLF and Unix LF identify +the same declared version without changing any archive bytes. SHA256 still +covers the original byte sequence. A source snapshot is checked through its +actual TOML package.version field; a matching dependency version cannot satisfy +that role. Missing metadata remains a failure rather than a guessed version. + +We **name = [Read the verified filename](access(record, "name"))**. +1. [This is an executable-only asset](text.ends_with(text=`name`, suffix=".exe")) + Return *[Retain its verified digest evidence](result.ok(value=`record`))*. +We **entries = [Read the archive entry list](access(record, "entries"))** and +**metadata = [Read bounded metadata files](access(record, "metadata"))** and +**required = [Start the role-specific entry list](table.empty_list())**. +1. [This is the source extension pack](text.ends_with(text=`name`, suffix="-ext.zip")) + + `required` = + + | entry | + |---| + | ext/VERSION | + | ext/quantum/index.mq.md | + | ext/web/index.mq.md | + + We **declared = [Read the pack version without assuming platform newlines](table.get(map=`metadata`, key="ext/VERSION"))**. + 1. `declared` == None + Return *[Report missing version metadata](result.error(code="release.pack_version", message=`name`, operation="assets.content"))*. + We **pack_version = [Normalize the source pack version field](text.str_trim(s=`declared`))**. + 1. `pack_version` != `version` + Return *[Reject a mismatched source pack version](result.error(code="release.pack_version", message=`name`, operation="assets.content"))*. +1. [This is a Linux native pack](text.contains(text=`name`, sub="-native-x86_64-unknown-linux-gnu")) + + `required` = + + | entry | + |---| + | native/libagent.so | + | native/liblinalg.so | + | native/libllm.so | + | native/libquantum.so | + | native/libweb.so | + +1. [This is a Windows native pack](text.contains(text=`name`, sub="-native-x86_64-pc-windows-msvc")) + + `required` = + + | entry | + |---| + | native/agent.dll | + | native/linalg.dll | + | native/llm.dll | + | native/quantum.dll | + | native/web.dll | + +1. [This is the standard-library source pack](text.ends_with(text=`name`, suffix="-stdlib.zip")) + + `required` = + + | entry | + |---| + | lib/fs.mq.md | + | lib/table.mq.md | + | lib/文件.mq.md | + +1. [This is the offline documentation pack](text.ends_with(text=`name`, suffix="-public.zip")) + We **required = [Require the documentation entry](table.append(list=`required`, item="index.html"))**. +1. [This is the tagged source snapshot](text.ends_with(text=`name`, suffix="-source.zip")) + We **cargo_source = [Read the selected manifest metadata](table.get(map=`metadata`, key="Cargo.toml"))**. + 1. `cargo_source` == None + Return *[Report missing source manifest](result.error(code="release.source_metadata", message=`name`, operation="assets.content"))*. + We **manifest = [Parse the actual source package declaration](toml.parse(text=`cargo_source`))** and **package_version = [Read the package version](access(access(manifest, "package"), "version"))**. + 1. `package_version` != `version` + Return *[Reject a source snapshot from another version](result.error(code="release.source_version", message=`name`, operation="assets.content"))*. +1. [This is the editor extension](text.ends_with(text=`name`, suffix=".vsix")) + We **package = [Decode the VSIX package metadata](json.parse(text=access(metadata, "extension/package.json")))**. + 1. access(`package`, "version") != `version` + Return *[Reject a mismatched VSIX version](result.error(code="release.vsix_version", message=`name`, operation="assets.content"))*. +- [Check every entry required by this role](for required as entry) + 1. not [The entry is present](table.contains(list=`entries`, item=`entry`)) + Return *[Report missing archive content](result.error(code="release.archive_content", message=`name` + ": " + entry, operation="assets.content"))*. +1. not [This is a standalone native pack](text.contains(text=`name`, sub="-native-")) + We **platform = None**. + 1. [This is a Windows CLI bundle](text.ends_with(text=`name`, suffix="-x86_64-pc-windows-msvc.zip")) + We **platform = "windows"**. + 1. [This is a Linux CLI bundle](text.ends_with(text=`name`, suffix="-x86_64-unknown-linux-gnu.zip")) + We **platform = "linux"**. + 1. `platform` != None + We **checked = [Verify the embedded source/native bundle](bundle_content(entries=`entries`, platform=`platform`, name=`name`))**. + 1. not access(`checked`, "ok") + Return *checked*. +Return *[Keep the verified digest and content evidence](result.ok(value=`record`))*. + +## download + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | Stable X.Y.Z explicitly chosen by the user | +| mode | text | "full" | full, cli or ext; determines the deliverable contract | +| directory | any | None | Relative destination; None selects dist/release-X.Y.Z | +| root | text | "." | Checkout directory; pass --fs-root . from its root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with locally downloaded, byte-verified and content-checked assets | + +Use `version`, `mode`="full", `directory`=None and `root`=".". +The destination stays inside the checkout. Files are reused only after their +size and GitHub digest are checked again; a .partial file never counts as an +artifact. Network retries try the configured GitHub proxy then the original +asset URL. The download adapter validates archive paths and CRCs without +extracting an executable. Role-specific checks below use the same version. +A failure stops the batch with its real error. Successfully verified files +remain in the destination for a retry, while no R2 pointer or PPA is changed. +plugin,fs.write,network.read,environment.read includes the adapter's local writes and network authority; the +working root is a location constraint, not a subprocess permission sandbox. + +We **catalog_result = [Require complete GitHub metadata first](catalog(version=`version`, mode=`mode`, root=`root`))**. +1. not access(`catalog_result`, "ok") + Return *catalog_result* with its failure intact. + +We **catalog_data = [Read the accepted metadata](access(catalog_result, "value"))** and +**required = [Read required names](access(access(catalog_data, "plan"), "required"))** and +**assets = [Read their GitHub size and digest records](access(catalog_data, "assets"))**. +1. `directory` == None + We **directory = "dist/release-" + version** for the release staging directory. +We **checked = [Start the verified artifact list](table.empty_list())**. +- [Download and verify each required artifact](for required as name) + We **asset = [Select its unmodified metadata](named(assets=`assets`, name=`name`))**. + + `payload` = + + | asset | directory | + |---|---| + | `asset` | `directory` | + + We **fetched = [Transfer exact GitHub bytes and validate digest and CRC](native.fetch(asset=`asset`, directory=`directory`, root=`root`))**. + 1. not access(`fetched`, "ok") + Return *fetched* with the completed earlier files retained. + We **verified = [Check the package's actual role and version](content(record=access(fetched, "value"), version=`version`))**. + 1. not access(`verified`, "ok") + Return *verified* before any publication step. + We **checked = [Append the checked evidence](table.append(list=`checked`, item=access(verified, "value")))**. +We **consistent = [Check source/native capabilities across the complete set](matrix(records=`checked`))**. +1. not access(`consistent`, "ok") + Return *consistent* before publication. +We **evidence = [Keep concise observed paths and hashes](summaries(records=`checked`, directory=`directory`))**. +Return *[The real verified local artifacts](result.ok(value=`evidence`))*. + +## status + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | Stable X.Y.Z explicitly chosen by the user | +| mode | text | "full" | full, cli or ext; determines the deliverable contract | +| root | text | "." | Checkout directory; pass --fs-root . from its root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with CDN parity, version pointers and checked URLs | + +Use `version`, `mode`="full" and `root`="." to verify published extension +bytes. CLI mode has no CDN obligation and reports that explicitly. Other modes +require both the versioned and latest download for each of the three packs, plus +both VERSION pointers. Their SHA256 values must match the GitHub-provided digest +for the exact release. Missing digests remain a failure; the task does not infer +integrity from a filename, HTTP status or a previous version's pointer. +This operation is read-only but downloads the bytes to compute their hashes. +A pointer can be published before every edge cache refreshes; any mismatch keeps +complete=False and retains the URL evidence so a later query can verify it. + +We **catalog_result = [Read the same release's asset metadata](catalog(version=`version`, mode=`mode`, root=`root`))**. +1. not access(`catalog_result`, "ok") + Return *catalog_result* with its failure intact. + +We **catalog_data = [Read the accepted catalog](access(catalog_result, "value"))** and +**checks = [Start public endpoint evidence](table.empty_list())** and **complete = True**. +1. `mode` != "cli" + We **names = [Read the three CDN deliverables](access(access(catalog_data, "plan"), "cdn"))** and + **assets = [Read the exact GitHub asset digests](access(catalog_data, "assets"))**. + + `prefixes` = + + | prefix | + |---| + | "v`version`" | + | latest | + + - [Verify versioned and latest publication independently](for prefixes as prefix) + + We **pointer_path = prefix + "/VERSION"** as the explicit public pointer. + + We **pointer = [Read the public version pointer](native.cdn(path=`pointer_path`))**. + 1. not access(`pointer`, "ok") + Return *pointer* with its service failure. + We **complete = [Keep a mismatched pointer incomplete](complete and access(access(pointer, "value"), "version") == version)**. + - [Compare every pack with its GitHub SHA256](for names as name) + We **asset = [Keep GitHub metadata as the source of truth](named(assets=`assets`, name=`name`))**. + + We **asset_path = prefix + "/" + name** as the exact public object. + + We **observed = [Hash the actual public download](native.cdn(path=`asset_path`))**. + 1. not access(`observed`, "ok") + Return *observed* with its failed public read. + We **digest = [Read the observed SHA256](access(access(observed, "value"), "sha256"))** and + **matches = [Require the same exact release bytes](table.get(map=`asset`, key="digest") == "sha256:" + digest)** and + **complete = complete and matches**. + + `evidence` = + + | path | sha256 | matches | + |---|---|---| + | "`prefix`/`name`" | `digest` | `matches` | + + We **checks = [Retain this endpoint's evidence](table.append(list=`checks`, item=`evidence`))**. + +We **needed = [Decide whether this mode publishes extension packs](mode != "cli")**. + +`state` = + +| complete | required | checks | +|---|---|---| +| `complete` | `needed` | `checks` | + +Return *[The measured CDN publication state](result.ok(value=`state`))*. + +## publish + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | Stable X.Y.Z explicitly chosen by the user | +| mode | text | "full" | full, cli or ext; determines the deliverable contract | +| directory | any | None | Verified staging directory; None uses dist/release-X.Y.Z | +| root | text | "." | Checkout directory; pass --fs-root . from its root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result of verified R2 upload followed by public byte-parity checks | + +Use `version`, `mode`="full", `directory`=None and `root`="." only after the +user has instructed this release. CLI-only mode has no extension publication +step. The three local ZIPs must already exist, match GitHub metadata and pass +content checks before any R2 write begins. Their combined capability matrix +must also agree: source-declared plugins require both matching native libraries. +Individually valid archives cannot hide a missing runtime on one platform. Missing credentials produce an error +with the existing uploader command available in this handbook's recovery notes. +The maintained uploader writes all versioned/latest packs before VERSION, keeping +pointer updates after content. It does not delete older versions. After upload, +this function verifies public parity; an edge-cache delay is incomplete evidence, +not a reason to upload unrelated files from the whole dist directory. + +We **catalog_result = [Validate the intended release and all required filenames](catalog(version=`version`, mode=`mode`, root=`root`))**. +1. not access(`catalog_result`, "ok") + Return *catalog_result* with its failure intact. + +1. `mode` == "cli" + Return *[Report that this mode has no CDN publication](status(version=`version`, mode=`mode`, root=`root`))*. +1. `directory` == None + We **directory = "dist/release-" + version** as the staging directory. +We **catalog_data = [Read the verified metadata catalog](access(catalog_result, "value"))** and +**names = [Read the exact three CDN packs](access(access(catalog_data, "plan"), "cdn"))** and +**assets = [Read their GitHub digests](access(catalog_data, "assets"))** and +**files = [Start the explicit upload path list](table.empty_list())** and +**records = [Retain the complete source and platform content evidence](table.empty_list())**. +- [Verify all local packs before touching R2](for names as name) + We **asset = [Choose the same release asset](named(assets=`assets`, name=`name`))** and + **path = directory + "/" + name**. + + `payload` = + + | asset | path | + |---|---| + | `asset` | `path` | + + We **verified = [Require local size, SHA256 and archive CRC parity](native.verify(asset=`asset`, path=`path`, root=`root`))**. + 1. not access(`verified`, "ok") + Return *verified* before any CDN write. + We **checked = [Require the expected contents and version](content(record=access(verified, "value"), version=`version`))**. + 1. not access(`checked`, "ok") + Return *checked* with the source or platform error. + We **records = [Retain the verified archive for capability matching](table.append(list=`records`, item=access(verified, "value")))** and + **sha256 = [Retain this file's checked native hash](access(access(verified, "value"), "sha256"))**. + + `file` = + + | path | name | sha256 | + |---|---|---| + | `path` | `name` | `sha256` | + + We **files = [Keep only the verified upload record](table.append(list=`files`, item=`file`))**. + +We **matched = [Require the source-declared plugins in both native platform packs](matrix(records=`records`))**. +1. not access(`matched`, "ok") + Return *matched* before publishing any pack or pointer. + +`upload` = + +| version | files | +|---|---| +| `version` | `files` | + +We **uploaded = [Upload only the three verified packs using private R2 credentials](native.upload(version=`version`, files=`files`, root=`root`))**. +1. not access(`uploaded`, "ok") + Return *uploaded* with its failure intact. + +Return *[Verify the public bytes after uploading](status(version=`version`, mode=`mode`, root=`root`))*. diff --git a/skills/marqdo-release/github.mq.md b/skills/marqdo-release/github.mq.md new file mode 100644 index 0000000..e6c60d9 --- /dev/null +++ b/skills/marqdo-release/github.mq.md @@ -0,0 +1,353 @@ +--- +markup: occlusion +title: Observe and update GitHub release evidence +import: + bridge: ./_bridge.mq.md + model: ./model.mq.md + table: lib/table.mq.md + result: lib/result.mq.md + fs: lib/fs.mq.md +--- + +GitHub release tasks keep source identity and publication state explicit. Start +with status for an existing version; notes is a separate mutation that consumes +a reviewed bilingual file. The same release metadata feeds assets.download and +assets.status, so name, size and digest checks do not drift between channels. + +Every task returns Result.ok/value/error. Check that inner ok before consuming +value, then inspect complete for gates. A successful query may truthfully report +an incomplete release. plugin grants the native boundary OS/network +authority; credentials are resolved privately from the environment or existing +credential stores. They are never parameters, return values or journal bindings. + +Example, from the checkout root: + +```sh +marqdo call skills/marqdo-release/github.mq.md status 'version="2.6.0"' --effects plugin --fs-root . --json +``` + +The command is read-only. A future release uses the version the user actually +specified. A red EK gate, missing Linux build or wrong-commit green run keeps the +release incomplete even if a GitHub download page already exists. + +## request + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | API path scoped to /repos/cflmy/marqdo/ | +| method | text | "GET" | GET for observation; PATCH for notes; POST for explicit publication | +| data | any | None | JSON request body; credentials are never arguments | +| missing | bool | False | Whether GET 404 is represented as a successful None | +| root | text | "." | Checkout directory; pass --fs-root . from its root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result containing service JSON or a transport error | + +Use `path`, `method`="GET", `data`=None, `missing`=False and `root`=".". +This function is the authenticated GitHub boundary used by the tasks below. +The proxy is tried before direct GitHub; GET and idempotent note PATCH may be +retried, while an uncertain POST is returned as failure. API failures retain a +code and service name without exposing tokens, headers or signed download URLs. +Reading requires plugin because the native engineering plugin owns HTTPS. + +`payload` = + +| path | method | data | missing | +|---|---|---|---| +| `path` | `method` | `data` | `missing` | + +Return *[Request GitHub JSON through the maintained transport](bridge.request(operation="github", payload=`payload`, root=`root`))*. + +## release + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | Stable X.Y.Z explicitly chosen by the user | +| mode | text | "full" | full, cli or ext; determines the deliverable contract | +| root | text | "." | Checkout directory; pass --fs-root . from its root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result containing release metadata, or None when not published | + +Use `version`, `mode`="full" and `root`=".". +The mode selects vX.Y.Z or ext-vX.Y.Z through the same pure plan used for +packaging. A missing release is an observable state, not proof that a previous +publish command failed before creating anything. Callers can distinguish it +from a network or authentication failure by inspecting Result.ok first. +This query does not create a release and never invokes the old Windows-only +publication script, whose assumptions predate embedded standard libraries. + +We **planned = [Derive the correct release tag](model.plan(version=`version`, mode=`mode`))**. +1. not access(`planned`, "ok") + Return *planned* with its failure intact. + +We **plan_data = [Read the accepted tag contract](access(planned, "value"))** and +**path = "/repos/cflmy/marqdo/releases/tags/" + access(plan_data, "tag")**. +Return *[Observe this exact release without creating one](request(path=`path`, missing=True, root=`root`))*. + +## commit + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| tag | text | required | Exact tag from the release plan | +| root | text | "." | Checkout directory; pass --fs-root . from its root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with the commit SHA targeted by a lightweight or annotated tag | + +Use `tag` and `root`=".". Annotated tags point first to a tag object, +whereas lightweight tags already point to a commit. Follow that distinction +before matching a workflow run. Comparing a tag-object SHA with head_sha would +silently fail to find the correct green run. Only the single annotated object +created by this handbook is accepted; nested tag objects remain an error. +A missing tag is reported as a transport failure rather than guessed from main. + +We **reference = [Read the exact remote tag reference](request(path="/repos/cflmy/marqdo/git/ref/tags/" + tag, root=`root`))**. +1. not access(`reference`, "ok") + Return *reference* with its failure intact. + +We **object = [Read the tag target](access(access(reference, "value"), "object"))**. +1. access(`object`, "type") == "tag" + We **annotation = [Resolve the annotated tag object](request(path="/repos/cflmy/marqdo/git/tags/" + access(object, "sha"), root=`root`))**. + 1. not access(`annotation`, "ok") + Return *annotation* without substituting main. + We **object = [Read the annotated commit target](access(access(annotation, "value"), "object"))**. +1. access(`object`, "type") != "commit" + Return *[Reject an unexpected tag target](result.error(code="release.tag_target", message="tag must resolve to a commit", operation="github.commit"))*. +Return *[The immutable release commit](result.ok(value=access(object, "sha")))*. + +## select_run + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| runs | list | required | Workflow runs ordered newest first by the GitHub API | +| sha | text | required | Exact commit that this gate must cover | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Newest run for this commit, or None | + +Use `runs` and `sha` to select one observed gate attempt. The first matching +head_sha is the most recent attempt provided by the API; an older successful +attempt cannot mask a later failure for the same commit. Runs for other commits +are irrelevant even if their badges are green. No API access or waiting occurs +here, making this decision directly testable with recorded service responses. +If the bounded query contains no matching run, return None and keep the gate +incomplete. The caller may fetch again after CI starts. + +- [Inspect workflow runs in their returned order](for runs as run) + 1. access(`run`, "head_sha") == `sha` + Return *run* as the observed attempt for this source. + +Return *None* when this commit has no observed run. + +## gate + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| workflow | text | required | release.yml, extension-release.yml or executable-knowledge.yml | +| sha | text | required | Commit that the workflow must cover | +| required | list | required | Required job names, such as windows and linux | +| root | text | "." | Checkout directory; pass --fs-root . from its root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with completion, observed run and required-job evidence | + +Use `workflow`, `sha`, `required` and `root`=".". Completion requires both a +successful run for the exact commit and every named job with conclusion success. +A skipped or missing Linux job cannot pass just because the Windows job created +a release. This query checks at most 100 recent runs, returns immediately for +queued/running CI, and does not rerun or cancel anything. Polling belongs to the +agent's bounded observation cycle, not an unbounded loop hidden in a tool. +Knowledge checks use the same rule, so uploaded assets never replace a green EK +gate. Missing evidence returns complete=False with the observed run retained. + +We **response = [Read recent attempts for one workflow](request(path="/repos/cflmy/marqdo/actions/workflows/" + workflow + "/runs?per_page=100", root=`root`))**. +1. not access(`response`, "ok") + Return *response* with its failure intact. + +We **run = [Choose the latest attempt for this commit](select_run(runs=access(access(response, "value"), "workflow_runs"), sha=`sha`))**. +We **complete = False** and **jobs = [Start an empty required-job evidence list](table.empty_list())**. +1. `run` != None + We **answer = [Read this attempt's actual jobs](request(path="/repos/cflmy/marqdo/actions/runs/" + access(run, "id") + "/jobs?per_page=100", root=`root`))**. + 1. not access(`answer`, "ok") + Return *answer* with its failed observation. + We **jobs = [Keep the observed jobs](access(access(answer, "value"), "jobs"))** and + **complete = [Require a successful completed run](access(run, "status") == "completed" and access(run, "conclusion") == "success")**. +- [Check that every required platform or knowledge job passed](for required as name) + We **matched = False** before examining this job name. + - [Match this job against observed evidence](for jobs as job) + 1. access(`job`, "name") == `name` and access(`job`, "conclusion") == "success" + We **matched = True** because the named job succeeded. + We **complete = complete and matched** to preserve every missing-job failure. + +`evidence` = + +| complete | sha | run | jobs | +|---|---|---|---| +| `complete` | `sha` | `run` | `jobs` | + +Return *[The observed gate and its evidence](result.ok(value=`evidence`))*. + +## status + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | Stable X.Y.Z explicitly chosen by the user | +| mode | text | "full" | full, cli or ext; determines the deliverable contract | +| root | text | "." | Checkout directory; pass --fs-root . from its root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with exact-source Release and executable-knowledge gates | + +Use `version`, `mode`="full" and `root`="." to inspect an existing release. +The Release workflow is matched against the resolved release tag; executable +knowledge is matched against the current remote main tip. Both sources are +returned so a reviewer can see if main has advanced. Every mode requires both +Windows and Linux jobs on the tag commit. Independent packs use extension-release.yml; +full/cli use release.yml. Existing assets cannot replace missing build evidence. +A missing release or an unfinished gate leaves complete=False. This task does +not mutate GitHub, push local work, create tags, or change the requested version. +The returned service metadata is evidence for the next task, not a permission +to publish a different version or overwrite a release's existing files. + +We **published = [Inspect the exact version's release](release(version=`version`, mode=`mode`, root=`root`))**. +1. not access(`published`, "ok") + Return *published* with its failure intact. + +We **planned = [Read the pure release contract](model.plan(version=`version`, mode=`mode`))**. +1. not access(`planned`, "ok") + Return *planned* with its failure intact. + +We **release_data = [Keep the published metadata or None](access(published, "value"))** and +**tag = [Read the planned tag](access(access(planned, "value"), "tag"))**. +We **tagged = [Resolve its actual source commit](commit(tag=`tag`, root=`root`))**. +1. not access(`tagged`, "ok") + Return *tagged* with its failure intact. + +We **main = [Observe the remote main tip](request(path="/repos/cflmy/marqdo/git/ref/heads/main", root=`root`))**. +1. not access(`main`, "ok") + Return *main* with its failure intact. + +We **main_sha = [Read main's commit SHA](access(access(access(main, "value"), "object"), "sha"))**. + +`knowledge_jobs` = + +| name | +|---| +| gate | + +We **knowledge = [Verify EK on the actual remote main commit](gate(workflow="executable-knowledge.yml", sha=`main_sha`, required=`knowledge_jobs`, root=`root`))**. +1. not access(`knowledge`, "ok") + Return *knowledge* with its failure intact. + +We **workflow = "release.yml"** for a CLI or full release. +1. `mode` == "ext" + We **workflow = "extension-release.yml"** for independent extension builds. + +`platform_jobs` = + +| name | +|---| +| windows | +| linux | + +We **platforms = [Require both platform builds for the tagged source](gate(workflow=`workflow`, sha=access(tagged, "value"), required=`platform_jobs`, root=`root`))**. +1. not access(`platforms`, "ok") + Return *platforms* with its failed gate observation. +We **release_gate = [Keep actual platform evidence](access(platforms, "value"))** and **release_complete = [Read the exact-tag completion decision](access(release_gate, "complete"))**. + +We **all_complete = [Require the published release and both source-specific gates](release_data != None and release_complete and access(access(knowledge, "value"), "complete"))**, +**release_sha = [Keep the resolved release commit](access(tagged, "value"))** and +**knowledge_state = [Keep the exact-main knowledge evidence](access(knowledge, "value"))** before forming the record. + +`status_data` = + +| complete | release | release_sha | main_sha | release_ci | knowledge_ci | +|---|---|---|---|---|---| +| `all_complete` | `release_data` | `release_sha` | `main_sha` | `release_gate` | `knowledge_state` | + +Return *[The release's observed gates and source identities](result.ok(value=`status_data`))*. + +## notes + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | Stable X.Y.Z explicitly chosen by the user | +| path | text | required | Reviewed UTF-8 bilingual notes file under the filesystem root | +| mode | text | "full" | full, cli or ext; determines the deliverable contract | +| root | text | "." | Checkout directory; pass --fs-root . from its root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result of updating only the existing release body | + +Use `version`, `path`, `mode`="full" and `root`=".". This is an explicit +GitHub mutation and needs the user's release instruction; reading this handbook +or asking for status does not authorize it. The prepared notes must contain +Chinese and English highlights, the actual asset matrix, installation routes, +core-surface delta and validation limits. The author remains responsible for +those claims; this function uploads the reviewed file rather than inventing it. +Reading uses fs.read in addition to plugin. UTF-8 text and its intentional +newlines travel in a structured JSON body, never through shell quoting. + +We **published = [Locate the existing release to edit](release(version=`version`, mode=`mode`, root=`root`))**. +1. not access(`published`, "ok") + Return *published* with its failure intact. + +We **release_data = [Read its metadata](access(published, "value"))**. +1. `release_data` == None + Return *[Do not invent a release when only editing notes](result.error(code="release.missing", message="release does not exist; wait for CI or attach an ext release", operation="github.notes"))*. +We **body = [Read the exact reviewed bilingual note file](fs.read_text(path=`path`))**. + +We **data = [Keep the reviewed body as one named API field](table.put(in=None, at="body", value=`body`))**. + +Return *[Publish the reviewed release body](request(path="/repos/cflmy/marqdo/releases/" + access(release_data, "id"), method="PATCH", data=`data`, root=`root`))*. + + +## create_ext + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | User-confirmed stable independent extension version | +| path | text | required | Reviewed bilingual notes committed with the release source | +| sha | text | required | Exact source commit expected from the authorized tag | +| root | text | "." | Checkout root matching the granted filesystem root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result containing newly created or already existing release metadata | + +Use `version`, `path`, `sha` and `root`="." only for authorized extension publication. This is an explicit GitHub mutation. First resolve ext-vX.Y.Z to its actual commit and require the caller's expected SHA. Read the committed note file through native filesystem operations before requesting creation. The file must describe this version's real changes and validation limits; the task does not synthesize release claims. + +An existing release is returned unchanged so a resumed upload cannot overwrite its notes or assets. A missing release is created once through the authenticated service boundary, with its exact existing tag and reviewed body. Uncertain POST completion is a failure, never an automatic replay; inspect the release before resuming. CI uses this task after packaging and then uploads with the existing gh tool without clobbering prior assets. + +We **planned = [Validate the independent extension version](model.plan(version=`version`, mode="ext"))**. +1. not access(`planned`, "ok") + Return *planned*. +We **tag = [Read the exact immutable extension tag](access(access(planned, "value"), "tag"))** and **target = [Resolve the actual remote tag commit](commit(tag=`tag`, root=`root`))**. +1. not access(`target`, "ok") + Return *target*. +1. access(`target`, "value") != `sha` + Return *[Refuse publication from a different source](result.error(code="release.source_mismatch", message="extension tag differs from expected commit", operation="create_ext"))*. +We **body = [Read the reviewed version-specific bilingual notes](fs.read_text(path=`path`))**. +1. `body` == "" + Return *[Require actual reviewed notes](result.error(code="release.notes_empty", message="extension notes must not be empty", operation="create_ext"))*. +We **existing = [Observe whether an earlier creation completed](release(version=`version`, mode="ext", root=`root`))**. +1. not access(`existing`, "ok") + Return *existing*. +1. access(`existing`, "value") != None + Return *existing*, preserving the existing release. + +`data` = + +| tag_name | name | target_commitish | body | draft | prerelease | +|---|---|---|---|---|---| +| `tag` | `tag` | `sha` | `body` | False | False | + +Return *[Create this exact tagged release once](request(path="/repos/cflmy/marqdo/releases", method="POST", data=`data`, root=`root`))*. diff --git a/skills/marqdo-release/index.mq.md b/skills/marqdo-release/index.mq.md new file mode 100644 index 0000000..033892e --- /dev/null +++ b/skills/marqdo-release/index.mq.md @@ -0,0 +1,220 @@ +--- +markup: occlusion +title: Marqdo release as an executable handbook +import: + model: ./model.mq.md + local: ./local.mq.md + github: ./github.mq.md + assets: ./assets.mq.md + ubuntu: ./ubuntu.mq.md + table: lib/table.mq.md + result: lib/result.mq.md +--- + +这份入口替代需要智能体重新拼装命令的发版 SKILL。版本和 full/cli/ext 模式必须由用户选择;已有明确选择时沿用授权,不重复询问。读取本手册或检查旧版本不会授权再次发布。当前维护版本的真实只读验证可调用 status 或 verify,并传入 version="2.6.0"。 + +先调用 plan 查看版本对应的产物与步骤,再由 local.inspect 查看本地状态。local.bump 修订版本,作者用开发手册的原生文件工具撰写双语 CHANGELOG、发布说明与用户文档,local.docs 构建真实文档。需要 CLI 的模式先编译独立编辑器分支,再显式提交审核过的文件并推送 main;EK 在实际提交上变绿后才创建新的不可变标签。每一步保留真实 Result,不通过资产存在来掩盖失败。 + +多文件工程按职责分开:model 是纯产物契约;local 是本地元数据、Git 与编辑器任务;github 是提交身份及 CI 证据;assets 与 asset_io 是同字节下载、内容检查和 R2 发布;ubuntu 与 package 是 noble 源码构建及 apt 验证。标准库的文件读写、JSON/TOML、哈希、网络、日期和表格负责组合,工程插件仅承担进程、认证和压缩格式边界。开发流程不需要 Python。独立拓展包在 packs.mq.md 中通过原生文件能力暂存与检查,并外联既有 ZIP 工具;ext-v 标签触发 extension-release.yml,两个平台均使用 packs.ci 与 packs.attach_ci 完成构建、精确来源检查、创建 Release 和不覆盖已有资产的上传。创建标签前须提交 doc/releases/ext-X.Y.Z.md 双语说明。 + +发布必须保留以下约束:main 不跟踪 vscode-extension 源码;标签不可覆盖;不得强推或绕过钩子;full 必须具备 Windows 和 Linux 产物。拓展包同时发布到 GitHub 和 R2,所有 ZIP 先于 VERSION 指针上传。full/cli 还需 Ubuntu PPA 源码上传、构建和 apt 发布证据。Release 与 EK 都应在正确来源提交上成功。双语说明要写实际核心表面变化及验证限制,不能只用模板宣称兼容。 + +凭据留在原有私密存储,不作为调用参数、源码或会话绑定。网络失败先走配置代理并有界重试,再直连;仍失败时保留本地证据,使用明确配置的外联传输,不能假装完成。sudo、GPG 或 dput 若需要人工输入,报告失败阶段及具体的 marqdo call 恢复命令。gh-pages 部署需要另外的用户指令。 + +命令形式是 marqdo call skills/marqdo-release/index.mq.md plan 'version="2.6.0"' --json。源码仓库开发时使用已构建的 target/debug/marqdo;先按开发入口 prepare_engineering 准备插件。status 和 verify 都使用 plugin,fs.write,network.read,environment.read,用于本地暂存和公开下载的校验;preflight 只需 plugin,fs.read,plan 不需要效应授权。自动化串接可加 --require-ok:函数返回失败 Result 时退出码非零,并保留真实返回值。所有命令都从仓库根目录传 --fs-root .。 + +## plan + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | User-confirmed stable X.Y.Z; inspection never chooses another version | +| mode | text | "full" | full, cli or ext | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with exact deliverable names and task routing | + +Use `version` and `mode`="full" after the user's version decision. +This pure entry derives filenames and publication obligations; it grants no +effect and writes no resource. Full has ten GitHub deliverables and both native +platforms, cli keeps the independent pack version, and ext has three packs on +both GitHub and R2. Unknown modes and malformed versions fail before IO. + +Follow the returned task routing to the actual callable files, whose headings +specify their inputs, outputs and failures. The routing is not a shell program +for the model to reconstruct. Inspecting the plan for an existing version is +safe and does not authorize a replacement release or a new immutable tag. + +Return *[Derive the confirmed release contract](model.plan(version=`version`, mode=`mode`))*. + +## preflight + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | User-confirmed stable X.Y.Z; inspection never chooses another version | +| mode | text | "full" | full, cli or ext | +| root | text | "." | Checkout/artifact root matching --fs-root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with ready, plan and actual local checkout facts | + +Use `version`, `mode`="full" and `root`="." before preparing a +release. This reads actual Git state and native version files; it does not fetch, +reset, stage, sign or publish. A clean main checkout without tracked editor +sources and without the selected local tag is ready for preparation. Existing +tags require inspection of their release state rather than replacement. + +A successful Result may contain ready=False. That is a real observation, not +permission to discard dirty files or overwrite refs. During authorized release +preparation, intentional edits remain visible until the explicit commit task. +The later tag task checks matching versions, remote main identity and EK again, +so preflight cannot become stale authorization. Call with plugin,fs.read and a +filesystem root that identifies the same checkout as the plugin's root. + +We **planned = [Validate the requested release contract](model.plan(version=`version`, mode=`mode`))**. +1. not access(`planned`, "ok") + Return *planned*. +We **observed = [Read the real checkout without changing it](local.inspect(root=`root`))**. +1. not access(`observed`, "ok") + Return *observed*. +We **plan_data = [Keep the pure release plan](access(planned, "value"))** and **state = [Keep the actual Git and version facts](access(observed, "value"))**. +We **exists = [Preserve any existing immutable tag](table.contains(list=access(state, "tags"), item=access(plan_data, "tag")))** and +**ready = access(state, "branch") == "main" and access(state, "changes") == "" and access(state, "extension_on_main") == "" and not exists**. + +`inspection` = + +| ready | plan | checkout | +|---|---|---| +| `ready` | `plan_data` | `state` | + +Return *[The preparation decision with its evidence](result.ok(value=`inspection`))*. + +## status + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | User-confirmed stable X.Y.Z; inspection never chooses another version | +| mode | text | "full" | full, cli or ext | +| root | text | "." | Checkout/artifact root matching --fs-root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with source-specific GitHub CI, CDN parity and Ubuntu state | + +Use `version`, `mode`="full" and `root`="." for an existing release. +This entry independently checks GitHub publication and its exact source commits, +the versioned and latest CDN bytes when packs ship, and Ubuntu publication when +the CLI ships. It creates no tag, release, upload or apt mutation. Temporary +download files are owned and cleaned by the native CDN task. + +The result keeps each component's evidence and requires all applicable components +to complete. A missing or red gate, different digest, pending build or stale apt +index remains incomplete. Network failures are failed Results, not fabricated +absence. Call with plugin,fs.write,network.read,environment.read: local writes +are only bounded verification staging. An ext-only release skips Ubuntu; a +cli-only release skips CDN. Existing GitHub assets alone never prove completion. + +We **source = [Observe publication and CI on the actual source identities](github.status(version=`version`, mode=`mode`, root=`root`))**. +1. not access(`source`, "ok") + Return *source*. +We **cdn = [Verify published pack hashes and VERSION pointers](assets.status(version=`version`, mode=`mode`, root=`root`))**. +1. not access(`cdn`, "ok") + Return *cdn*. +We **ppa = None** and **ppa_complete = True** for an extension-only release. +1. `mode` != "ext" + We **observed = [Check source publication, builds and the actual apt index](ubuntu.status(version=`version`))**. + 1. not access(`observed`, "ok") + Return *observed*. + We **ppa = [Retain the real Ubuntu evidence](access(observed, "value"))** and **ppa_complete = [Read its independent completion state](access(ppa, "complete"))**. +We **github_state = [Keep GitHub evidence](access(source, "value"))** and **cdn_state = [Keep CDN evidence](access(cdn, "value"))** and +**complete = access(github_state, "complete") and access(cdn_state, "complete") and ppa_complete**. + +`state` = + +| complete | github | cdn | ubuntu | +|---|---|---|---| +| `complete` | `github_state` | `cdn_state` | `ppa` | + +Return *[The independently measured release state](result.ok(value=`state`))*. + +## verify + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | User-confirmed stable X.Y.Z; inspection never chooses another version | +| mode | text | "full" | full, cli or ext | +| root | text | "." | Checkout/artifact root matching --fs-root | +| directory | any | None | Staging directory; None means dist/release-X.Y.Z | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with all verified local artifacts and published completion evidence | + +Use `version`, `mode`="full", `root`="." and `directory`=None to +verify an existing release from its actual bytes. First download or reuse every +required GitHub artifact, check size and digest, inspect archive paths and CRCs, +and verify each package's role and version. Then status checks independent +publication channels. Existing valid local files may be reused after rechecking. + +This is verification, not publication. It needs plugin,fs.write,network.read, +environment.read and can consume network time for all platform packs. Failed +checks preserve their source error and completed local files for diagnosis; +none triggers a re-upload. Full completion includes Linux and Windows, green +source-specific CI, matching CDN copies and Ubuntu's actual apt index. Keep the +returned hashes as release evidence. A later release still needs its own user +version decision and source review. + +We **downloaded = [Validate all required GitHub asset bytes and package contents](assets.download(version=`version`, mode=`mode`, directory=`directory`, root=`root`))**. +1. not access(`downloaded`, "ok") + Return *downloaded*. +We **observed = [Verify all applicable published channels](status(version=`version`, mode=`mode`, root=`root`))**. +1. not access(`observed`, "ok") + Return *observed*. +We **artifacts = [Retain exact local hash evidence](access(downloaded, "value"))** and **publication = [Retain independent remote evidence](access(observed, "value"))** and **complete = [Read the real completion decision](access(publication, "complete"))**. + +`evidence` = + +| complete | artifacts | publication | +|---|---|---| +| `complete` | `artifacts` | `publication` | + +Return *[The verified bytes and actual publication state](result.ok(value=`evidence`))*. + + +## finish + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | User-confirmed stable X.Y.Z | +| mode | text | "full" | full, cli or ext | +| root | text | "." | Checkout/artifact root matching --fs-root | +| directory | any | None | Local artifact staging directory | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result succeeding only when all verified release obligations are complete | + +Use `version`, `mode`="full", `root`="." and `directory`=None at the +final verification step of an authorized release. This runs verify on actual +artifact bytes and independent published channels. It does not create another +release, overwrite assets or repeat an upload. + +Unlike an observational status query, this completion gate returns a failed +Result when any applicable obligation is pending. The failure retains its +evidence record so a reviewer can identify the unfinished channel. Use +--require-ok when this task is the last step of external automation; a pending +release then produces a nonzero exit status. It needs the same native staging, +network, environment and plugin grants as verify. A service failure retains its +original source diagnostic. Only this successful final gate permits reporting +the chosen release complete; changing the version still requires the user's +explicit decision. + +We **observed = [Verify actual artifacts and every applicable publication channel](verify(version=`version`, mode=`mode`, root=`root`, directory=`directory`))**. +1. not access(`observed`, "ok") + Return *observed* with its original failure. +We **evidence = [Retain the complete verification record](access(observed, "value"))**. +1. not access(`evidence`, "complete") + We **failure = [Keep pending publication distinct from successful completion](result.error(code="release.incomplete", message="inspect evidence for the unfinished release obligation", operation="finish"))**. + Return *[Retain evidence with the failed completion gate](table.put(in=`failure`, at="evidence", value=`evidence`))*. +Return *observed* when every required obligation is verified. diff --git a/skills/marqdo-release/local.mq.md b/skills/marqdo-release/local.mq.md new file mode 100644 index 0000000..250b528 --- /dev/null +++ b/skills/marqdo-release/local.mq.md @@ -0,0 +1,883 @@ +--- +markup: occlusion +title: Prepare and publish a reviewed source release +import: + bridge: ./_bridge.mq.md + model: ./model.mq.md + github: ./github.mq.md + fs: lib/fs.mq.md + table: lib/table.mq.md + result: lib/result.mq.md + text: lib/text.mq.md + toml: lib/toml.mq.md + sys: lib/sys.mq.md + datetime: lib/datetime.mq.md + re: lib/re.mq.md +--- + +Local release tasks replace repeated command-writing with explicit callable +operations. Inspect first, use bump for version metadata, author and review the +bilingual release text, build docs, compile the editor branch separately, commit +reviewed paths, push main, wait for EK, then create the annotated tag. + +These are separate tasks because their results are reviewable artifacts and +because waiting for CI is different from creating a new reference. Existing +user authorization carries through the chosen release; none of the tasks asks +for a second version choice. A new release version or a replacement tag needs +its own user decision. No task force-pushes or bypasses hooks. + +Every process operation returns Result.ok/value/error. A failed compile, Git +hook or network request stops the dependent task. Multi-file metadata edits are +not a transaction: inspect any partial changes before retrying. No task cleans +or stages unrelated work, commits editor sources on main, or deploys gh-pages. + +```sh +marqdo call skills/marqdo-release/local.mq.md inspect --effects plugin,fs.read --fs-root . --json +``` + +For mutation, use the chosen version and the effect grant described on that +heading. bump needs fs.write and plugin; the rest of the command tasks +use plugin, whose children retain normal OS authority. Do not interpret +--fs-root as a sandbox for external tools. GPG or sudo interaction is reported +at the Ubuntu boundary rather than hidden behind an unconditional success. + +## inspect + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| root | text | "." | Checkout root matching --fs-root; relative to the granted runtime cwd | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with Git identity and versions read by native filesystem tools | + +Use `root`="." to inspect a checkout without changing it. Git supplies branch, +HEAD, dirty paths and tags through the engineering boundary. Cargo manifests +and ext/VERSION are read with lib/fs and decoded with lib/toml and lib/text. +The version facts are therefore visible in this source rather than hidden in +an external file-reading script. No credential contents are returned. + +The plugin root and --fs-root must identify the same directory; this check catches +a caller accidentally combining one checkout's Git state with another checkout's +version files. Local tags are evidence only; remote references are checked before +tagging. This operation requires plugin and fs.read but performs no publication. + +We **payload = [Start an empty Git metadata request](table.empty_map())** and +**observed = [Read Git's actual repository state](bridge.request(operation="git_inspect", payload=`payload`, root=`root`))**. +1. not access(`observed`, "ok") + Return *observed* with its source error. +We **state = [Read the observed Git metadata](access(observed, "value"))** and +**cwd = [Read the native filesystem working root](sys.cwd())**. +1. access(`state`, "root") != `cwd` + Return *[Refuse inconsistent process and filesystem roots](result.error(code="release.root_mismatch", message="root must match --fs-root", operation="local.inspect"))*. + +We **cli = [Read and decode the actual interpreter manifest](toml.parse(text=fs.read_text(path="Cargo.toml")))** and +**wasm = [Read and decode the actual WASM manifest](toml.parse(text=fs.read_text(path="crates/marqdo-wasm/Cargo.toml")))** and +**cli_version = [Read the interpreter package version](access(access(cli, "package"), "version"))** and +**wasm_version = [Read the WASM package version](access(access(wasm, "package"), "version"))** and +**ext_version = [Read the independent pack version](text.str_trim(s=fs.read_text(path="ext/VERSION")))**. + +`versions` = + +| cli_version | wasm_version | ext_version | +|---|---|---| +| `cli_version` | `wasm_version` | `ext_version` | + +We **combined = [Combine native file facts with Git identity](table.merge(a=`state`, b=`versions`))**. +Return *[The actual checkout facts](result.ok(value=`combined`))*. + +## command + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| argv | list | required | Exact command and argument vector; never shell source | +| cwd | text | "." | Working directory inside the checkout | +| timeout | number | 120 | Maximum child duration in seconds | +| root | text | "." | Checkout directory; pass --fs-root . from its root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with checked exit status and bounded stdout/stderr | + +Use `argv`, `cwd`=".", `timeout`=120 and `root`="." for maintained commands. +This transport keeps arguments separate even when filenames contain spaces, +quotes, dollar signs or backticks. It refuses inline shell programs, forced Git +updates and hook bypass. Git credentials are attached privately when needed; +they never become parameters or command text. Nonzero exit and timeout remain +failed Results, so a later stage cannot silently continue after a failed build. +A child inherits the caller's OS capabilities. This helper does not claim that +--fs-root makes arbitrary subprocesses safe or confines their own file access. + +`payload` = + +| argv | cwd | timeout | +|---|---|---| +| `argv` | `cwd` | `timeout` | + +Return *[Execute this exact maintained argument vector](bridge.request(operation="command", payload=`payload`, root=`root`))*. + +## replace_version + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Cargo manifest relative to the granted filesystem root | +| old | text | required | Observed previous package version | +| version | text | required | Stable X.Y.Z explicitly chosen by the user | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Number of replaced manifest version fields | + +Use `path`, `old` and `version` only after inspecting the version files. +The exact package-version line is replaced once. Other dependency versions and +surrounding documentation remain intact. The file helper refuses a missing or +ambiguous match, exposing drift instead of rewriting a whole manifest from a +model-generated template. Calling with the same version is a no-op. +This helper writes one file and is not a multi-file transaction. The calling +bump operation records which stage failed so the author can inspect any partial +changes before retrying. It needs fs.write under the supplied filesystem root. + +1. `old` == `version` + Return *0* because this manifest already has the requested version. +We **find = "version = \"" + old + "\""** and +**replacement = "version = \"" + version + "\""** as exact manifest lines. +Return *[Replace only the observed package version line](fs.text_patch(path=`path`, find=`find`, replace=`replacement`))*. + +## bump + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | Stable X.Y.Z explicitly chosen by the user | +| mode | text | "full" | full, cli or ext; determines the deliverable contract | +| root | text | "." | Checkout directory; pass --fs-root . from its root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with updated version metadata and Cargo check evidence | + +Use `version`, `mode`="full" and `root`="." after the user chooses the release. +Full updates CLI, WASM and ext/VERSION; cli updates the two Cargo packages; ext +updates only ext/VERSION. Cargo check updates the lockfile for CLI/full and the +Debian stanza preserves the existing maintainer while dating the entry in +Asia/Shanghai. No tag, commit, remote push, R2 upload or PPA upload happens here. +The author still writes the bilingual CHANGELOG, README/tutorial changes and +release notes: version replacement cannot decide or verify their factual claims. +Run docs and the relevant regressions after those authored changes are reviewed. +The native filesystem calls need fs.write; Cargo and packaging transport need +plugin. A failure leaves intentional local changes available for review, +rather than pretending the multi-file edit was atomic or resetting other work. + +We **planned = [Validate the user-chosen version and mode](model.plan(version=`version`, mode=`mode`))**. +1. not access(`planned`, "ok") + Return *planned* with its failure intact. + +We **observed = [Read current versions before changing any](inspect(root=`root`))**. +1. not access(`observed`, "ok") + Return *observed* with its failure intact. + +We **state = [Keep the observed version metadata](access(observed, "value"))**. +1. access(`state`, "branch") != "main" or access(`state`, "extension_on_main") != "" + Return *[Require the main checkout without tracked editor sources](result.error(code="release.branch", message="bump runs on main; editor sources belong only on vscode-extension", operation="local.bump"))*. +1. `mode` != "ext" + We **cli_edit = [Update the interpreter package version](replace_version(path="Cargo.toml", old=access(state, "cli_version"), version=`version`))** and + **wasm_edit = [Update the WASM package version](replace_version(path="crates/marqdo-wasm/Cargo.toml", old=access(state, "wasm_version"), version=`version`))**. + + `cargo_args` = + + | argument | + |---| + | "cargo" | + | "check" | + | "--offline" | + + We **checked = [Update Cargo.lock and verify the new package metadata](command(argv=`cargo_args`, root=`root`, timeout=600))**. + 1. not access(`checked`, "ok") + Return *checked* with the local edits left for inspection. + We **packaging = [Add the dated Debian stanza through native file IO](debian(version=`version`))**. + 1. not access(`packaging`, "ok") + Return *packaging* before committing any metadata. +1. `mode` != "cli" + We **ext_edit = [Write the independent extension pack version](fs.write_text(path="ext/VERSION", text=`version` + "\n"))**. +Return *[Read back all resulting metadata and dirty paths](inspect(root=`root`))*. + +## docs + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| root | text | "." | Checkout directory; pass --fs-root . from its root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result from rebuilding the actual public documentation | + +Use `root`="." after authoring public sources and release-facing documentation. +This command runs the checked-in documentation builder, which uses Marqdo View +on the real pages instead of copying stale generated HTML. Generated files stay +ignored and are packaged by CI. Library-only import helpers have no main entry; +their expected page execution status does not authorize inventing a main. +A failed builder is returned as an error and is not treated as proof that docs +were refreshed. This task does not deploy gh-pages; deployment is a separate +user request, even during a full release. + +`argv` = + +| argument | +|---| +| "bash" | +| "scripts/build-public.sh" | + +Return *[Regenerate documentation from the authored Marqdo sources](command(argv=`argv`, root=`root`, timeout=900))*. + +## review_index + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| paths | list | required | Exact reviewed repository-relative file paths | +| cwd | text | "." | Git checkout within root; editor stage or main | +| root | text | "." | Checkout root matching --fs-root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result whose value lists the already staged paths | + +Use `paths`, `cwd`="." and `root`="." before staging or running a +version-changing tool. This inspection reads the actual Git index with explicit +unquoted path output; UTF-8 names and spaces remain ordinary path data. +Every existing staged path must appear in the supplied reviewed file list. +A refusal leaves both the index and working tree unchanged. + +The release source and editor branch share this inspection so a pre-staged +unrelated edit cannot become part of either version commit. It does not inspect +unstaged file content, authorize a commit or reset another task's index. +Newline-bearing filenames are outside this release handbook's path contract. +Requires plugin for Git; there is no network request or filesystem write. + +`argv` = + +| argument | +|---| +| "git" | +| "-c" | +| "core.quotepath=false" | +| "diff" | +| "--cached" | +| "--name-only" | + +We **observed = [Read the current staged file names before any change](command(argv=`argv`, cwd=`cwd`, root=`root`))**. +1. not access(`observed`, "ok") + Return *observed* with its Git diagnostic. +We **staged = [Split the observed index into individual file names](text.str_split(s=access(access(observed, "value"), "stdout"), sep="\n"))**. +- [Require each existing index path to be explicitly reviewed](for staged as path) + 1. `path` != "" and not [This staged path belongs to the review](table.contains(list=`paths`, item=`path`)) + Return *[Preserve unrelated staged work](result.error(code="release.staged_unrelated", message=`path`, operation="review_index"))*. +Return *[The inspected index paths](result.ok(value=`staged`))*. + +## commit + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| paths | list | required | Reviewed explicit paths; never use a blanket git add . | +| message | text | required | Commit message describing the actual reviewed release | +| root | text | "." | Checkout directory; pass --fs-root . from its root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with commit output; no remote mutation | + +Use `paths`, `message` and `root`="." after reviewing authored changes and +running the relevant checks. This function stages only the supplied paths, +checks the staged patch for whitespace errors, and creates an ordinary commit +with hooks enabled. It does not infer that every dirty file belongs to a release. +Editor sources remain on their own branch: do not include vscode-extension in +these paths. The current branch must be main. Only individual reviewed files are accepted; +a directory path is refused before staging. Deleted files can still be reviewed +by their exact repository path. Retries preserve already-staged deletions: Git no longer knows those missing paths in its index, so they must not be handed to git add again. Existing staged paths must all +appear in that same explicit file list before staging begins, so another task's +index work cannot be swept into the release commit. Broad pathspecs, parent +traversal and nested editor paths are rejected. These checks preserve the index +on refusal; a later hook failure keeps intentional staging available for review. The author can inspect staged changes before +this explicit commit task; a hook failure stays visible and is never bypassed. + +`branch_args` = + +| argument | +|---| +| "git" | +| "branch" | +| "--show-current" | + +We **observed = [Require the source branch before touching its index](command(argv=`branch_args`, root=`root`))**. +1. not access(`observed`, "ok") + Return *observed* with the command diagnostic. +We **branch = [Read the actual source branch](text.str_trim(s=access(access(observed, "value"), "stdout")))**. +1. `branch` != "main" + Return *[Keep release source commits on main](result.error(code="release.commit_branch", message="source commit requires main", operation="local.commit"))*. + +1. len(`paths`) == 0 or [Editor sources are not main-branch release files](table.contains(list=`paths`, item="vscode-extension")) + Return *[Require explicit reviewed main-branch paths](result.error(code="release.commit_paths", message="provide reviewed paths and exclude vscode-extension", operation="local.commit"))*. + +- [Validate individual reviewed repository paths](for paths as path) + 1. `path` == "." or `path` == "" or [This path is broad, outside the checkout or editor-only](re.is_match(text=`path`, pattern="(^/|(^|/)\\.\\.(/|$)|(^|/)vscode-extension(/|$)|[:*?])")) + Return *[Require concrete main-branch file paths](result.error(code="release.commit_paths", message=`path`, operation="local.commit"))*. + 1. [Inspect an existing reviewed path without opening it](fs.exists(path=`path`)) + We **metadata = [Require a file rather than a directory pathspec](fs.stat(path=`path`))**. + 1. access(`metadata`, "is_dir") + Return *[Do not stage an entire reviewed directory](result.error(code="release.commit_paths", message=`path`, operation="local.commit"))*. + +We **reviewed = [Protect all previously staged work](review_index(paths=`paths`, root=`root`))**. +1. not access(`reviewed`, "ok") + Return *reviewed* before changing the index. + +`deleted_args` = + +| argument | +|---| +| "git" | +| "-c" | +| "core.quotepath=false" | +| "diff" | +| "--cached" | +| "--name-only" | +| "--diff-filter=D" | +| "--no-renames" | + +We **removed = [Read deletions already retained by the reviewed index](command(argv=`deleted_args`, root=`root`))**. +1. not access(`removed`, "ok") + Return *removed* with the original index diagnostic. +We **deleted = [Keep exact already-staged deletion paths](text.str_split(s=access(access(removed, "value"), "stdout"), sep="\n"))** and **stage_paths = [Start only files requiring staging](table.empty_list())**. +- [Preserve reviewed deletions when retrying a failed commit](for paths as path) + 1. fs.exists(path=`path`) or not table.contains(list=`deleted`, item=`path`) + We **stage_paths = [Stage existing files and unstaged removals](table.append(list=`stage_paths`, item=`path`))**. +1. len(`stage_paths`) > 0 + + `prefix` = + + | argument | + |---| + | "git" | + | "add" | + | -- | + + We **argv = [Append only paths still requiring staging](table.concat(a=`prefix`, b=`stage_paths`))** and + **staged = [Stage those exact reviewed paths](command(argv=`argv`, root=`root`))**. + 1. not access(`staged`, "ok") + Return *staged* with its failure intact. + +`check_args` = + +| argument | +|---| +| "git" | +| "diff" | +| "--cached" | +| "--check" | + +We **checked = [Check the exact staged patch](command(argv=`check_args`, root=`root`))**. +1. not access(`checked`, "ok") + Return *checked* with its failure intact. + +`commit_args` = + +| argument | +|---| +| "git" | +| "commit" | +| "-m" | +| `message` | + +Return *[Create an ordinary commit with hooks](command(argv=`commit_args`, root=`root`))*. + +## push + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| refspec | text | "HEAD:refs/heads/main" | main, vscode-extension or a same-name stable tag; force syntax is rejected | +| cwd | text | "." | Checkout directory inside root; editor staging may override it | +| root | text | "." | Checkout root matching --fs-root; relative to the granted runtime cwd | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result confirming the exact expected remote ref SHA | + +Use `refspec`="HEAD:refs/heads/main", `cwd`="." and `root`="." only for +the authorized source publication. The argument vector and retry order are +visible here: proxy first, then direct GitHub, with two attempts per route. +After each response, including an uncertain timeout, read the remote ref before +deciding to retry. Only its exact expected SHA proves that this push arrived. + +A branch must match its destination; stable tags can only push to the same name. +The native boundary also rejects force and hook bypass. A test-only configured +remote can replace the network routes in an isolated fixture. Production +credentials remain private inside the engineering Git boundary. This task never +changes origin and never treats stale remote state as success. If both network +routes fail, retain local refs and use an explicitly configured SSH/HK transport +rather than force-pushing or silently skipping publication. + +MARQDO_RELEASE_GIT_REMOTE is an explicit transport override for an already +reviewed SSH/HK route or an isolated fixture. The task does not invent that +route, rewrite origin or generate a jump program. The same branch checks and +exact-SHA readback apply to an override; transport success alone is insufficient. +Configure SSH identities in the existing OS store, never in tool arguments. + +We **valid = [Accept only reviewed release refspec shapes](re.is_match(text=`refspec`, pattern="^(HEAD:refs/heads/(main|vscode-extension)|refs/tags/(ext-)?v[0-9]+\\.[0-9]+\\.[0-9]+:refs/tags/(ext-)?v[0-9]+\\.[0-9]+\\.[0-9]+)$"))**. +1. not `valid` + Return *[Reject arbitrary or forced ref updates](result.error(code="release.refspec", message="unsupported release refspec", operation="local.push"))*. +We **parts = [Separate the source and destination ref](text.str_split(s=`refspec`, sep=":"))** and +**source = [Read its local source](access(parts, 1))** and **destination = [Read its remote target](access(parts, 2))**. +1. `source` != "HEAD" and `source` != `destination` + Return *[Keep tag names immutable across push](result.error(code="release.refspec", message="tag destination must equal its source", operation="local.push"))*. + +`rev_args` = + +| argument | +|---| +| "git" | +| "rev-parse" | +| `source` | + +1. `source` == "HEAD" + `branch_args` = + + | argument | + |---| + | "git" | + | "branch" | + | "--show-current" | + + We **observed = [Read the current source branch before any push](command(argv=`branch_args`, cwd=`cwd`, root=`root`))**. + 1. not access(`observed`, "ok") + Return *observed*. + We **branch = [Keep the actual source branch](text.str_trim(s=access(access(observed, "value"), "stdout")))**. + 1. `destination` != "refs/heads/" + `branch` + Return *[Refuse a different branch destination](result.error(code="release.push_branch", message="source branch must match destination", operation="local.push"))*. + +We **local = [Resolve the exact local ref before transport](command(argv=`rev_args`, cwd=`cwd`, root=`root`))**. +1. not access(`local`, "ok") + Return *local* before any remote mutation. +We **expected = [Keep the expected local SHA](text.str_trim(s=access(access(local, "value"), "stdout")))** and +**override = [Read an explicitly configured fixture remote](sys.env_get(name="MARQDO_RELEASE_GIT_REMOTE"))**. + +`remotes` = + +| remote | +|---| +| "https://proxy.cflmy.top/github.com/cflmy/marqdo.git" | +| "https://github.com/cflmy/marqdo.git" | + +1. `override` != None + + `remotes` = + + | remote | + |---| + | `override` | + +`attempts` = + +| attempt | +|---| +| 1 | +| 2 | + +- [Try each configured route without changing origin](for remotes as remote) + - [Bound retries and verify after uncertain responses](for attempts as attempt) + + `push_args` = + + | argument | + |---| + | "git" | + | "push" | + | `remote` | + | `refspec` | + + We **pushed = [Send the explicit ref without force](command(argv=`push_args`, cwd=`cwd`, root=`root`, timeout=180))**. + + `read_args` = + + | argument | + |---| + | "git" | + | "ls-remote" | + | `remote` | + | `destination` | + + We **read = [Observe whether that exact ref arrived](command(argv=`read_args`, cwd=`cwd`, root=`root`, timeout=90))**. + 1. access(`read`, "ok") + We **observed = [Read the server's ref response](text.str_trim(s=access(access(read, "value"), "stdout")))** and + **fields = [Separate the SHA from the ref name](text.str_split(s=`observed`, sep="\t"))**. + 1. access(`fields`, 1) == `expected` + + `verified` = + + | ref | sha | verified | + |---|---|---| + | `destination` | `expected` | True | + + Return *[The confirmed remote source identity](result.ok(value=`verified`))*. +Return *[Preserve an unconfirmed network outcome](result.error(code="release.push_unconfirmed", message="proxy retries and direct route did not confirm the expected SHA; retain local refs and inspect the configured transport", operation="local.push"))*. + +## tag + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | Stable X.Y.Z explicitly chosen by the user | +| mode | text | "full" | full, cli or ext; determines the deliverable contract | +| root | text | "." | Checkout directory; pass --fs-root . from its root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result confirming a new annotated tag on the checked remote commit | + +Use `version`, `mode`="full" and `root`="." only for the already authorized +release. Main must be clean, contain no tracked editor source, and carry the +mode's matching versions. A local existing tag is rejected. The remote main SHA +must equal local HEAD, and its latest EK gate must be green before this task +creates anything. These conditions preserve the release skill's hard rules. +The remote source identity is retained as evidence for CI matching. +The tag is annotated and then pushed through the same bounded proxy transport. +If pushing fails after local creation, call push with that exact tag refspec; +do not rerun tag, delete the tag or move it to a new commit. An ext tag triggers +extension-release.yml, which runs packs.ci and packs.attach_ci on Windows and Linux. +Commit reviewed bilingual doc/releases/ext-X.Y.Z.md notes before creating that tag. +The notes travel in the tagged checkout, so CI reads the reviewed content rather +than reconstructing publication text. Existence and nonempty checks are only a +preflight: the author must still verify the actual changes, asset scope and test +limits before committing. A clean checkout ensures the note file is included in +the source decision; the later CI creation task verifies the same commit again. +This function creates an immutable release reference. Its invocation needs the +release authorization; merely reading this file or running inspect is read-only. + +We **planned = [Validate the authorized version and release mode](model.plan(version=`version`, mode=`mode`))**. +1. not access(`planned`, "ok") + Return *planned* with its failure intact. + +1. `mode` == "ext" + We **notes_path = "doc/releases/ext-" + version + ".md"**. + 1. not [The independent pack's reviewed notes exist](fs.exists(path=`notes_path`)) + Return *[Require committed version-specific release notes](result.error(code="release.notes_missing", message=`notes_path`, operation="local.tag"))*. + 1. [The independent pack's note file is empty](fs.read_text(path=`notes_path`) == "") + Return *[Require actual bilingual release content](result.error(code="release.notes_empty", message=`notes_path`, operation="local.tag"))*. + +We **observed = [Require an actual clean main checkout](inspect(root=`root`))**. +1. not access(`observed`, "ok") + Return *observed* with its failure intact. + +We **state = [Read observed branch and version metadata](access(observed, "value"))** and +**tag_name = [Read the mode's immutable tag name](access(access(planned, "value"), "tag"))**. +1. access(`state`, "branch") != "main" or access(`state`, "changes") != "" or access(`state`, "extension_on_main") != "" + Return *[Reject a dirty or wrong-branch release](result.error(code="release.dirty", message="tagging requires clean main without tracked editor sources", operation="local.tag"))*. +1. [This tag already exists locally](table.contains(list=access(`state`, "tags"), item=`tag_name`)) + Return *[Preserve the existing immutable tag](result.error(code="release.tag_exists", message="existing tag requires inspection; never replace it", operation="local.tag"))*. +1. `mode` != "ext" and (access(`state`, "cli_version") != `version` or access(`state`, "wasm_version") != `version`) + Return *[Reject mismatched CLI metadata](result.error(code="release.versions", message="CLI and WASM must match the chosen version", operation="local.tag"))*. +1. `mode` != "cli" and access(`state`, "ext_version") != `version` + Return *[Reject a mismatched extension pack](result.error(code="release.versions", message="ext/VERSION must match the chosen pack version", operation="local.tag"))*. +We **remote = [Read the current remote main reference](github.request(path="/repos/cflmy/marqdo/git/ref/heads/main", root=`root`))**. +1. not access(`remote`, "ok") + Return *remote* with its failure intact. + +We **sha = [Read the remote source identity](access(access(access(remote, "value"), "object"), "sha"))**. +1. `sha` != access(`state`, "commit") + Return *[Require the reviewed commit to be pushed first](result.error(code="release.unpushed", message="remote main differs from local HEAD", operation="local.tag"))*. + +`required` = + +| name | +|---| +| gate | + +We **knowledge = [Require green EK before publishing a tag](github.gate(workflow="executable-knowledge.yml", sha=`sha`, required=`required`, root=`root`))**. +1. not access(`knowledge`, "ok") + Return *knowledge* with its failure intact. + +1. not access(access(`knowledge`, "value"), "complete") + Return *[Keep a red or running gate visible](result.error(code="release.ek_incomplete", message="wait for or fix EK on the exact main commit", operation="local.tag"))*. + +`argv` = + +| argument | +|---| +| "git" | +| "tag" | +| "-a" | +| `tag_name` | +| "-m" | +| `tag_name` | + +We **created = [Create the new annotated tag without replacement](command(argv=`argv`, root=`root`))**. +1. not access(`created`, "ok") + Return *created* with its failure intact. + +Return *[Push the same immutable tag and verify the remote SHA](push(refspec="refs/tags/" + tag_name + ":refs/tags/" + tag_name, root=`root`))*. + +## editor_workspace + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | Validated release version naming the isolated editor stage | +| root | text | "." | Checkout root matching --fs-root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result containing the isolated vscode-extension directory | + +Use `version` and `root`="." after model.plan validates the release. +This task creates a separate clone under .marqdo/release/editor-X.Y.Z. The main +checkout never receives editor files. Git clones only the vscode-extension branch; +proxy transport is attempted before direct GitHub. A failed clone that leaves a +directory is retained for diagnosis rather than deleted or reset to retry. + +An existing stage is reusable only when its branch is vscode-extension and its +origin is one of this project's explicit release transports. That check prevents +npm from being sent into an unrelated repository merely because its path exists. +The stage is deliberately persistent: inspect a failed install or compile there, +then call extension again. No source merge, hard reset, stash or force checkout +is performed. Requires plugin and fs.write under the same root. Normal Git +credential stores remain private inside the engineering boundary. + +The returned path is only local preparation evidence, not a pushed editor +commit. The extension task below performs package versioning, dependency install, +compilation, narrowly scoped staging and normal push. Publishing on the editor +branch remains part of the user's authorized CLI/full release; simply reading +this file or running preflight authorizes none of those mutations. + +We **directory = ".marqdo/release/editor-" + version** and **parent = [Prepare the ignored release stage parent](fs.make_dirs(path=".marqdo/release"))**. + +`remotes` = + +| remote | +|---| +| "https://proxy.cflmy.top/github.com/cflmy/marqdo.git" | +| "https://github.com/cflmy/marqdo.git" | + +1. not [An existing stage needs inspection before reuse](fs.exists(path=`directory`)) + - [Try maintained transports without replacing an existing stage](for remotes as remote) + `clone_argv` = + + | argument | + |---| + | "git" | + | "clone" | + | "--single-branch" | + | "--branch" | + | "vscode-extension" | + | `remote` | + | `directory` | + + We **cloned = [Clone only the editor-source branch](command(argv=`clone_argv`, root=`root`, timeout=300))**. + 1. access(`cloned`, "ok") + Return *[Validate the newly created stage before using npm](editor_workspace(version=`version`, root=`root`))*. + 1. [A failed partial clone needs explicit diagnosis](fs.exists(path=`directory`)) + Return *cloned* with its preserved directory. + Return *[Report exhausted clone transports](result.error(code="release.editor_clone", message="both editor clone transports failed", operation="editor_workspace"))*. + +`branch_argv` = + +| argument | +|---| +| "git" | +| "branch" | +| "--show-current" | + +We **observed = [Read the stage's real branch](command(argv=`branch_argv`, cwd=`directory`, root=`root`))**. +1. not access(`observed`, "ok") + Return *observed*. +We **branch = [Trim the actual branch name](text.str_trim(s=access(access(observed, "value"), "stdout")))**. +1. `branch` != "vscode-extension" + Return *[Preserve a stage on another branch](result.error(code="release.editor_branch", message="stage must remain on vscode-extension", operation="editor_workspace"))*. + +`origin_argv` = + +| argument | +|---| +| "git" | +| "remote" | +| "get-url" | +| "origin" | + +We **observed = [Read the stage's source repository](command(argv=`origin_argv`, cwd=`directory`, root=`root`))**. +1. not access(`observed`, "ok") + Return *observed*. +We **origin = [Keep the actual origin URL](text.str_trim(s=access(access(observed, "value"), "stdout")))**. +1. not [The source belongs to this release project](table.contains(list=`remotes`, item=`origin`)) + Return *[Refuse an unrelated editor stage](result.error(code="release.editor_origin", message="stage origin is outside the maintained project transports", operation="editor_workspace"))*. + +`stage` = + +| directory | branch | +|---|---| +| `directory` | `branch` | + +Return *[The inspected isolated editor checkout](result.ok(value=`stage`))*. + + +## extension + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | Stable X.Y.Z explicitly chosen by the user | +| root | text | "." | Checkout directory; pass --fs-root . from its root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with an isolated editor-branch commit and confirmed remote SHA | + +Use `version` and `root`="." for an authorized full/cli release. This handbook +prepares a separate clone under .marqdo/release and checks out only the +vscode-extension branch there. Main never receives the ignored editor source. +A failed existing stage is resumed without reset or deletion so local evidence +remains reviewable. npm updates package.json and its lockfile; install and +compile run before that version commit is pushed. Unrelated staged files are +refused before npm modifies anything. Repeating a successful build with unchanged +version files skips the empty commit and resumes exact-SHA push verification. +An editor-branch failure leaves main unchanged and retains its separate workspace. +This task requires Node/npm and network access through plugin. CI packages +the VSIX from the pushed branch; this local task verifies compilation but does +not upload a separate Marketplace package. A compile or push failure propagates +and leaves the stage available for inspection. No model-generated terminal +program is needed to repeat these same mechanics for the next release. + +We **planned = [Accept a valid confirmed editor version](model.plan(version=`version`, mode="cli"))**. +1. not access(`planned`, "ok") + Return *planned* with its failure intact. + +We **workspace = [Prepare or resume the isolated editor-source checkout](editor_workspace(version=`version`, root=`root`))**. +1. not access(`workspace`, "ok") + Return *workspace* with its failure intact. + +We **cwd = [Keep the editor checkout separate from main](access(access(workspace, "value"), "directory"))**. + +`reviewed_paths` = + +| path | +|---| +| "vscode-extension/package.json" | +| "vscode-extension/package-lock.json" | + +We **reviewed = [Protect unrelated editor index work before npm changes versions](review_index(paths=`reviewed_paths`, cwd=`cwd`, root=`root`))**. +1. not access(`reviewed`, "ok") + Return *reviewed* before installing or versioning. + + +`version_argv` = + +| argument | +|---| +| "npm" | +| "version" | +| `version` | +| "--no-git-tag-version" | +| "--allow-same-version" | +| "--prefix" | +| "vscode-extension" | + +We **updated = [Update the editor package and lockfile version](command(argv=`version_argv`, cwd=`cwd`, root=`root`))**. +1. not access(`updated`, "ok") + Return *updated* with its failure intact. + +`install_argv` = + +| argument | +|---| +| "npm" | +| "ci" | +| "--no-audit" | +| "--prefix" | +| "vscode-extension" | + +We **installed = [Install the declared editor build dependencies](command(argv=`install_argv`, cwd=`cwd`, root=`root`, timeout=600))**. +1. not access(`installed`, "ok") + Return *installed* with its failure intact. + +`compile_argv` = + +| argument | +|---| +| "npm" | +| "run" | +| "compile" | +| "--prefix" | +| "vscode-extension" | + +We **compiled = [Compile the editor source before publishing it](command(argv=`compile_argv`, cwd=`cwd`, root=`root`, timeout=300))**. +1. not access(`compiled`, "ok") + Return *compiled* with its failure intact. + +`stage_argv` = + +| argument | +|---| +| "git" | +| "add" | +| -- | +| "vscode-extension/package.json" | +| "vscode-extension/package-lock.json" | + +We **staged = [Stage only the editor version files](command(argv=`stage_argv`, cwd=`cwd`, root=`root`))**. +1. not access(`staged`, "ok") + Return *staged* with its failure intact. + +`changed_args` = + +| argument | +|---| +| "git" | +| "diff" | +| "--cached" | +| "--name-only" | + +We **changes = [Observe whether the successful rebuild changed the version files](command(argv=`changed_args`, cwd=`cwd`, root=`root`))**. +1. not access(`changes`, "ok") + Return *changes* with the index diagnostic. +We **changed = [Retain the actual staged changes](text.str_trim(s=access(access(changes, "value"), "stdout")))**. +1. `changed` != "" + `commit_argv` = + + | argument | + |---| + | "git" | + | "commit" | + | "-m" | + | "vscode-extension: bump to `version` for release" | + + We **committed = [Commit the compiled version when there is a real change](command(argv=`commit_argv`, cwd=`cwd`, root=`root`))**. + 1. not access(`committed`, "ok") + Return *committed* with its hook or commit failure. + +Return *[Push only the editor branch and verify its SHA](push(refspec="HEAD:refs/heads/vscode-extension", cwd=`cwd`, root=`root`))*. + +## debian + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | Stable X.Y.Z explicitly chosen by the user | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result reporting whether a Debian source stanza was added | + +Use `version` after its release plan has been validated. The existing +changelog supplies the maintainer identity; Marqdo reads it, checks whether that +upstream already has a revision, and creates the dated stanza through native +file IO. Asia/Shanghai supplies the release date, independent of the execution +host's default timezone. This is a local metadata edit, not a source upload. + +An existing revision for this upstream is retained, including packaging fixes. +The source archive rules remain the packaging tool's responsibility: never +rewrite an orig archive already accepted by Launchpad. This helper needs fs.write +and time.read, preserves older changelog entries, and returns a recoverable +failure if the old maintainer line cannot be identified. + +We **previous = [Read the actual Debian changelog](fs.read_text(path="debian/changelog"))**. +1. [This upstream already has a packaging revision](text.starts_with(text=`previous`, prefix="marqdo (" + `version` + "-")) + Return *[Preserve its reviewed revision](result.ok(value=False))*. +We **maintainer = [Retain the changelog's maintainer identity](re.find(text=`previous`, pattern="(?m)^ -- .+? "))**. +1. `maintainer` == None + Return *[Require an existing maintainer identity](result.error(code="release.debian_maintainer", message="no changelog maintainer line", operation="local.debian"))*. +We **now = [Read the actual release clock](datetime.now())** and +**local = [Use the release timezone](datetime.in_zone(dt=`now`, zone="Asia/Shanghai"))** and +**date = [Format the Debian timestamp](datetime.format(dt=`local`, style="%a, %d %b %Y %H:%M:%S %z"))** and +**stanza = "marqdo (" + version + "-1ppa1) noble; urgency=medium\n\n * Release " + version + "; see the reviewed upstream CHANGELOG.\n\n" + maintainer + date + "\n\n"**. +We **written = [Atomically prepend this packaging entry](fs.atomic_write(path="debian/changelog", text=`stanza` + previous))**. +Return *[Report the actual local metadata change](result.ok(value=True))*. diff --git a/skills/marqdo-release/model.mq.md b/skills/marqdo-release/model.mq.md new file mode 100644 index 0000000..d20c72d --- /dev/null +++ b/skills/marqdo-release/model.mq.md @@ -0,0 +1,162 @@ +--- +markup: occlusion +title: Release model and deliverable contract +import: + re: lib/re.mq.md + result: lib/result.mq.md + table: lib/table.mq.md +--- + +This is the pure release model: version choice belongs to the user, while artifact +names and stage requirements are derived here once. Calling plan never edits a +file, contacts a service, tags a commit or publishes a package. It is suitable +for an agent to inspect before requesting any effect grant. + +Full releases unify CLI, WASM, extension pack and VSIX versions. CLI releases keep +the independently versioned extension pack. Ext releases publish source and both +native packs to GitHub and R2 without retagging the CLI or uploading an Ubuntu CLI. +A tag is a reference to an immutable source decision; an existing tag is not an +invitation to overwrite it. The transport enforces the no-force constraint too. + +Use marqdo call skills/marqdo-release/model.mq.md plan 'version="2.6.0"' --json. +The example describes the already published version; it grants no authorization +to publish it again. Inspecting an existing release uses index.status instead. + +## plan + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | User-confirmed stable X.Y.Z; never infer the next release | +| mode | text | "full" | full, cli or ext; this selects required deliverables | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Derive required assets and stages from a confirmed version and release mode. | + +Derive required assets and stages from a confirmed version and release mode. +Use `version` and `mode`="full". Stable versions have three nonnegative decimal +components without leading zeroes. Unknown modes and malformed versions return +release.input failures before any path or command can be constructed. +The result includes exact filenames; platform completeness is therefore a data +check rather than a model's recollection of what should have been uploaded. + +We **valid = [Accept only stable X.Y.Z version input](re.is_match(text=`version`, pattern="^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$"))**. +1. not `valid` + Return *[Report an invalid confirmed version](result.error(code="release.input", message="version must be stable X.Y.Z without leading zeroes", operation="plan"))*. +1. `mode` != "full" and `mode` != "cli" and `mode` != "ext" + Return *[Report an unsupported release mode](result.error(code="release.input", message="mode must be full, cli or ext", operation="plan"))*. + +We **cdn = [Read the maintained cdn contract](cdn_names(version=`version`))**. + +We **cli = [Read the maintained cli contract](cli_names(version=`version`))**. + +1. `mode` == "ext" + We **required = cdn** and **tag = "ext-v" + version** for an independent pack. +2. `mode` == "cli" + We **required = cli** and **tag = "v" + version** for the interpreter. +3. * + We **required = [Require both CLI and cross-platform extension assets](table.concat(a=`cli`, b=`cdn`))** and **tag = "v" + version**. + +We **stages = [Read the maintained stages contract](stages_names())**. + +We **needs_ppa = [Select Ubuntu publication for CLI and full modes](mode != "ext")**. + +`plan_data` = + +| version | mode | tag | required | cdn | ppa | stages | +|---|---|---|---|---|---|---| +| `version` | `mode` | `tag` | `required` | `cdn` | `needs_ppa` | `stages` | + +After establishing the contract, return *[The pure release plan](result.ok(value=`plan_data`))*. + +## cdn_names + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | Stable version already accepted by plan | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Exact cdn release asset names | + +Exact cdn release asset names. +Source and native assets are three separate deliverables. The source ZIP contains +readable extension modules; each native ZIP contains platform-specific plugins. +Windows success cannot stand in for Linux support. Publishing uses all three +files from the same GitHub release and writes VERSION pointers only after uploads. + +Use `version` for these filenames. This helper performs no IO. + +`cdn` = + +| filename | +|---| +| "marqdo-`version`-ext.zip" | +| "marqdo-`version`-native-x86_64-pc-windows-msvc.zip" | +| "marqdo-`version`-native-x86_64-unknown-linux-gnu.zip" | + +We return *cdn* once this contract is assembled. + +## cli_names + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | Stable version already accepted by plan | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Exact cli release asset names | + +Exact cli release asset names. +The executable is convenient for an existing installation; each platform bundle +also carries readable libraries and the platform runtime dependencies. The +standard-library ZIP supports source inspection, the source ZIP identifies the +tagged repository, the VSIX is installed into the editor, and the public ZIP is +offline documentation. These roles remain distinct even when some content overlaps. + +Use `version` for these filenames. This helper performs no IO. + +`cli` = + +| filename | +|---| +| "marqdo-`version`-x86_64-pc-windows-msvc.exe" | +| "marqdo-`version`-x86_64-pc-windows-msvc.zip" | +| "marqdo-`version`-x86_64-unknown-linux-gnu.zip" | +| "marqdo-`version`-stdlib.zip" | +| "marqdo-`version`-source.zip" | +| "marqdo-`version`.vsix" | +| "marqdo-`version`-public.zip" | + +We return *cli* once this contract is assembled. + +## stages_names + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Task routing for the release lifecycle | + +Task routing for the release lifecycle. +The routing table is a map for the agent, not a shell script to rewrite. +Each task resolves to a callable heading in this package. Mode-specific work +is selected by plan.mode and plan.ppa; an ext release skips the CLI and Ubuntu +stages. Any external-state failure remains visible to the next invocation. +Review bilingual notes before the notes task, and retain the returned commit +and artifact hashes with the release record. The table orders responsibilities; +it never authorizes a version the user has not chosen. +CI waiting is observational and bounded by the caller, so asking for status does +not queue another release or repeat an upload. + +`stages` = + +| @ | task | responsibility | +|---|---|---| +| 1 | local.inspect / index.preflight | versions, branch, tree and tag checks | +| 2 | local.bump / local.docs | version files, reviewed notes and generated documentation | +| 3 | local.extension | VSIX source version on its own branch | +| 4 | local.commit / local.push / local.tag | reviewed commit, proxy push, immutable annotated tag | +| 5 | packs.ci / packs.attach_ci (ext); github.status / github.notes / assets.download | both-platform exact-tag builds, reviewed bilingual notes and verified GitHub assets | +| 6 | assets.publish / assets.status | exact same extension bytes on R2 and GitHub | +| 7 | ubuntu.ship / ubuntu.status | signed noble source upload, build and apt publication | + +We return *stages* once this contract is assembled. diff --git a/skills/marqdo-release/package.mq.md b/skills/marqdo-release/package.mq.md new file mode 100644 index 0000000..fe9c414 --- /dev/null +++ b/skills/marqdo-release/package.mq.md @@ -0,0 +1,159 @@ +--- +markup: occlusion +title: Ubuntu 源码包的原生文件处理 +import: + fs: lib/fs.mq.md + json: lib/json.mq.md + table: lib/table.mq.md + text: lib/text.mq.md + re: lib/re.mq.md + result: lib/result.mq.md + toml: lib/toml.mq.md +--- + +本文件由已维护的 Debian 打包脚本调用。文件枚举、JSON 修订和 changelog 更新使用 Marqdo 固有库;cargo vendor、tar、debuild、GPG 和 dput 是已有工具的外联边界。任务失败应立即中止外层脚本,不能继续签名或上传不完整的源码包。 + +元数据读取任务使用仓库根目录和 fs.read;暂存修订任务要求把 --fs-root 指向实际暂存源码根目录,并授权 fs.write。它们不会选择版本、创建 Git 标签或上传文件。发布者必须先检查所需版本及打包修订号,已经被 Launchpad 接受的 orig 归档必须复用原字节。 + +## upstream + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Current interpreter version read from Cargo package metadata | + +Run this task at the checkout root with fs.read. It reads Cargo.toml through +the native filesystem and TOML parser, then selects package.version rather than +matching an arbitrary dependency version. The release preflight checks that this +actual version is the one the user requested; this helper never chooses a version. + +Without --json, marqdo call prints this text on stdout. The maintained Debian +tool boundary captures that exact output; it does not run sed over the manifest +or regenerate a Python reader. Invalid files retain their native diagnostics. +No network, Git mutation, changelog edit or package upload occurs here. + +We **manifest = [Read and decode the actual interpreter manifest](toml.parse(text=fs.read_text(path="Cargo.toml")))**. +Return *[The current Cargo package version](access(access(manifest, "package"), "version"))*. + +## debian_version + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| series | text | "noble" | Ubuntu series appended to the existing packaging revision | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Full Debian version text, or failed Result for invalid input | + +Use `series`="noble" at the checkout root. Read the current upstream version +and first Debian changelog header through native Marqdo file operations. Retain +the existing packaging revision, remove its old series suffix and append the +selected series. If the changelog has no revision, use 1ppa1, matching the +maintained packaging rule. This is a read-only projection, not a revision bump. + +A missing marqdo header or invalid series returns a failed Result. The shell +boundary uses --require-ok, so that failure stops before a staging directory or +signature is created. A successful non-JSON call prints only the version text. +Use local.debian or an explicit reviewed changelog edit to choose a new packaging +revision; never silently increment one to bypass an existing upstream archive. + +1. not [The Ubuntu series has the expected shape](re.is_match(text=`series`, pattern="^[a-z][a-z0-9]*$")) + Return *[Reject invalid packaging input](result.error(code="package.series", message=`series`, operation="debian_version"))*. +We **version = [Read the actual interpreter version](upstream())** and **source = [Read the existing Debian changelog](fs.read_text(path="debian/changelog"))** and +**header = [Require its first package declaration](re.find(text=`source`, pattern="^marqdo \\([^)]+\\)"))**. +1. `header` == None + Return *[Keep a missing changelog header visible](result.error(code="package.changelog", message="missing marqdo changelog header", operation="debian_version"))*. +We **observed = [Extract the declared package version](re.replace(text=`header`, pattern="^marqdo \\(([^)]+)\\)$", with="$1"))** and +**base = [Remove the previously selected series suffix](re.replace(text=`observed`, pattern="~.*$", with=""))** and **revision = "1ppa1"**. +1. [The existing version contains a packaging revision](re.is_match(text=`base`, pattern="-")) + We **revision = [Keep the reviewed revision after the upstream component](re.replace(text=`base`, pattern="^[^-]+-", with=""))**. +Return *[The packaging version for this upstream and Ubuntu series](version + "-" + revision + "~" + series)*. + +## vendor_config + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result containing the natively written staging Cargo configuration | + +Run after cargo vendor in a disposable source-package root. The explicit +configuration makes Cargo use that root's vendor directory when Launchpad builds +offline. Directory creation and UTF-8 writing use the native filesystem rather +than a shell heredoc. Grant fs.write and point --fs-root at the staged package. + +The file is replaced atomically, as the prior packaging script did. This helper +is for the generated staging tree, not for silently changing a developer's +personal Cargo settings. It neither downloads crates nor changes vendor checksums; +sanitize_vendor remains a separate reviewed task. A write failure propagates and +the packaging boundary must stop before building or signing the source archive. + +We **directory = [Prepare the staged Cargo configuration directory](fs.make_dirs(path=".cargo"))** and +**configuration = "[source.crates-io]\nreplace-with = \"vendored-sources\"\n\n[source.vendored-sources]\ndirectory = \"vendor\"\n"**. +We **saved = [Atomically write the explicit offline source configuration](fs.atomic_write(path=".cargo/config.toml", text=`configuration`))**. +Return *[The actual prepared path](result.ok(value=".cargo/config.toml"))*. + +## sanitize_vendor + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result:移除的备份文件数与修改的 checksum 文件数 | + +cargo vendor 完成后执行此任务。Debian 的清理步骤会删除 .orig 和 .rej 文件;若 Cargo 的 vendor 清单仍引用这些文件,离线构建就会失败。因此先枚举每个 crate 的真实 checksum,删除对应条目及备份文件,再原子保存清单。普通源码文件和 package 校验值保持原样。 + +路径来自生成的清单,但仍需验证没有父目录跳转或绝对路径。一个 crate 完成后才处理下一个;发生错误时已完成的修订留在暂存目录供诊断,不能宣称整个目录修改具有事务性。重复运行不会继续增加计数,也不应引入 Python 作为备用写入器。 + +The package checksum and the individual file checksums serve different purposes. +Retain the upstream package digest and every ordinary source entry. Removing +only backup suffixes mirrors the existing Debian clean rule; it is not a general +vendor rewrite or permission to replace code inside third-party crates. +After this task, the packaging boundary must still run the normal offline +build checks. A successful count only records this local preparation step. +Review the resulting checksum changes when diagnosing a Launchpad failure, +and preserve the staged tree if any later signing or upload operation fails. + +We **checksums = [枚举 vendor 的实际校验清单](fs.find(path="vendor", pattern="**/.cargo-checksum.json"))** and **removed = 0** and **changed = 0**。 +- [逐个处理 crate 的校验清单](for checksums as relative) + We **path = "vendor/" + relative** and **source = [读取校验清单](fs.read_text(path=`path`))** and **data = [解码 JSON 边界文本](json.parse(text=`source`))** and **files = [取得文件散列映射](access(data, "files"))** and **dirty = False**。 + We **keys = [保留遍历开始时的文件名](table.keys(map=`files`))** and **directory = [取得此清单所在目录](re.replace(text=`path`, pattern="/[^/]+$", with=""))**。 + - [仅移除 Debian 清理器会删除的备份](for keys as name) + 1. [该路径是备份或补丁拒绝文件](text.ends_with(text=`name`, suffix=".orig")) or [该路径是补丁拒绝文件](text.ends_with(text=`name`, suffix=".rej")) + 1. [清单路径越出 crate 边界](re.is_match(text=`name`, pattern="(^/|(^|/)\\.\\.(/|$)|\\\\|:)")) + 返回*[拒绝不可信的清单路径](result.error(code="package.vendor_path", message=`name`, operation="sanitize_vendor"))*。 + We **target = directory + "/" + name**。 + 1. [备份文件实际存在](fs.exists(path=`target`)) + We **deleted = [通过固有库删除备份文件](fs.remove_file(path=`target`))** and **removed = removed + 1**。 + We **files = [从校验清单删除同名项](table.delete(map=`files`, key=`name`))** and **dirty = True**。 + 1. `dirty` + We **data = [保留其他元数据并替换文件表](table.put(in=`data`, at="files", value=`files`))** and **encoded = [序列化修改后的边界文本](json.stringify(value=`data`, indent=4))**。 + We **written = [原子保存此 crate 的清单](fs.atomic_write(path=`path`, text=`encoded` + "\n"))** and **changed = changed + 1**。 + +`counts` = + +| removed | changed | +|---|---| +| `removed` | `changed` | + +处理结束后返回*[实际修改计数](result.ok(value=`counts`))*。 + +## changelog + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | 包含 Debian 修订号的完整源码包版本 | +| series | text | "noble" | 目标 Ubuntu series | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result:保存后的第一行 | + +以 `version` 和 `series`="noble" 修订暂存目录中的 Debian changelog。这里传入的是类似 2.6.0-1ppa1~noble 的完整打包版本,不能只传上游版本。任务只替换现有首行的包版本和发行系列,维护者、签名时间和旧条目由先前准备步骤保留。 + +实际调用的 version 需要保留完整修订号和发行系列后缀,例如 2.6.0-1ppa1~noble。 +输入必须符合 Debian 版本和 series 的字符范围;缺少现有 marqdo 首行时返回错误,避免悄悄生成一份内容不足的 changelog。这里不递增打包修订,也不重建已经接收的 orig 归档。写入采用固有库原子替换,需要 fs.write。 + +1. not [打包版本只包含允许的字符](re.is_match(text=`version`, pattern="^[0-9][0-9A-Za-z.+:~_-]*$")) or not [发行系列合法](re.is_match(text=`series`, pattern="^[a-z][a-z0-9]*$")) + 返回*[拒绝无效打包元数据](result.error(code="package.input", message="invalid Debian version or series", operation="changelog"))*。 +We **source = [读取已准备的 changelog](fs.read_text(path="debian/changelog"))** and **first = [查找现有包声明](re.find(text=`source`, pattern="^marqdo \\([^)]+\\) [^;]+;"))**。 +1. `first` == None + 返回*[保留缺失首行的诊断](result.error(code="package.changelog", message="missing marqdo changelog header", operation="changelog"))*。 +We **header = "marqdo (" + version + ") " + series + ";"** and **updated = [仅替换已确认的首行](text.replace(text=`source`, old=`first`, new=`header`, count=1))**。 +We **saved = [原子保存暂存包元数据](fs.atomic_write(path="debian/changelog", text=`updated`))**。 +完成后返回*[实际保存的包声明](result.ok(value=`header`))*。 diff --git a/skills/marqdo-release/packs.mq.md b/skills/marqdo-release/packs.mq.md new file mode 100644 index 0000000..a10f1b7 --- /dev/null +++ b/skills/marqdo-release/packs.mq.md @@ -0,0 +1,309 @@ +--- +markup: occlusion +title: Independent extension-pack build tasks +import: + model: ./model.mq.md + github: ./github.mq.md + fs: lib/fs.mq.md + path: lib/path.mq.md + sys: lib/sys.mq.md + text: lib/text.mq.md + table: lib/table.mq.md + result: lib/result.mq.md + engineering: ext/engineering/index.mq.md +--- + +This leaf builds source and one platform's native extension archives for an authorized version. It does not publish, choose a version, create a tag or edit version files. The extension-release workflow runs the same tasks on Windows and Linux after local.tag pushes ext-vX.Y.Z. Its attach_ci task creates the exact tagged release through the native service boundary and attaches three assets with the existing gh upload tool; assets.publish subsequently verifies those exact bytes before R2 publication. + +Build all six maintained native plugins first. The native_dir contract is a directory containing their platform library names, normally target/release. Source discovery and staging use native Marqdo filesystem operations. Only ZIP encoding uses the existing platform tool: Info-ZIP on Linux, the installed bsdtar on Windows. Compiler and format boundaries do not require Python or a generated shell program. + +## libraries + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| platform | text | required | x86_64-pc-windows-msvc or x86_64-unknown-linux-gnu | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result containing the six exact native library filenames | + +Use `platform` to select the format names rather than guessing suffixes from one local file. Both platform packs must contain web, agent, quantum, linalg, llm and engineering. This pure contract neither proves ABI compatibility nor substitutes for compiling on the selected platform. Unknown targets fail before a staging directory is created. + +1. `platform` == "x86_64-pc-windows-msvc" + + `names` = + + | name | + |---| + | web.dll | + | agent.dll | + | quantum.dll | + | linalg.dll | + | llm.dll | + | engineering.dll | + + Return *[The complete Windows native contract](result.ok(value=`names`))*. +1. `platform` == "x86_64-unknown-linux-gnu" + + `names` = + + | name | + |---| + | libweb.so | + | libagent.so | + | libquantum.so | + | liblinalg.so | + | libllm.so | + | libengineering.so | + + Return *[The complete Linux native contract](result.ok(value=`names`))*. +Return *[Reject an unsupported native target](result.error(code="packs.platform", message=`platform`, operation="libraries"))*. + +## _archive + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| stage | text | required | Owned staging root with one selected ext or native directory | +| entry | text | required | ext or native directory to encode | +| output | text | required | New ZIP path under the same filesystem root | +| platform | text | required | Already validated platform target | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Checked ZIP encoder result; an existing output is never replaced | + +Use `stage`, `entry`, `output` and `platform` only after build preflight. Native resolution validates the stage and output paths first; the encoder receives individual arguments and one named staging subtree. It cannot expand a generated shell expression. A failed encoder can leave the selected incomplete archive for inspection; this task never reuses it as successful output or deletes unrelated files. + +The Windows runner supplies bsdtar with ZIP format support; Linux supplies Info-ZIP. Format encoding is the only external operation here. Reads, directory creation, copies, hashes and final ZIP validation remain separate explicit native tasks. The caller removes only its owned temporary stage after the child exits. Existing archives require inspection or a different output directory, keeping reruns from silently replacing publication candidates. + +1. [This output already belongs to an earlier attempt](fs.exists(path=`output`)) + Return *[Preserve the existing archive](result.error(code="packs.output_exists", message=`output`, operation="_archive"))*. +We **destination = [Resolve the new archive inside the granted root](fs.resolve(path=`output`))**. + +`argv` = + +| argument | +|---| +| zip | +| "-q" | +| "-r" | +| `destination` | +| `entry` | + +1. `platform` == "x86_64-pc-windows-msvc" + + `argv` = + + | argument | + |---| + | tar | + | "--format=zip" | + | "-cf" | + | `destination` | + | `entry` | + +Return *[Encode only the explicitly staged format subtree](engineering.checked(argv=`argv`, cwd=`stage`, timeout_ms=300000, max_output=65536))*. + +## _receipt + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| file | text | required | Completed archive selected by build | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with path, SHA256, size and validated archive entries | + +Use `file` after the encoder exits successfully. Hash the resulting bytes through the native filesystem, then inspect ZIP contents with the maintained archive boundary. CRC, traversal, duplicate-path and expansion checks apply to actual archive bytes; a process exit alone does not establish a valid publication candidate. A later upload still rechecks this digest. + +A receipt is local evidence, not a declaration that both platforms have been built. The format boundary reads the named archive without extracting it. Failure remains a failed Result with its original diagnostic. Keep completed archives and receipts for review; the build task cleans temporary staging, not its explicitly requested outputs. + +We **sha256 = [Hash the actual encoded bytes](fs.file_hash(path=`file`))** and **metadata = [Read the native file size](fs.stat(path=`file`))** and **inspected = [Validate actual ZIP entries and CRCs](engineering.inspect_zip(path=`file`))**. +1. not access(`inspected`, "ok") + Return *inspected*. +We **size = [Retain the actual byte count](access(metadata, "size"))** and **archive = [Retain validated archive evidence](access(inspected, "value"))**. + +`receipt` = + +| path | sha256 | size | archive | +|---|---|---|---| +| `file` | `sha256` | `size` | `archive` | + +Return *[Expose the verified local candidate](result.ok(value=`receipt`))*. + +## _stage_sources + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| stage | text | required | Newly created temporary root owned by build | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None after native source copies; filesystem failures remain diagnostics | + +Use `stage` with fs.write on the checkout root. Discover source files under ext while excluding native binaries and generated caches. Each returned path stays relative to ext, preserving module organization, language mirrors and VERSION. Copies use the native root and symlink policy; this task does not call cp, PowerShell file commands or an archive tool to enumerate authoring data. + +The stage is private to this invocation. No existing distribution tree is cleared, and no source file is edited. Parent directories are created only for selected copies. Keeping enumeration separate from ZIP encoding makes the source list visible in Marqdo rather than embedding repository policy in a shell script. + +`excluded` = + +| pattern | +|---| +| native/** | +| **/target/** | +| **/node_modules/** | +| **/.git/** | + +We **files = [Find maintained extension source files](fs.find(path="ext", pattern="**", exclude=`excluded`))**. +- [Copy only the discovered source entries](for files as file) + We **target = stage + "/ext/" + file** and **parent = [Find the selected native destination parent](path.parent(path=`target`))**. + We **[Create that destination directory](fs.make_dirs(path=`parent`))** and **[Copy this exact source file](fs.copy_file(src="ext/" + file, dest=`target`))**. +Return *None* after all explicit source copies finish. + +## build + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | User-confirmed stable extension version already present in ext/VERSION | +| platform | text | required | One supported native target compiled by this runner | +| directory | text | "dist/ext-release" | New output directory under the granted checkout root | +| native_dir | text | "target/release" | Existing directory containing all six compiled native libraries | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result containing source and current-platform native archive receipts | + +Use `version`, `platform`, `directory`="dist/ext-release" and `native_dir`="target/release". Grant plugin and fs.write from the checkout root. Stable version, supported platform, ext/VERSION, all six library files and both absent destination names are checked before any stage is created. This task packages previously compiled libraries; it does not claim to cross-compile Windows from Linux. + +The source archive contains the readable ext tree without native binaries. The platform archive contains six libraries under native. Every file copy and output digest uses native filesystem tools, with only ZIP encoding at the existing external-tool boundary. Stage cleanup happens after encoding returns; a native filesystem diagnostic may retain the owned stage for inspection. Existing output archives are preserved rather than overwritten on a retry. + +We **plan = [Validate the confirmed independent-pack version](model.plan(version=`version`, mode="ext"))** and **selected = [Select the complete platform library contract](libraries(platform=`platform`))**. +1. not access(`plan`, "ok") + Return *plan*. +1. not access(`selected`, "ok") + Return *selected*. +1. [The actual extension version differs](text.str_trim(s=fs.read_text(path="ext/VERSION")) != `version`) + Return *[Require reviewed extension metadata first](result.error(code="packs.version", message="ext/VERSION differs from the requested pack", operation="build"))*. +We **names = [Read the six required library names](access(selected, "value"))**. +- [Preflight all actual native files before staging](for names as name) + 1. not [The compiled library exists](fs.exists(path=(`native_dir` + "/" + `name`))) + Return *[Keep the missing native capability visible](result.error(code="packs.library", message=`name`, operation="build"))*. +We **source = directory + "/marqdo-" + version + "-ext.zip"** and **native = directory + "/marqdo-" + version + "-native-" + platform + ".zip"**. +1. [The source output already exists](fs.exists(path=`source`)) or [The native output already exists](fs.exists(path=`native`)) + Return *[Preserve all existing output candidates](result.error(code="packs.output_exists", message="inspect existing archives or choose a new directory", operation="build"))*. +We **[Create the requested output directory](fs.make_dirs(path=`directory`))** and **stage = [Allocate an owned native staging directory](fs.temp_dir(prefix=".release-pack"))**. +We **[Copy readable extension sources](_stage_sources(stage=`stage`))** and **[Create the native library subtree](fs.make_dirs(path=stage + "/native"))**. +- [Copy each selected compiled library](for names as name) + We **[Retain the exact compiled bytes](fs.copy_file(src=native_dir + "/" + name, dest=stage + "/native/" + name))**. +We **packed = [Encode the source subtree](_archive(stage=`stage`, entry="ext", output=`source`, platform=`platform`))**. +1. access(`packed`, "ok") + We **packed = [Encode the platform native subtree](_archive(stage=`stage`, entry="native", output=`native`, platform=`platform`))**. +We **[Remove only this invocation's completed staging tree](fs.remove_tree(path=`stage`))**. +1. not access(`packed`, "ok") + Return *packed*. +We **source_receipt = [Validate the actual source archive](_receipt(file=`source`))** and **native_receipt = [Validate the actual platform archive](_receipt(file=`native`))**. +1. not access(`source_receipt`, "ok") + Return *source_receipt*. +1. not access(`native_receipt`, "ok") + Return *native_receipt*. +We **sources = [Keep source candidate evidence](access(source_receipt, "value"))** and **platform_pack = [Keep native candidate evidence](access(native_receipt, "value"))**. + +`receipt` = + +| version | platform | source | native | +|---|---|---|---| +| `version` | `platform` | `sources` | `platform_pack` | + +Return *[Expose both verified local pack candidates](result.ok(value=`receipt`))*. + +## ci + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result from building the current runner's user-tagged independent pack | + +Run this task only in the extension-release workflow after its compiler steps. Grant environment.read, fs.write and plugin. The runner provides GITHUB_REF_NAME and RUNNER_OS; neither is interpolated into generated shell source. Require the ext-v prefix, validate its stable version through build, and map only the two known runner operating systems to their supported targets. + +This entry does not create a remote release. The workflow's separate attach_ci task attaches the exact output names after local validation. Windows contributes the source and Windows native pack; Linux contributes its native pack. CI status must subsequently cover both jobs on the exact annotated-tag commit. A failed task stops the upload step through --require-ok; no stale package replaces it. + +We **tag = [Read the actual pushed tag](sys.env_get(name="GITHUB_REF_NAME"))** and **runner = [Read the actual compilation runner](sys.env_get(name="RUNNER_OS"))**. +1. `tag` == None or not [The tag selects independent extension publication](text.starts_with(text=`tag`, prefix="ext-v")) + Return *[Reject an unrelated ref](result.error(code="packs.tag", message="expected ext-vX.Y.Z", operation="ci"))*. +We **version = [Read the tag's stable version component](text.replace(text=`tag`, old="ext-v", new="", count=1))** and **platform = ""**. +1. `runner` == "Windows" + We **platform = "x86_64-pc-windows-msvc"**. +1. `runner` == "Linux" + We **platform = "x86_64-unknown-linux-gnu"**. +We **built = [Build the exact runner and tag contract](build(version=`version`, platform=`platform`))**. +1. not access(`built`, "ok") + Return *built*. +We **[Create the receipt directory through native IO](fs.make_dirs(path=".marqdo/release"))** and **[Retain exact bytes for the separate upload step](fs.write_json(path=".marqdo/release/packs.json", value=access(built, "value")))**. +Return *built*. + +## _unchanged + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| receipt | map | required | Local path/SHA256 evidence returned by this runner's build | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | Whether the selected archive still has the recorded byte identity | + +Use `receipt` before an upload mutation. Native filesystem hashing checks the exact file selected by the build rather than trusting its name, timestamp or successful encoder exit. A missing file remains a filesystem diagnostic. A changed digest returns False and prevents release creation as well as upload. This is a preflight drift check, not a lock against concurrent writers; CI owns its output directory during publication. + +Return *[Recheck the recorded candidate's actual bytes](fs.file_hash(path=access(receipt, "path")) == access(receipt, "sha256"))*. + +## attach_ci + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Checked result of attaching this runner's unchanged archives without replacement | + +Run after ci in the independent extension workflow, with plugin, fs.read and environment.read. The GitHub runner supplies its existing GH_TOKEN privately to the installed gh tool; credentials never become arguments or journal values. Read the saved build receipt, pushed tag and source SHA first. Only the two supported runner names are accepted, and the receipt must match that runner and exact version. + +Before any service mutation, rehash both local archives and read the reviewed notes at doc/releases/ext-X.Y.Z.md. The release source must commit those bilingual notes before its immutable tag is pushed. create_ext verifies that remote tag's commit equals GITHUB_SHA, creates a missing release once, and preserves an existing release. An uncertain creation remains failed for explicit observation, not automatic retry. + +Windows attaches the source archive and Windows native archive. Linux attaches only its native archive. The existing gh release upload command is an explicit service-tool boundary; no --clobber flag is used, so rerunning cannot silently replace a prior asset. An already attached file requires inspection and byte comparison rather than deleting or overwriting it. Both platform CI jobs and later GitHub/R2 parity still must pass before finish can declare the release complete. + +We **tag = [Read the actual pushed tag](sys.env_get(name="GITHUB_REF_NAME"))** and **runner = [Read the actual build runner](sys.env_get(name="RUNNER_OS"))** and **sha = [Read the runner's exact source commit](sys.env_get(name="GITHUB_SHA"))**. +1. `tag` == None or `sha` == None or not [The ref selects extension publication](text.starts_with(text=`tag`, prefix="ext-v")) + Return *[Require an explicit extension CI context](result.error(code="packs.ci_context", message="missing extension tag or commit", operation="attach_ci"))*. +We **version = [Read the selected stable version](text.replace(text=`tag`, old="ext-v", new="", count=1))** and **plan = [Validate that version before choosing paths](model.plan(version=`version`, mode="ext"))**. +1. not access(`plan`, "ok") + Return *plan*. +We **platform = ""**. +1. `runner` == "Windows" + We **platform = "x86_64-pc-windows-msvc"**. +1. `runner` == "Linux" + We **platform = "x86_64-unknown-linux-gnu"**. +We **supported = [Reject unsupported compilation runners](libraries(platform=`platform`))**. +1. not access(`supported`, "ok") + Return *supported*. +We **receipt = [Read this runner's actual native build receipt](fs.read_json(path=".marqdo/release/packs.json"))**. +1. access(`receipt`, "version") != `version` or access(`receipt`, "platform") != `platform` + Return *[Reject stale or foreign runner evidence](result.error(code="packs.receipt", message="receipt version/platform mismatch", operation="attach_ci"))*. +We **source = [Read the source archive identity](access(receipt, "source"))** and **native = [Read the platform archive identity](access(receipt, "native"))**. +1. access(`source`, "path") != ("dist/ext-release/marqdo-" + `version` + "-ext.zip") or access(`native`, "path") != ("dist/ext-release/marqdo-" + `version` + "-native-" + `platform` + ".zip") + Return *[Require the exact runner output names](result.error(code="packs.receipt_path", message="receipt paths differ from the selected outputs", operation="attach_ci"))*. +1. not [_unchanged source bytes](_unchanged(receipt=`source`)) or not [Unchanged native bytes](_unchanged(receipt=`native`)) + Return *[Stop before publication when local bytes drift](result.error(code="packs.changed", message="archive changed after build", operation="attach_ci"))*. +We **published = [Create or observe the exact release from reviewed committed notes](github.create_ext(version=`version`, path="doc/releases/ext-" + version + ".md", sha=`sha`))**. +1. not access(`published`, "ok") + Return *published*. + +`argv` = + +| argument | +|---| +| gh | +| release | +| upload | +| `tag` | +| "--repo" | +| "cflmy/marqdo" | + +1. `runner` == "Windows" + We **argv = [Attach the source pack from the Windows runner](table.append(list=`argv`, item=access(source, "path")))**. +We **argv = [Attach only this runner's native pack](table.append(list=`argv`, item=access(native, "path")))**. +Return *[Upload the verified candidates without replacing existing assets](engineering.checked(argv=`argv`, timeout_ms=300000, max_output=65536))*. diff --git a/skills/marqdo-release/reference.md b/skills/marqdo-release/reference.md new file mode 100644 index 0000000..cc9e2ba --- /dev/null +++ b/skills/marqdo-release/reference.md @@ -0,0 +1,22 @@ +# Release task reference + +Read [the executable release entry](index.mq.md). Version and mode come from the user; existing authorization is retained. Every task has its own input/return tables, effects, failure boundaries and recovery behavior. + +| Need | Actual callable source | +|---|---| +| Inspect versions and checkout | local.mq.md inspect | +| Derive mode obligations | index.mq.md plan | +| Author local source/notes | ../marqdo-dev/files.mq.md read, patch, write or apply | +| Prepare versions/editor/docs | local.mq.md bump, extension and docs | +| Commit reviewed files/push refs | local.mq.md commit, push and tag | +| Observe exact-source CI/edit reviewed notes | github.mq.md status and notes | +| Verify GitHub bytes and package roles | assets.mq.md download | +| Publish verified R2 packs/check public parity | assets.mq.md publish and status | +| Build signed noble source/check actual apt | ubuntu.mq.md ship and status | +| Require every release obligation complete | index.mq.md finish | + +A failed process, hook, HTTP response or pending CI remains visible. Inspect Result.ok before value. Use --require-ok when an external automation must stop on a failed Result; observational status may truthfully return complete=False. finish turns incomplete publication into a failed completion gate and retains its evidence. + +Git retries use the documented proxy then direct route. A reviewed SSH/HK route can be supplied through MARQDO_RELEASE_GIT_REMOTE; no jump program or credential value belongs in a model argument. Existing tags and failed stages remain available for inspection. Do not force, retag or reset to make a check green. If sudo, GPG or dput needs human interaction, report the exact failure and give the concrete ubuntu.mq.md ship call for the already authorized version. An accepted orig archive must retain its original bytes. + +Credentials stay in existing private stores. Do not publish from reading this note, deploy gh-pages without instruction, or call an asset list proof of green CI and apt publication. diff --git a/skills/marqdo-release/ubuntu.mq.md b/skills/marqdo-release/ubuntu.mq.md new file mode 100644 index 0000000..daf2841 --- /dev/null +++ b/skills/marqdo-release/ubuntu.mq.md @@ -0,0 +1,265 @@ +--- +markup: occlusion +title: Ubuntu publication: source, build and apt evidence +import: + net: lib/net.mq.md + json: lib/json.mq.md + text: lib/text.mq.md + table: lib/table.mq.md + re: lib/re.mq.md + result: lib/result.mq.md + engineering: ext/engineering/index.mq.md + local: ./local.mq.md + model: ./model.mq.md +--- + +Ubuntu 发布分为源码接收、构建成功和 apt 索引发布三个状态。这里用 Marqdo 固有网络库读取公开证据;gzip 格式交给工程拓展解码,不启动 Python。ship 是独立的外部写入任务,只有实际发版授权才能调用。status 只读,不会尝试重新上传已经存在的版本。 + +源包准备和文件修订在 package.mq.md;Debian 工具链、GPG 和 dput 通过维护中的系统脚本外联。sudo、签名口令或 Launchpad 拒绝都是真实失败,需要报告确切阶段与修复命令。已接收的 orig 归档不能改字节重传,打包修复只递增 Debian 修订号。 + +## read_json + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | text | required | Public Launchpad JSON URL | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result containing decoded response JSON | + +Use `url` for an explicitly selected public metadata endpoint. Native net.get +returns an HTTP response separately from transport success. Require status 200 +before decoding its body: a 404 HTML page must never become an empty publication +record. The helper reads at most one MiB with a bounded timeout and keeps the +original transport failure. No authentication, subprocess or temporary file is +needed for these public facts. + +This helper does not guess whether an upstream version has shipped. Its caller +selects matching source publications and builds from the returned records. +A schema change remains visible to that caller. Reading a successful response +is evidence for that endpoint at this time, not permission to upload a new +package. Call with network.read; further gzip decoding is a separate capability. + +We **fetched = [Read bounded public Launchpad JSON](net.get(url=`url`, timeout_ms=30000, max_bytes=1048576))**. +1. not access(`fetched`, "ok") + Return *fetched* with the transport diagnostic. +We **response = [Inspect the actual HTTP response](access(fetched, "value"))**. +1. access(`response`, "status") != 200 + Return *[Retain the unsuccessful HTTP status](result.error(code="ubuntu.http", message=str(access(response, "status")), operation="read_json"))*. +We **body = [Decode the successful JSON body](json.parse(text=access(response, "body")))**. +Return *[The service's actual metadata](result.ok(value=`body`))*. + +## source + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | User-confirmed stable X.Y.Z | +| series | text | "noble" | Ubuntu series being observed | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result containing the newest matching published source or None | + +Use `version` and `series`="noble" to locate a published upstream package. +The pure release model first validates the upstream version. Launchpad returns +publication history ordered by date; select the first entry with this upstream +version followed by a Debian revision and the exact target distro series. +A newer unrelated release or another Ubuntu series cannot satisfy this check. + +None is a successful observation that this version is not currently published. +An HTTP failure remains a failed Result and must not be reported as absence. +A source publication alone does not establish successful binary compilation: +builds and apt are separate tasks below. This query is public and requires +network.read. It changes neither Launchpad state nor local version metadata, +and it never infers the user's next version from the newest remote package. + +We **planned = [Validate the selected upstream version](model.plan(version=`version`))**. +1. not access(`planned`, "ok") + Return *planned*. +We **observed = [Read ordered publication history](read_json(url="https://api.launchpad.net/1.0/~cflmy/+archive/ubuntu/marqdo?ws.op=getPublishedSources&source_name=marqdo&exact_match=true&status=Published&order_by_date=true"))**. +1. not access(`observed`, "ok") + Return *observed*. +We **entries = [Read actual publication records](access(access(observed, "value"), "entries"))**. +- [Choose the exact upstream and distro series](for entries as entry) + 1. [The Debian revision belongs to this upstream](text.starts_with(text=access(`entry`, "source_package_version"), prefix=`version` + "-")) and access(`entry`, "distro_series_link") == "https://api.launchpad.net/1.0/ubuntu/" + `series` + Return *[The matching source publication](result.ok(value=`entry`))*. +Return *[No matching publication exists](result.ok(value=None))*. + +## builds + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| publication | any | required | Source publication returned by source, or None | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with complete and the selected source's actual builds | + +Use `publication` from the source task, rather than a build number copied +from a previous release. Launchpad's source record supplies the build collection. +The required amd64 build must report Successfully built. Keep all returned build +records for diagnosis, including logs and a pending or failed status. + +A missing source or an empty build collection remains incomplete. Do not treat +the successful metadata request as successful compilation. The task deliberately +does not retry or rescore Launchpad jobs; those are separate external mutations +that need a concrete packaging fix and release authorization. This read requires +network.read. Successful compilation still leaves the apt publication check: +the publisher may need time to expose the binary package in the repository +index after a build turns green. + +We **entries = [Start with no invented build records](table.empty_list())** and **complete = False**. +1. `publication` != None + We **observed = [Read builds belonging to this source publication](read_json(url=access(publication, "self_link") + "?ws.op=getBuilds"))**. + 1. not access(`observed`, "ok") + Return *observed*. + We **entries = [Keep the real build evidence](access(access(observed, "value"), "entries"))**. + - [Require the intended Linux architecture](for entries as build) + 1. access(`build`, "arch_tag") == "amd64" and access(`build`, "buildstate") == "Successfully built" + We **complete = True** because this source's amd64 binary compiled. + +`state` = + +| complete | entries | +|---|---| +| `complete` | `entries` | + +Return *[The actual source-specific build state](result.ok(value=`state`))*. + +## apt + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | User-confirmed stable X.Y.Z | +| series | text | "noble" | Ubuntu series being observed | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result with complete, package_version and the public index URL | + +Use `version` and `series`="noble" to inspect the actual public amd64 apt +index. Launchpad publishes Packages.gz; the uncompressed URL may return 404. +Native net.get reads portable bytes, then the engineering format boundary +validates gzip and decodes bounded UTF-8 text. No shell pipeline, local apt cache +or Python parser substitutes for the remote index. + +Find the marqdo package stanza and its exact upstream prefix plus Debian revision. +A different package's Version line cannot satisfy this check. A successful build +may precede index publication, so complete=False is an honest intermediate state. +Transport, gzip and schema failures retain their diagnostics. The task needs +network.read and plugin and writes no file. It proves repository visibility at +this instant; installation on a particular user's machine additionally depends +on their configured source and apt refresh. + +We **url = "https://ppa.launchpadcontent.net/cflmy/marqdo/ubuntu/dists/" + series + "/main/binary-amd64/Packages.gz"** and +**fetched = [Read the actual compressed apt index](net.get(url=`url`, response="bytes", max_bytes=16777216))**. +1. not access(`fetched`, "ok") + Return *fetched*. +We **response = [Inspect its HTTP status](access(fetched, "value"))**. +1. access(`response`, "status") != 200 + Return *[Retain index unavailability](result.error(code="ubuntu.apt_http", message=str(access(response, "status")), operation="apt"))*. +We **decoded = [Validate and decode the gzip format](engineering.gzip_text(data=access(response, "body")))**. +1. not access(`decoded`, "ok") + Return *decoded*. +We **stanzas = [Keep package fields in their own records](text.str_split(s=access(decoded, "value"), sep="\n\n"))** and **complete = False** and **package_version = None**. +- [Inspect only the marqdo package's version](for stanzas as stanza) + 1. [This is the marqdo package stanza](text.starts_with(text=`stanza`, prefix="Package: marqdo\n")) + We **line = [Read its Version field](re.find(text=`stanza`, pattern="(?m)^Version: [^\n]+"))**. + 1. `line` != None + We **candidate = [Remove the field label](text.replace(text=`line`, old="Version: ", new="", count=1))**. + 1. [This index contains the requested upstream](text.starts_with(text=`candidate`, prefix=`version` + "-")) + We **package_version = candidate** and **complete = True**. + +`state` = + +| complete | package_version | url | +|---|---|---| +| `complete` | `package_version` | `url` | + +Return *[The observed apt publication state](result.ok(value=`state`))*. + +## status + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | User-confirmed stable X.Y.Z | +| series | text | "noble" | Ubuntu series being observed | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result combining source publication, build and apt completion | + +Use `version` and `series`="noble" to verify an existing Ubuntu release. +Each observation remains separate in the returned record so the user can tell +whether upload, compilation or apt publication is pending. Completion requires +a published source, its successful amd64 build, and the matching apt package. + +This is a read-only task requiring network.read and plugin. It does not invoke +sudo, GPG, debuild or dput. Repeating status observes newer external state without +creating another upload. If a service request fails, return its real failure +rather than manufacturing a pending state. An ext-only release has no Ubuntu +obligation; the top-level release handbook handles that mode explicitly. Keep +the version provided by the caller: querying status never selects a next release +or edits the local changelog. + +We **published = [Locate this upstream's source publication](source(version=`version`, series=`series`))**. +1. not access(`published`, "ok") + Return *published*. +We **publication = [Retain its matching source record](access(published, "value"))** and +**built = [Check the source-specific amd64 build](builds(publication=`publication`))**. +1. not access(`built`, "ok") + Return *built*. +We **indexed = [Verify actual apt repository visibility](apt(version=`version`, series=`series`))**. +1. not access(`indexed`, "ok") + Return *indexed*. +We **build_state = [Keep build evidence](access(built, "value"))** and **apt_state = [Keep index evidence](access(indexed, "value"))** and +**complete = publication != None and access(build_state, "complete") and access(apt_state, "complete")**. + +`state` = + +| complete | publication | build | apt | +|---|---|---|---| +| `complete` | `publication` | `build_state` | `apt_state` | + +Return *[The independently measured Ubuntu release state](result.ok(value=`state`))*. + +## ship + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| version | text | required | User-confirmed stable X.Y.Z | +| series | text | "noble" | Ubuntu series being observed | +| root | text | "." | Checkout matching --fs-root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result from the signed Ubuntu source publication boundary | + +Use `version`, `series`="noble" and `root`="." only for an authorized +CLI/full release. Verify the checked-out interpreter has that exact upstream +version before invoking the maintained Debian tools. Their signatures, orig +archive rules and dput behavior remain the operating-system boundary. File +preparation in that script delegates to package.mq.md. + +This task requires plugin and fs.read and may need interactive OS credentials. +A sudo, GPG or dput failure is incomplete publication. Report the exact failing +stage and give the concrete recovery call, rather than hiding it behind success +or inventing another version. After the command succeeds, run status: upload +acceptance alone does not establish green builds or apt availability. Never +rewrite an orig archive already accepted by Launchpad. + +We **observed = [Require actual checkout version metadata](local.inspect(root=`root`))**. +1. not access(`observed`, "ok") + Return *observed*. +1. access(access(`observed`, "value"), "cli_version") != `version` + Return *[Refuse a different source version](result.error(code="ubuntu.version", message="checkout version differs from requested upstream", operation="ship"))*. + +`argv` = + +| argument | +|---| +| "bash" | +| "scripts/ppa-ship.sh" | +| `series` | + +Return *[Build, sign and upload through the maintained Debian tools](local.command(argv=`argv`, timeout=3600, root=`root`))*. diff --git a/skills/marqdo/SKILL.md b/skills/marqdo/SKILL.md index 9f837c8..6a8f1bc 100644 --- a/skills/marqdo/SKILL.md +++ b/skills/marqdo/SKILL.md @@ -1,281 +1,62 @@ --- name: marqdo -description: >- - Author and edit Marqdo programs (.mq.md): Markdown markers are executable - syntax (functions, calls, statements, returns, control flow). Use when writing - or modifying .mq.md files, teaching Marqdo, generating Marqdo from prose, - importing lib/* or ext/web or ext/quantum, running marqdo CLI, building dynamic - sites with ext/web, quantum circuits with ext/quantum, or when the user - mentions Marqdo, mq.md, markup-as-syntax, code-as-documentation, web/网页, or - quantum/量子 extension (ZH under ext/quantum/量子/). +description: Author, run and review readable Marqdo programs, libraries and executable knowledge. Use for .mq.md, marqdo call, Document/Endpoint/Resource web projects and quantum tools; read the executable programming and development handbooks. --- -# Marqdo development +# Marqdo -Marqdo = **Markdown markers as syntax**. A `.mq.md` file is both documentation and a runnable program. Read this skill **before** inventing syntax from Markdown habits or Python. +<!-- CORE_SYNTAX_V2.1: keep this card within the first 1200 body characters --> -<!-- CORE_SYNTAX_V2.1: must stay at the top so skill_brief budgets never truncate it --> +## CORE SYNTAX -## CORE SYNTAX (v2.1 Occlusion — mandatory) +Occlusion is the current default. `**…**` executes a statement; `*…*` returns. +Use `[intent](actual code)` in an executable position: the label is prose and +only its payload executes. Empty parentheses are a pending None stub. +Read collections with `access(coll, key)`. Classic indexing is only for explicit +legacy sources and migration. Reading narrative references never runs effects. -These rules are the **current default**. Do **not** teach Classic `[key](map)` index or “bold is return of print”. Classic migration only: [migration-classic.md](migration-classic.md). - -1. **File suffix** `.mq.md`. Print with `> print text=…` / `> 打印 内容=…` — never use `**…**` to print. -2. **`**…**` = statement** (assign / call / expression). `*…*` = return. Closing markers touch the last token (no trailing space). -3. **`[描述](payload)` = occlusion:** `[]` is prose (never executed); `()` is the only executed part. Empty `()` → `None` stub. -4. **Read collections with `access(coll, key)`** (aliases `取` / `取值`). **Never** use `[key](map)` as index under default Occlusion. -5. **Foreach:** `- [描述](遍历 coll 为 item)` (`遍历`/`for`, `为`/`as`/`in`). Prefer explicit traversal when generating new code. -6. **Import / call:** frontmatter `import:` / `导入:`; call `lib.member`. One language (EN or ZH) per file. -7. **Control flow:** `#` object/type, `##`+ function, prose params (legacy `+` remains parseable), `1.`/`2.` branches, `-` loops, `N. *` else. No invented `if`/`for`/`def`/`return` keywords. -8. **Prose vs code:** blank line separates comment paragraphs from executable lines. -9. **GFM tables** for data; prefer `table.put` over `json.set` chains. `ext/**` never calls `host_*`. -10. Body narrative `[描述](target)` is lazy (NarrativeRef) — reading does not execute side effects. - -| Marker | Meaning (v2.1) | -|--------|----------------| -| `#` / `##`+ | Object/type · function/method | +| Marker | Meaning | +|---|---| | `**…**` | Statement (assign / call / expression) | | `*…*` | Return | -| `[描述](payload)` | Occlusion step (payload executes) | +| `[intent](payload)` | Readable intent with executable payload | | `access(c, k)` | Collection read | -| `> fn …` | Call | -| GFM table | Collection literal | - -Canonical: `doc/design/core-surface.md`, `doc/design/document-native-development-guide.md`. Deeper tables: [reference.md](reference.md). Patterns: [examples.md](examples.md). Authoring craft: [marqdo-dev](../marqdo-dev/SKILL.md). Release: [marqdo-release](../marqdo-release/SKILL.md). - -Executable-knowledge gate: [`tests/executable_knowledge/`](../../tests/executable_knowledge/README.md). - -## Hard rules (do not violate) - -1. Obey **CORE SYNTAX** above — Occlusion is default; do not emit Classic index links. -2. **Identifiers:** declare library parameters in prose as `` input `name` `` (defaults follow `=`); inside `*…*` / `**…**` bare ids are variables. Quote text literals. Standalone `>` calls: backticks where bare would be text. -3. **Structure lines** (`#` `>` `+` `-` `|`) are not wrapped in italics. -4. **Paths:** bare `/` in expressions is division; in call args / table cells unspaced `a/b` is path text. Ratios as text need quotes (`"1/5"`). -5. End side-effect-only helpers with `*None*` / `*空*` / `**` / `****` when the outer function continues. Lone `---` is a thematic break, not function end. -6. **`ext/**` never calls `host_*`.** Prefer tables over `json.set` / `json.append`. -7. **One language per file.** Sandbox trial before promoting Agent-generated trees. -8. Browser: Marqdo on WASM + `lib/browser` tables; do not hand-write business JS. - - -## Call one function - -```markdown -# 计算器 - -## 加法 - -计算两个数字`a`和`b`的和。 - -*[计算结果](a + b)* -``` - -``` -marqdo call calculator.mq.md 计算器.加法 a=2 b=3 -``` - -prints `5`. The same command works on any `.mq.md`; the file does not need a special skill name. - -## Minimal program - -```markdown -# main - -> print text=Hello World! -``` - -Chinese builtins (same functions, no import): - -```markdown -# main - -> 打印 内容=你好 -``` - -## Functions, calls, end-body - -```markdown -# main - -> greet who=Marqdo - -## greet - + `who` - -> print text=Hello, `who`! - -*None* -``` - -- Call: `> name key=value` or `> name value`. -- Nested helpers use deeper `#` (`##`, `###`, …). -- After a helper with only side effects, end with `*None*` / whole-line `**` / `****` when later lines must stay in the outer function. Lone `---` is only a thematic break (skipped). -- In bold assigns, prefer bare calls: `**摘要 = 结账摘要 …**` (omit `>`). - -## Statements, returns, branches - -```markdown -**x = 1** -**y = x + 2** - -## add_one - + `n` - -*n + 1* -``` - -```markdown -*n = 0* - -1. `n` > 0 - > print text=positive -2. `n` < 0 - > print text=negative -3. * - > print text=zero -``` - -## Frontmatter imports + stdlib - -A standard library is normally one `lib/*.mq.md` file: read/import/call that file directly. It is its own manual and skill; no `index.mq.md` or module handbook directory is required. Each function puts parameter/default and return tables directly below its heading, explains purpose, failures and limits, and keeps narrative above 50%. Use prose parameters, not legacy `+` declarations. Describe opaque instructions with `[what it does](actual code)` inside statement/return markers; labels do not execute. Multi-file extensions use an index to organize their files. File tools require explicit `--effects fs.read` or `--effects fs.write` with `--fs-root`; real workflows live in `examples/stdlib-handbook`. Read the [executable authoring guide](../../doc/library-development.mq.md) for inline prose and complete runnable examples. - - -Imports use nested YAML `import:` (`导入` equivalent): file (`.mq.md`) or short name (`lib.member`). Members are **not** flattened into the caller. Call with a bare dotted path: - -```markdown ---- -title: example -import: - text: lib/text.mq.md - clock: lib/time.mq.md ---- - -# main - -**xs = > text.split value="a,b,c" sep=","** -> print text=`xs` -**t = > clock.now_unix** -``` - -- Import **English** or **Chinese** library file; call that file’s API names via `lib.member` (do not mix languages). -- 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 (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/) · [agent-sandbox-okf](../../examples/agent-sandbox-okf/). Harness: `scripts/agent-harness.sh`. Design: [ext-agent.md](../../doc/design/ext-agent.md) · optimize O1–O5: [ext-ai-optimize.md](../../doc/roadmap/ext-ai-optimize.md). Dev LLM: copy [.env.example](../../.env.example) → `.env` (gitignored). - -**Sandbox (O1):** `import sandbox:ext/ai/sandbox.mq.md` · `agent.trial` / `智能体.试跑` · `run`/`step` take `sandbox=` / `沙盒=` (default `False`). Profile caps are tables via `sandbox.profile`. Gold: `tests/ext/agent-sandbox-optin.mq.md`. - -## Official extension: `ext/web` (Document / Endpoint / Resource) - -Install: `marqdo ext add web` (ZH id: `网页`). See ADR 0007 · [ext-web-artifact.md](../../doc/design/ext-web-artifact.md). - -**Do not degrade:** Document/Endpoint metadata; facade `web.page|route|serve|render|inspect`; View `|type|slot|value|attrs|style|` only; no `compose_*` / `configure` / author `ensure_plugin`. DB → `ext/data`; auth → `ext/security`; net → `ext/net`. - -- **Root skill (agents first):** [`ext/web/index.mq.md`](../../ext/web/index.mq.md) · ZH [`ext/web/网页/索引.mq.md`](../../ext/web/网页/索引.mq.md)(作者门面仍为 `网页.mq.md`) -- **Layout law (in-package):** file-partition pages (nav/sidebar/footer/…) until simple; no HTML/CSS injection as default — [`ext/web/layout/index.mq.md`](../../ext/web/layout/index.mq.md) · [ext-web-layout-paradigm.md](../../doc/design/ext-web-layout-paradigm.md) -- **Recursive practice:** home → nav/main/footer → footer brand/links → links docs/community; continue until a leaf is plain Markdown. Parents import children and declare one relationship. Use `component.markdown`, `component.wrap`, `layout.stack`, and `layout.columns`; merge alone gives siblings, not columns. -- **Runnable reference:** [web-layout-handbook](../../examples/web-layout-handbook/index.mq.md) and [Chinese reference](../../examples/web-layout-handbook-zh/index.mq.md). A composed Document declares `view: main` and returns node rows at startup; ordinary Documents keep their Markdown/data-source path. Use `inspect root=...` for disk routes, and `run` for a live server. -- EN author facade: `import web:ext/web/web.mq.md` -- Agent: `marqdo call ext/web/layout/index.mq.md rules --json` then facade tools with `--effects plugin` - -Design: [ext-web-artifact.md](../../doc/design/ext-web-artifact.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/). - -## Official extension: `ext/quantum` (circuits + Q7/Q8) - -Install: `marqdo ext add quantum` (ZH id: `量子`). Build: `cargo build --release -p marqdo_plugin_quantum`, then **`marqdo ext add quantum` again** so view loads the new `libquantum.so` (stale plugin = old black/white circuits). - -- **Root skill (read first):** [`ext/quantum/index.mq.md`](../../ext/quantum/index.mq.md) — explains every module and exact `marqdo call` commands for agents with no other context. -- **Ext paradigm:** [`doc/design/ext-skill-tools-paradigm.md`](../../doc/design/ext-skill-tools-paradigm.md) — code=doc=skill=tools; checklist for new packs. -- **Modules:** `circuit/` · `gate/` · `simulate/` · `state/` · `density/` · `viz/` · `_capability/` (each has `index.mq.md`). ZH package: `ext/quantum/量子/`(根 `索引.mq.md`,模块同名中文目录). -- **Agent:** `marqdo call ext/quantum/<module>/index.mq.md <fn> … --effects plugin` (`--toget` / `$name`). Narration: `marqdo check --narrative-ratio FILE`. -- **Author import example:** `circuit: ext/quantum/circuit/index.mq.md` then `circuit.circuit` / method chain. - -**Hard rules:** `ext/**` never calls `host_*`; hot path is ABI plugin; ≤12 qubits for statevector; density-matrix ops ≤6 qubits; one language file per program; quote draw string args (`kind="…"`, `theme="…"`). - -**Core:** domain skills above (`# circuit` / `# gate` / `# density` on module files) — table `steps=` or method chain; `simulate` / `probabilities` / `run` / `draw`. - -**Q7 linear algebra:** `density`, `partial_trace`, `eig`, `expect` (Pauli string, left=high bit), `purity`, `kron`, `schmidt`, `fidelity`. - -**Draw kinds:** `circuit|probs|bloch|hinton|city|density|paulivec|qsphere|multibloch`. - -**Q8 themes (circuit / probs / bloch):** `theme="dark"|"light"|"bw"` (ZH `主题=`; **default `dark`** — slate lab look, gate-family colors, label chips so wires never cross `q0` text). View plot chrome follows `data-theme` on the SVG. Advanced kinds (hinton/…) still Q8c pending full re-skin. - -```markdown -**_ = > `qc`.draw kind="circuit" theme="dark"** -**_ = > `qc`.draw kind="probs" theme="light"** -``` - -Design: [ext-quantum.md](../../doc/design/ext-quantum.md) · Q7: [ext-quantum-q7.md](../../doc/design/ext-quantum-q7.md) · Q8 viz: [ext-quantum-viz-style.md](../../doc/design/ext-quantum-viz-style.md) · examples: [quantum-bell](../../examples/quantum-bell/) · [quantum-entanglement](../../examples/quantum-entanglement/). - -## Foreign kernels (v1.5.0) - -`lib/foreign` is now a full foreign-kernel surface, not only `run`: - -- `invoke` returns a record (`ok`, `code`, `stdout`, `stderr`, `ms`, `timed_out`, `truncated`, `result`); pass `input` for JSON stdin and `output="json"` for a parsed result. -- `call` is JSON-in / JSON-out; `call_many` fans out one program over a list with ordered results. -- `session_open` starts a persistent Python/Node kernel; `session_eval` evaluates source; `session_set` / `session_get` bridge values explicitly as JSON. Close it with `session_close`. -- A view document opts into kernel state with `会话 = > foreign.session kernels=... cells=...`; the table names are free. `view` consumes only the `会话` handle and never scans source lines or reserved table names. Without `会话`, cells are stateless one-shot runs; no kernel is created. Clearing outputs calls `/api/session/clear` and keeps persistent kernel state. There is no separate notebook CLI mode or command, and no new Markdown marker exists. -- The same source remains the authority; state crossing kernels is explicit, never implicitly mirrored. - -## AI authoring workflow - -1. Decide language surface (English builtins + `lib/text.mq.md`, or Chinese + `lib/文本.mq.md`). -2. Write `.mq.md` with `# main`, blank lines around prose, correct markers. -3. Run: `marqdo run path/to/file.mq.md` (cwd = project root so `lib/` resolves). -4. On `path:line:col: message`, fix that span; re-run until exit 0. -5. Optional: `marqdo view .` / `marqdo debug .` for structure and breakpoints. - -## Anti-patterns (common model mistakes) - -| Wrong | Right | -|-------|-------| -| `**Hello**` to print | `> print text=Hello` | -| `# main` then prose then code with no blank line | Blank line before code | -| `if x > 0:` | `1. `x` > 0` | -| `* > print text=hi *` | `> print text=hi` | -| `` *`a` = 1 * `` (trailing space + backticks) | `**a = 1**` — bare bind, no trailing space before `*` / `**` | -| `*xs = > text.split value=a,b sep=,*` (italic is return, and bare text args) | `**xs = > text.split value="a,b" sep=","**` — statement; quote text literals | -| Forgetting empty return after nested `##` helper when outer continues | Add `*None*` / `**` / `****` (not `---`) | -| 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` / `compose_*` page parts | `type: web` Document + View table / `web.render` / `web.serve` | -| 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 | -| Bare `kind=hinton` inside `*…*` | `kind="hinton"` — quote text literals | -| Bare `theme=dark` inside `*…*` | `theme="dark"` — quote; ZH `主题="dark"` | -| Rebuild plugin but skip `ext add` | `cargo build -p marqdo_plugin_quantum` then `marqdo ext add quantum` (or set `MARQDO_QUANTUM_PLUGIN`) | - -## Checklist before finishing - -- [ ] File ends with `.mq.md` -- [ ] Print via `print` / `打印`, not bold -- [ ] Blank lines separate comment paragraphs from code -- [ ] `# main` exists when the file is an entry program -- [ ] Nested side-effect helpers ended with `*None*` / `**` / `****` when the outer function continues -- [ ] 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) +| `- [intent](for items as item)` | Explicit traversal | +| `1.` / `2.` | Branches; numbered * is else | +| GFM table | Data: one column list, one row record, @ row records | + +Read [the executable programming guide](../../doc/library-development.mq.md) +before authoring. Its actual callable examples demonstrate inline computation, +structured results, defaults and recoverable native file reads. Use +[the development entry](../marqdo-dev/index.mq.md) and its file tools for source +work, and [the release entry](../marqdo-release/index.mq.md) for an authorized +release. These mq.md files are the working instructions and tools; do not rebuild +a parallel command playbook in SKILL.md. + +Call the actual file and heading with `marqdo call`. In a source checkout use +the built `target/debug/marqdo`; prepare its engineering plugin through the +development entry. Large structured inputs use --args-json FILE or stdin; +JSON strings stay literal during call-session replay. --require-ok makes failed +Results stop external automation while preserving their returned evidence. +Read each function's parameter/return tables and effect contract before calling. + +Author programs as readable explanations: useful narrative exceeds half of +each callable unit; parameter and return tables immediately follow its heading; +inline assignments, actions and returns explain their purpose. Standard libraries +remain single-file handbooks. Multi-file projects and extensions use index.mq.md. +GFM describes data, public helpers describe operations, and components recursively +split web layouts until their content leaves are ordinary Markdown. + +Native Marqdo capabilities handle file reading/writing, tables, parsing, hashing +and network reads. Add an extension for a reusable capability gap or call an +explicit existing external tool with argument arrays. Keep decisions, retries +and the execution flow in mq.md. Do not generate Python or shell programs for +already available native operations. OS processes and plugins retain their OS +authority; an fs-root does not sandbox their own access. + +Use the current [web entry](../../ext/web/index.mq.md) for Document, Endpoint and +Resource artifacts, or [quantum entry](../../ext/quantum/index.mq.md) for circuit +workflows. Do not restore removed compose_* or app.configure APIs. Preserve +intentional fixtures and [classic migration context](migration-classic.md). +Validate the real calls and error paths; a narrative ratio or uploaded asset +alone is never functional evidence. diff --git a/skills/marqdo/examples.md b/skills/marqdo/examples.md index 0048837..6d29a72 100644 --- a/skills/marqdo/examples.md +++ b/skills/marqdo/examples.md @@ -1,328 +1,5 @@ -# Marqdo examples (AI) +# Marqdo executable examples -## 1. Hello (English) +The maintained programming rules and runnable examples live in [the executable programming guide](../../doc/library-development.mq.md). Read its parameter and return contracts, then call the actual source heading. [The development entry](../marqdo-dev/index.mq.md) provides native file operations and verification tasks; [the release entry](../marqdo-release/index.mq.md) provides publication workflows. -```markdown -# main - -> print text=Hello World! -``` - -## 2. Hello (Chinese builtins) - -```markdown -# main - -> 打印 内容=你好,世界! -``` - -## 3. Function + named call + body end - -```markdown -# main - -Greeting via a nested function: - -> greet who=Marqdo - -## greet - + `who` - -> print text=Hello, `who`! - ---- -``` - -## 4. Bindings and return - -```markdown -# main - -*a = 2* -*b = > add_one n=`a`* -> print text=`b` - -## add_one - + `n` - -**n + 1** -``` - -## 5. Branch with else - -```markdown -# main - -*n = 0* - -1. `n` > 0 - > print text=positive -2. `n` < 0 - > print text=negative -3. * - > print text=zero -``` - -## 6. Foreach loop - -```markdown -# main - -`篮子` = - -| 果 | -|----| -| 苹果 | - -- [果](篮子) - > print text=`果` -``` - - -## 6b. Map table + footnote get - -```markdown -# main - -`分类` = - -| 苹果 | 黄瓜 | -|------|------| -| 水果 | 蔬菜 | - -*种 = 分类[^苹果]* -> print text=`种` - -*第一 = 篮子[^1]* -``` - -One column → list; ≥2 columns + one data row → map; ≥2 columns + many rows → map of lists. Data cells are expressions (same as call-arg values): bare words, numbers, `` `var` ``, quoted strings; URLs and `gpt-4o-mini` stay text via path/hyphen folding. Footnotes: lists use 1-based digit indices; maps use key text (including digit keys like `[^00]`). Foreach on a map walks **keys**. - -Row-oriented records (SQL-like): first header `@` / `行` / `row` → list of maps (marker column excluded): - -```markdown -`订单` = - -| 行 | 品名 | 数量 | -|----|------|------| -| 1 | 苹果 | 2 | - -*名 = 订单[^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 ---- -title: split demo -import: - text: lib/text.mq.md ---- - -# main - -*parts = > split value=a,b,c sep=,* -> print text=`parts` -``` - -## 8. Comment paragraphs (blank-line rule) - -```markdown -# main - -This whole paragraph is a comment, including lines that look like code: -*not_executed = 1* -> print text=also still comment - -After a blank line, code runs: - -> print text=this runs -``` - -## 9. Frontmatter import only - -```markdown ---- -description: loads math -import: - math: lib/math.mq.md ---- - -# main - -*t = > num value=3.5* -> print text=`t` -``` - -## 10. Object handle + method - -See `tests/structure/object-handle.mq.md` and `ext/llm.mq.md`: `# Type` constructs a map with `_type`; methods use `` > `obj`.method `` and read `self` / `自`. - -## 10b. Object inheritance - -```markdown -# Greeter - -## hello - + `who` - -*msg = "Hello, `who`!"* -**msg** - -# Loud = > Greeter - -## hello - + `who` - -*msg = "HELLO, `who`!"* -**msg** -``` - -`_type` stays the most specific name (`Loud`). Methods walk the base chain; same-name `##` on the child overrides. **No implicit super** — if the child needs parent fields, call the parent explicitly: - -```markdown -# Child = > Parent - + `name` - -*self = > Parent name=`name`* -*self = > json.set map=`self` key=extra value=1* -**self** -``` - -## 11. Agent layout (ABI) - -```markdown ---- -import: - agent: ext/agent.mq.md ---- - -# main - -> load_native - -*ws = > agent* -*n = > `ws`.ensure_layout* -> print text=`n` -``` - -Requires `MARQDO_AGENT_PLUGIN` pointing at the built `agent` shared library (see `doc/design/ext-agent.md`). - -## 12. What not to emit - -```markdown -# BAD — bold is return, not print -**Hello** - -# BAD — Python control keywords -if x > 0: - print(x) - -# BAD — wrapping a call in italics -*> print text=hi* - -# BAD — old branch syntax (removed) -+ `x` > 0 - -# GOOD — ordered list arms -1. `x` > 0 - > print text=pos -2. * - > print text=other - -# GOOD — another independent branch (restart at 1.) -1. `y` > 0 - > print text=y-pos -2. * - > print text=y-other -``` - -## 13. Dynamic site (Web Artifact, minimal) - -`index.mq.md`: - -```markdown ---- -type: web -title: Hello -route: / -method: GET ---- - -# Hello - -Executable document as a page. -``` - -`serve.mq.md`: - -```markdown ---- -import: - web: ext/web/web.mq.md ---- - -# main - -> web.serve root="." host="127.0.0.1" port=8080 -``` - -- Import `ext/web/web.mq.md` **or** `ext/web/网页.mq.md` — not both. -- Full Artifact blog: `examples/marqdo-blog/` (`pages/` · `api/` · `db/` · `data_source`). -- Design: `doc/design/ext-web-artifact.md` · ADR 0007. No `compose_*` / `configure`. - -## 14. Quantum entanglement lab (ext/quantum Q7/Q8) - -```markdown ---- -import: - quantum: ext/quantum/circuit/index.mq.md ---- - -# main - -`steps` = - -| step | gate | qubits | -|------|------|--------| -| 1 | H | 0 | -| 2 | CX | 0,1 | - -*qc = > quantum.circuit qubits=2 steps=`steps`* -*rho = > `qc`.density* -*red = > `rho`.partial_trace keep=0* -*sch = > `qc`.schmidt cut=1* -*_ = > `qc`.draw kind="circuit" theme="dark"* -*_ = > `qc`.draw kind="hinton"* -> print text=`red` -``` - -- Full lab: `examples/quantum-entanglement/`. Bell-only: `examples/quantum-bell/`. -- `theme="dark"|"light"|"bw"` (default dark) on `circuit` / `probs` / `bloch`. Quote `kind=` / `theme=`. -- After rebuilding the plugin: `marqdo ext add quantum` so view loads the new native lib. +Use [the recursive Markdown web example](../../examples/web-layout-handbook/index.mq.md) and [the quantum workflow](../../examples/quantum-entanglement/index.mq.md) for domain development. Their real source is the manual. [Classic migration context](migration-classic.md) remains for explicitly historical syntax; new programs use readable occlusion and access(collection, key). Do not copy a second fenced program from this discovery note. diff --git a/skills/marqdo/reference.md b/skills/marqdo/reference.md index 6481ab8..850370a 100644 --- a/skills/marqdo/reference.md +++ b/skills/marqdo/reference.md @@ -1,191 +1,5 @@ -# Marqdo reference (AI) +# Marqdo executable reference -Load this when you need stdlib names, CLI, or edge cases. Core rules stay in [SKILL.md](SKILL.md). +The maintained programming rules and runnable examples live in [the executable programming guide](../../doc/library-development.mq.md). Read its parameter and return contracts, then call the actual source heading. [The development entry](../marqdo-dev/index.mq.md) provides native file operations and verification tasks; [the release entry](../marqdo-release/index.mq.md) provides publication workflows. -## CLI - -```text -marqdo --version -marqdo run FILE.mq.md -marqdo run FILE.mq.md --backend bytecode -marqdo view PATH # docs browser, default port 7429 -marqdo debug PATH # debugger UI, default port 7430 -marqdo catalog PATH -o .marqdo -marqdo ext list -marqdo ext add llm|agent|web|quantum -marqdo ext remove llm|agent|web|quantum -``` - -Diagnostics look like `path:line:col: message` (1-based line/col). - -**v0.2 surface:** parameters `` + `name` ``; branches `` 1. `cond` `` / `` 2. * `` (same-indent restart at `1.` = **new** branch statement); loops `` - [item](coll) `` or `` - [`item`](`coll`) ``; identifiers in backticks (foreach header may omit ticks). See `doc/design/markdown-mapping.md`. - -Stdlib search order for `lib/…` imports: `MARQDO_LIB`, `./lib`, directory of the `marqdo` executable (and a few parents). Prefer the **bundle zip** (`marqdo.exe` + `lib/`) over a bare exe. - -官方扩展(`ext/…`,非 stdlib):`marqdo ext add` 装到 `MARQDO_EXT` 或 `~/.marqdo/ext`;导入仍写 `import llm:ext/llm.mq.md`。解析还含 cwd `ext/`、二进制旁 `ext/`。对象:`doc/design/objects.md`。Agent:`doc/design/ext-agent.md` · 安装器:`doc/design/ext-cli.md`。 - -## Builtins (no import) - -| EN | ZH | Role | -|----|----|------| -| `print` | `打印` | stdout; arg `text` / `内容` | -| `input` | `输入` | one line; arg `prompt` / `提示` | -| `len` | `长度` | length; arg `value` / `值` | -| `str` | `文本` | to text; arg `value` / `值` | -| `int` | `整数` | to int; arg `value` / `值` | - -Keywords (not variable names): `True`/`真`, `False`/`假`, `None`/`空`, `and`/`且`, `or`/`或`, `not`/`非`. - -## Standard library files - -Import one file; use **that** file’s function names. - -| EN import | ZH import | Typical APIs (EN / ZH) | -|-----------|-----------|-------------------------| -| `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) | **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` | 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/index.mq.md` · `web.mq.md` | `ext/web/网页/索引.mq.md` · `网页.mq.md` | dynamic sites — see **ext/web** section below | -| `ext/quantum/index.mq.md` + modules | `ext/quantum/量子/索引.mq.md` + modules | circuits + Q7 density/viz + Q8 themes — see **ext/quantum** below | - -Open the imported `.mq.md` under `lib/` or `ext/` to see exact `##` / `#` names and parameters. Gold tests: `tests/lib/`, `tests/structure/`, `tests/ext/`. - -## ext/web (Artifact sites · ADR 0007) - -Install: `marqdo ext add web` (`网页`). Native: `bash scripts/build-web-plugin.sh`. - -Layout practice: split home into nav/main/footer; split footer into brand/links, -then links into docs/community until content leaves are ordinary Markdown. -Use `component.markdown|wrap`, `layout.stack|columns`, and @ record lists. -A parent value holds child rows of the same five-column View schema. -Explicit `view: main` Documents assemble once at startup; `inspect root=...` -scans disk declarations. See the Web root handbook and reference layout site. - - -| EN import | ZH import | Surface | -|-----------|-----------|---------| -| `ext/web/web.mq.md` | `ext/web/网页.mq.md` | facade: `page` · `route` · `serve` · `render` · `inspect` · `use` | - -| Kind | Metadata | Notes | -|------|----------|-------| -| Document | `type: web` / `类型: 网页` | `route` · `data_source` · `data_order` · `data_where` | -| Endpoint | `type: endpoint` / `类型: 端点` | `path` · `method` · `# main` handler · `request`/`response` | -| View | `|type|slot|value|attrs|style|` | `web.render nodes=` | -| Resource | `ext/data` · `ext/security` · `ext/net` | db/cache/storage · auth/rbac/oidc · websocket | - -Do **not** use `compose_*` / `app.configure` / author `ensure_plugin`. - -Example: `examples/marqdo-blog/`. Design: `doc/design/ext-web-artifact.md`. Historical matrix: `doc/design/web-net-capabilities.md`. - -## ext/quantum (circuits + Q7/Q8) - -Install: `marqdo ext add quantum` (`量子`). Native: `cargo build --release -p marqdo_plugin_quantum`, then re-run `ext add` so view picks up the new `.so`. - -| EN import | ZH import | Core types | -|-----------|-----------|------------| -| `ext/quantum/circuit/index.mq.md` (etc.) | `ext/quantum/量子/电路/索引.mq.md` (etc.) | `# circuit` / `# 电路` · `# gate` / `# 门` · `# density` / `# 密度` + call tools | - -| Area | EN APIs | Notes | -|------|---------|-------| -| Circuit | `h`/`cx`/…, `simulate`, `probabilities`, `run`, `draw`, `noise` | `steps=` GFM table; ≤12 qubits | -| Gate | `matrix`, `matches_matrix`, `draw` | named or `matrix=` custom unitary | -| Density (Q7) | `purity`, `partial_trace`, `eig`, `expect`, `draw` | ≤6 qubits for dense ρ | -| Free (Q7) | `kron`, `schmidt`, `fidelity` | top-level on import bind | -| Draw kinds | `circuit\|probs\|bloch\|hinton\|city\|density\|paulivec\|qsphere\|multibloch` | quote `kind="…"` | -| Themes (Q8) | `theme="dark"\|"light"\|"bw"` (ZH `主题=`) | default **dark**; circuit/probs/bloch themed; SVG `data-theme` | - -Examples: `examples/quantum-bell/`, `examples/quantum-entanglement/`. Design: `doc/design/ext-quantum.md` · Q7: `doc/design/ext-quantum-q7.md` · Q8: `doc/design/ext-quantum-viz-style.md`. - -## Formula + plot (math) - -```markdown ---- -import: - math: lib/math.mq.md ---- - -# main - -`f` = -$$ -x^2 - 2 -$$ - -*_svg = > plot formula=`f` var=x min=-3 max=3* -``` - -Empty RHS assignment + following `$$…$$` binds a formula value. Narrative-only `$$` without binding is display, not assignment. - -## Foreign (Python example) - -```markdown ---- -import: - foreign: lib/foreign.mq.md ---- - -# main - -`hi` = -```python -print("hello-from-python") -``` -``` - -Lines starting with `` ` `` can be code (binding). Keep a blank line before/after fences per comment rules. - -## Function-end details - -| Form | Effect | -|------|--------| -| Lone `---` or `***` (≥3 same chars) at function body top level | End function; no return value | -| `****` or empty bold | Return `None` and end body | -| `**expr**` | Return `expr`; does **not** by itself cut off later sibling statements — still use HR or shallower heading | - -File-leading paired `---` is frontmatter only; body `---` is not frontmatter. - -## Call arguments - -- Named: `> greet who=World` -- Positional: `> greet World` -- Spaces in values: allowed in named forms as in docs (`who=marqdo user`) -- Inline call in statement: `` *`n` = > len value=`s`* `` - -See `doc/design/call-arguments.md`. - -## Identifiers - -- Variables: `` `name` `` -- Comparisons: `==` `>` `<` `>=` `<=` -- Do not use keyword tokens as names - -## Design docs (repo) - -| Doc | Topic | -|-----|--------| -| `doc/design/markdown-mapping.md` | Syntax constitution | -| `doc/design/objects.md` | `#` objects / `##` methods | -| `doc/design/keywords.md` | Builtins / keywords | -| `doc/design/return-hr-and-code-surface.md` | Function end / surfaces | -| `doc/design/stdlib-i18n.md` | EN/ZH lib files | -| `doc/design/stdlib-modules.md` | L1 modules including plugin | -| `doc/design/ext-abi.md` | Native C ABI v1 | -| `doc/design/ext-llm.md` | `ext/llm` | -| `doc/design/ext-agent.md` | `ext/agent` agent **framework** (layout shipped; LLM orchestration roadmap) | -| `doc/design/ext-cli.md` | `marqdo ext list/add/remove` | -| `doc/design/ext-web.md` | `ext/web` dynamic sites (author API) | -| `doc/design/web-net-capabilities.md` | ext/web capability matrix (W0–W7 + P3) | -| `doc/design/ext-quantum.md` | `ext/quantum` circuits | -| `doc/design/ext-quantum-q7.md` | Q7 density linear algebra + advanced SVG | -| `doc/design/ext-quantum-viz-style.md` | Q8 themed SVG (`dark`/`light`/`bw`; circuit/probs/bloch) | -| `doc/design/view-debug.md` | view / debug hosts | +Use [the recursive Markdown web example](../../examples/web-layout-handbook/index.mq.md) and [the quantum workflow](../../examples/quantum-entanglement/index.mq.md) for domain development. Their real source is the manual. [Classic migration context](migration-classic.md) remains for explicitly historical syntax; new programs use readable occlusion and access(collection, key). Do not copy a second fenced program from this discovery note. diff --git a/src/call.rs b/src/call.rs index 7704e65..0799abf 100644 --- a/src/call.rs +++ b/src/call.rs @@ -117,6 +117,8 @@ pub struct CallOptions { pub fs_root: Option<std::path::PathBuf>, pub session: Option<String>, pub toget: Option<String>, + /// JSON transport values are literal data, including leading $ and @. + pub literal_args: bool, } /// Call `function` in `path` with named arguments (pure-only, no session). @@ -146,7 +148,7 @@ pub fn call_file_with( ) })?; - let mut session = if opts.session.is_some() || opts.toget.is_some() || args_need_session(args) { + let mut session = if opts.session.is_some() || opts.toget.is_some() || (!opts.literal_args && args_need_session(args)) { let id = opts .session .clone() @@ -156,7 +158,9 @@ pub fn call_file_with( None }; - let resolved = if let Some(ref mut sess) = session { + let resolved = if opts.literal_args { + args.to_vec() + } else if let Some(ref mut sess) = session { crate::call_session::resolve_args(sess, args, backend)? } else { args.to_vec() @@ -185,6 +189,9 @@ pub fn call_file_with( opts.toget.as_deref(), &value, )?; + if let Some(step) = sess.steps.last_mut() { + step.literal_args = opts.literal_args; + } crate::call_session::save_session(sess)?; } @@ -276,6 +283,7 @@ fn execute_source_function_with_root( fs_root: Option<&Path>, ) -> Result<(Value, String)> { let module = load_module(path)?; + let source = std::fs::read_to_string(path)?; let fun = find_function_at_line(&module.functions, line).ok_or_else(|| { call_diag( Some(path), @@ -297,6 +305,7 @@ fn execute_source_function_with_root( )); } let mut host = HostContext::for_capture(Some(path), caps); + host.set_entry_source(Some(path), &source); if let Some(root) = fs_root { let root = root.canonicalize()?; if !root.is_dir() { @@ -338,6 +347,7 @@ fn execute_source_function_with_root( ) })?; let mut host = HostContext::for_capture(Some(path), caps); + host.set_entry_source(Some(path), &source); if let Some(root) = fs_root { let root = root.canonicalize()?; host.cwd = root.clone(); @@ -404,6 +414,13 @@ pub fn parse_call_args(tokens: &[String]) -> Result<Vec<(String, Value)>> { Ok(out) } +/// Decode a JSON object of literal arguments with the standard safe-JSON domain. +/// Unlike command-line $name syntax, JSON strings remain data during replay. +pub fn parse_call_args_json(source: &str) -> Result<Vec<(String, Value)>> { + crate::host::json::decode_arguments(source) + .map_err(|message| call_diag(None, 0, "call.bad_value", message)) +} + fn locate_artifact<'a>( project: &'a SemanticProject, entry: &Path, @@ -526,6 +543,8 @@ fn parse_literal(raw: &str) -> Result<Value, String> { if raw.starts_with('$') || raw.starts_with('@') { return Ok(Value::Text(raw.to_string())); } + // Preserve the existing name=value raw-quoted text transport. Escaped, + // structured and multiline data uses the explicit --args-json channel. if raw.len() >= 2 { let bytes = raw.as_bytes(); if (bytes[0] == b'"' && bytes[raw.len() - 1] == b'"') diff --git a/src/call_session.rs b/src/call_session.rs index fd060e4..405e144 100644 --- a/src/call_session.rs +++ b/src/call_session.rs @@ -35,6 +35,8 @@ pub struct CallStep { pub function: String, pub args: BTreeMap<String, serde_json::Value>, pub effects: String, + #[serde(default, skip_serializing_if = "is_false")] + pub literal_args: bool, #[serde(default, skip_serializing_if = "Option::is_none")] pub result: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -43,6 +45,8 @@ pub struct CallStep { pub toget: Option<String>, } +fn is_false(value: &bool) -> bool { !*value } + fn sessions_root() -> PathBuf { if let Ok(p) = std::env::var("MARQDO_CALL_SESSION_DIR") { return PathBuf::from(p); @@ -179,7 +183,7 @@ fn replay_live(session: &CallSession, backend: Backend) -> Result<BTreeMap<Strin for (k, jv) in &step.args { let mut val = json_to_value(jv).map_err(|e| anyhow::anyhow!(e))?; if let Value::Text(t) = &val { - if t.starts_with('$') || t.starts_with('@') { + if !step.literal_args && (t.starts_with('$') || t.starts_with('@')) { let key = &t[1..]; val = live .get(key) @@ -249,6 +253,7 @@ pub fn record_step( function: function.to_string(), args: arg_map, effects: effects.as_str(), + literal_args: false, result: if is_json_friendly(result) { value_to_json(result).ok() } else { @@ -321,6 +326,7 @@ mod write_snapshot_tests { fs::write(dir.join("log.txt"), "once").unwrap(); for backend in [Backend::Tree, Backend::Bytecode] { let step = CallStep { + literal_args: false, file: Path::new(env!("CARGO_MANIFEST_DIR")) .join("lib/fs.mq.md") .to_string_lossy() diff --git a/src/ext_cli.rs b/src/ext_cli.rs index e15f6ad..5266036 100644 --- a/src/ext_cli.rs +++ b/src/ext_cli.rs @@ -18,6 +18,12 @@ pub struct ExtPackage { } pub const CATALOG: &[ExtPackage] = &[ + ExtPackage { + id: "engineering", + description: "Native process, authenticated service and archive boundaries for executable handbooks", + mq_files: &["engineering/index.mq.md", "engineering/索引.mq.md"], + native_crate: Some("marqdo_plugin_engineering"), + }, ExtPackage { id: "llm", description: "OpenAI-compatible chat object (ext/ai/llm)", @@ -52,17 +58,28 @@ pub const CATALOG: &[ExtPackage] = &[ "data/cache.mq.md", "data/db.mq.md", "data/form.mq.md", + "data/表单.mq.md", + "data/admin.mq.md", + "data/后台.mq.md", + "data/view.mq.md", + "data/视图.mq.md", + "data/api.mq.md", "data/storage.mq.md", "security/index.mq.md", "security/auth.mq.md", + "security/鉴权.mq.md", + "security/tenant.mq.md", "security/rbac.mq.md", "security/oidc.mq.md", "net/index.mq.md", "net/http.mq.md", "net/url.mq.md", "net/websocket.mq.md", + "net/实时.mq.md", "web/index.mq.md", "web/web.mq.md", + "web/head.mq.md", + "web/页头.mq.md", "web/网页.mq.md", "web/_capability/index.mq.md", "web/page/index.mq.md", @@ -169,6 +186,7 @@ pub fn native_short_name(crate_or_id: &str) -> &str { "marqdo_plugin_llm" | "llm" => "llm", "marqdo_plugin_quantum" | "quantum" => "quantum", "marqdo_plugin_linalg" | "linalg" => "linalg", + "marqdo_plugin_engineering" | "engineering" => "engineering", other => other, } } @@ -190,6 +208,7 @@ pub fn native_env_var(short: &str) -> &'static str { "llm" => "MARQDO_LLM_PLUGIN", "quantum" => "MARQDO_QUANTUM_PLUGIN", "linalg" => "MARQDO_LINALG_PLUGIN", + "engineering" => "MARQDO_ENGINEERING_PLUGIN", _ => "MARQDO_AGENT_PLUGIN", } } @@ -605,7 +624,7 @@ pub fn remove_ext(id: &str) -> Result<()> { /// point at a freshly built plugin path. pub fn installed_native_path(name: &str) -> Option<PathBuf> { let short = native_short_name(name); - if !matches!(short, "agent" | "web" | "llm" | "quantum" | "linalg") { + if !CATALOG.iter().any(|package| package.id == short && package.native_crate.is_some()) { return None; } let lib_name = native_lib_filename(short); @@ -650,6 +669,7 @@ pub fn path_is_trusted_plugin(path: &Path) -> bool { "MARQDO_LLM_PLUGIN", "MARQDO_QUANTUM_PLUGIN", "MARQDO_LINALG_PLUGIN", + "MARQDO_ENGINEERING_PLUGIN", ] { if let Ok(p) = env::var(key) { let p = PathBuf::from(p); @@ -659,7 +679,7 @@ pub fn path_is_trusted_plugin(path: &Path) -> bool { } } } - for short in ["agent", "web", "llm", "quantum", "linalg"] { + for short in CATALOG.iter().filter_map(|p| p.native_crate).map(native_short_name) { if let Ok(found) = find_native_plugin(short) { let found = found.canonicalize().unwrap_or(found); if found == path { diff --git a/src/host/dispatch.rs b/src/host/dispatch.rs index 8a18bff..d3d1cfd 100644 --- a/src/host/dispatch.rs +++ b/src/host/dispatch.rs @@ -290,6 +290,8 @@ pub enum HostFn { ListIntersection = 280, ListDifference = 281, TableSummarize = 282, + DocumentTable = 283, + FsResolve = 284, } /// Single source of truth for every host function. `<TAB>` slimming @@ -578,6 +580,8 @@ pub const HOST_FN_TABLE: &[HostFnDef] = &[ HostFnDef { id: 280, f: HostFn::ListIntersection, name: "host_table_intersection", required: &["a", "b"], optional: &[] }, HostFnDef { id: 281, f: HostFn::ListDifference, name: "host_table_difference", required: &["a", "b"], optional: &[] }, HostFnDef { id: 282, f: HostFn::TableSummarize, name: "host_table_summarize", required: &["list", "key", "field"], optional: &["op"] }, + HostFnDef { id: 283, f: HostFn::DocumentTable, name: "host_document_table", required: &["text"], optional: &["title", "index"] }, + HostFnDef { id: 284, f: HostFn::FsResolve, name: "host_fs_resolve", required: &["path"], optional: &[] }, ]; @@ -610,6 +614,8 @@ impl HostFn { "host_document_links" => Self::DocumentLinks, "host_document_replace_table" => Self::DocumentReplaceTable, "host_document_tables" => Self::DocumentTables, + "host_document_table" => Self::DocumentTable, + "host_fs_resolve" => Self::FsResolve, "host_document_replace_section" => Self::DocumentReplaceSection, "host_document_section" => Self::DocumentSection, "host_document_sections" => Self::DocumentSections, @@ -897,6 +903,8 @@ impl HostFn { Self::DocumentLinks => &["pure"], Self::DocumentReplaceTable => &["pure"], Self::DocumentTables => &["pure"], + Self::DocumentTable => &["pure"], + Self::FsResolve => &["fs.read"], Self::DocumentReplaceSection => &["pure"], Self::DocumentSection => &["pure"], Self::DocumentSections => &["pure"], @@ -1206,6 +1214,7 @@ pub fn call_host( HostFn::DocumentLinks => super::document::call(ctx, fn_id, bound), HostFn::DocumentReplaceTable => super::document::call(ctx, fn_id, bound), HostFn::DocumentTables => super::document::call(ctx, fn_id, bound), + HostFn::DocumentTable => super::document::call(ctx, fn_id, bound), HostFn::DocumentReplaceSection => super::document::call(ctx, fn_id, bound), HostFn::DocumentSection => super::document::call(ctx, fn_id, bound), HostFn::DocumentSections => super::document::call(ctx, fn_id, bound), @@ -1275,6 +1284,7 @@ pub fn call_host( HostFn::FsMakeDirs => fs::make_dirs(ctx, require(bound, "path")?), HostFn::FsRemoveTree => fs::remove_tree(ctx, require(bound, "path")?), HostFn::FsStat => fs::stat(ctx, require(bound, "path")?), + HostFn::FsResolve => fs::resolve(ctx, require(bound, "path")?), HostFn::FsWalk => fs::walk(ctx, require(bound, "path")?), HostFn::NowUnix => time::now_unix(), HostFn::NowMs => time::now_ms(), diff --git a/src/host/document.rs b/src/host/document.rs index 3da5ff1..7e99646 100644 --- a/src/host/document.rs +++ b/src/host/document.rs @@ -157,6 +157,46 @@ fn tables(text: &str) -> Vec<Table> { } out } +fn literal_value(expression: crate::ast::Expr) -> Result<Value, String> { + use crate::ast::{Expr, Literal}; + match expression { + Expr::Literal(literal) => Ok(match literal { + Literal::None => Value::None, + Literal::Bool(value) => Value::Bool(value), + Literal::Int(value) => Value::Int(value), + Literal::Num(value) => Value::Num(value), + Literal::Text(value) => Value::Text(value), + }), + Expr::Unary { op: crate::ast::UnaryOp::Neg, expr } => match literal_value(*expr)? { + Value::Int(value) => value.checked_neg().map(Value::Int).ok_or_else(|| "negative table literal overflows an integer".into()), + Value::Num(value) => Ok(Value::Num(-value)), + _ => Err("negative table literal requires a number".into()), + }, + Expr::List(values) => values.into_iter().map(literal_value) + .collect::<Result<Vec<_>, _>>().map(Value::List), + Expr::Map(fields) => fields.into_iter() + .map(|(key, value)| literal_value(value).map(|value| (key, value))) + .collect::<Result<Vec<_>, _>>().map(Value::Map), + _ => Err("document.table accepts literal data cells; variable references, interpolation and calls are not evaluated".into()), + } +} +fn table_value(source: &str, title: Option<&str>, index: usize) -> Result<Value, String> { + let section_list; + let selected = if let Some(title) = title { + section_list = sections(source); + let section = unique_section(§ion_list, title)?; + &source[section.body..section.end] + } else { + source + }; + let found = tables(selected); + let table = found.get(index).ok_or_else(|| format!( + "document.table index {index} is out of range ({} tables)", found.len()))?; + let expression = crate::parse::parse_gfm_table(&selected[table.start..table.end]) + .map_err(|error| format!("document.table: {error:#}"))?; + literal_value(expression) +} + fn check_digest(b: &Args, text: &str) -> Result<(), String> { if let Some(Value::Text(expected)) = b.get("expected_sha256") { if format!("{:x}", Sha256::digest(text.as_bytes())) != *expected { @@ -232,6 +272,19 @@ pub(super) fn call(_ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value }) .collect(), )), + HostFn::DocumentTable => { + let title = match b.get("title") { + None | Some(Value::None) => None, + Some(value) => Some(as_text(value, "title")?), + }; + let index = match b.get("index") { + None | Some(Value::None) => 0, + Some(Value::Int(value)) if *value >= 0 => + usize::try_from(*value).map_err(|_| "table index too large")?, + _ => return Err("table index must be a zero-based nonnegative integer".into()), + }; + table_value(source, title, index) + } HostFn::DocumentReplaceTable => { let change = (|| { check_digest(b, source)?; @@ -356,3 +409,47 @@ pub(super) fn call(_ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value _ => Err("not a document operation".into()), } } + +#[cfg(test)] +mod literal_table_tests { + use super::*; + #[test] + fn literal_values_retain_native_record_column_and_list_shapes() { + let source="# 数据\n\n| @ | name | enabled | count |\n|---|---|---|---|\n| 1 | 中国 | True | 3 |\n"; + let actual=table_value(source,Some("数据"),0).unwrap(); + assert_eq!(actual,Value::List(vec![Value::Map(vec![ + ("name".into(),Value::Text("中国".into())), + ("enabled".into(),Value::Bool(true)), + ("count".into(),Value::Int(3)), + ])])); + assert_eq!(table_value("| number |\n|---|\n| 1 |\n| 2 |\n",None,0).unwrap(),Value::List(vec![Value::Int(1),Value::Int(2)])); + let columns=table_value("| key | value |\n|---|---|\n| a | 1 |\n| b | 2 |\n",None,0).unwrap(); + assert!(matches!(columns,Value::Map(fields) if fields.iter().all(|(_, value)|matches!(value,Value::List(_))))); + } + #[test] + fn negative_numbers_none_and_false_keep_their_literal_types() { + let source="| values |\n|---|\n| -3 |\n| -0.5 |\n| None |\n| False |\n"; + assert_eq!(table_value(source,None,0).unwrap(),Value::List(vec![ + Value::Int(-3),Value::Num(-0.5),Value::None,Value::Bool(false), + ])); + } + #[test] + fn unique_sections_and_indices_skip_fenced_examples() { + let source="```text\n| code |\n|---|\n| hidden |\n```\n\n# first\n\n| x | y |\n|---|---|\n| 1 | 2 |\n\n# second\n\n| x | y |\n|---|---|\n| 3 | 4 |\n"; + let second=Value::Map(vec![("x".into(),Value::Int(3)),("y".into(),Value::Int(4))]); + assert_eq!(table_value(source,Some("second"),0).unwrap(),second); + assert_eq!(table_value(source,None,1).unwrap(),second); + assert!(table_value("# same\n\n# same\n",Some("same"),0).unwrap_err().contains("ambiguous")); + assert!(table_value(source,None,2).unwrap_err().contains("out of range")); + } + #[test] + fn rejects_dynamic_cells_duplicate_headers_and_silent_truncation() { + for source in ["| value |\n|---|\n| `outside` |\n","| x | x |\n|---|---|\n| a | b |\n","| x | y |\n|---|---|\n| a | b | extra |\n"] { + assert!(table_value(source,None,0).is_err(),"accepted {source}"); + } + let escaped="| @ | text | flag |\n|---|---|---|\n| 1 | left\\|right | False |\n"; + assert_eq!(table_value(escaped,None,0).unwrap(),Value::List(vec![Value::Map(vec![ + ("text".into(),Value::Text("left|right".into())),("flag".into(),Value::Bool(false)), + ])])); + } +} diff --git a/src/host/foreign_doc.rs b/src/host/foreign_doc.rs index 0151043..fdb9ffe 100644 --- a/src/host/foreign_doc.rs +++ b/src/host/foreign_doc.rs @@ -407,7 +407,7 @@ impl DocumentSession { let entry = module .functions .iter() - .find(|f| f.name == "main" && f.is_object()) + .find(|f| f.name == "main") .or_else(|| { let objs: Vec<_> = module.functions.iter().filter(|f| f.is_object()).collect(); if objs.len() == 1 { @@ -416,7 +416,7 @@ impl DocumentSession { None } }) - .ok_or_else(|| "notebook: no `# main` (or sole object) to index".to_string())?; + .ok_or_else(|| "notebook: no `main` entry (or sole object) to index".to_string())?; let mut cells = Vec::new(); let mut seen = HashSet::new(); collect_cells(&entry.body, &mut cells, &mut seen)?; diff --git a/src/host/fs.rs b/src/host/fs.rs index 1fcf828..9610dba 100644 --- a/src/host/fs.rs +++ b/src/host/fs.rs @@ -32,6 +32,24 @@ fn text_body(v: &Value) -> Result<&str, String> { } } +/// Return the logical absolute path checked by native filesystem operations. +pub fn resolve(ctx: &HostContext, path: &Value) -> Result<Value, String> { + let checked = ctx.resolve_path(text_path(path)?)?; + let absolute = if checked.is_absolute() { checked } else { + std::env::current_dir().map_err(|error| error.to_string())?.join(checked) + }; + let mut normalized = std::path::PathBuf::new(); + for component in absolute.components() { + match component { + std::path::Component::CurDir => {}, + std::path::Component::ParentDir => { normalized.pop(); }, + component => normalized.push(component.as_os_str()), + } + } + normalized.to_str().map(|value| Value::Text(value.to_owned())) + .ok_or_else(|| "resolved filesystem path is not UTF-8".into()) +} + pub fn read_text(ctx: &HostContext, path: &Value) -> Result<Value, String> { let p = ctx.resolve_path(text_path(path)?)?; if let Some(hit) = crate::host::sandbox_fs::cow_read_text(ctx, &p)? { diff --git a/src/host/json.rs b/src/host/json.rs index 344da93..5559401 100644 --- a/src/host/json.rs +++ b/src/host/json.rs @@ -97,6 +97,41 @@ pub(crate) fn decode_text(text: &str) -> Result<Value, DecodeError> { Ok(value.0) } + +/// The call protocol envelope is not a runtime column table. Validate each +/// actual argument with BoundaryValue while keeping duplicate-key detection. +pub(crate) fn decode_arguments(text: &str) -> Result<Vec<(String, Value)>, String> { + use serde::Deserialize; + struct Arguments(Vec<(String, Value)>); + impl<'de> serde::Deserialize<'de> for Arguments { + fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self,D::Error> { + struct Visitor; + impl<'de> serde::de::Visitor<'de> for Visitor { + type Value = Arguments; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a JSON object of named arguments") + } + fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Arguments,A::Error> { + use serde::de::Error; + let mut args = Vec::new(); + let mut keys = std::collections::HashSet::new(); + while let Some(key) = map.next_key::<String>()? { + if !keys.insert(key.clone()) { return Err(A::Error::custom("duplicate argument name")); } + let BoundaryValue(value) = map.next_value()?; + args.push((key, value)); + } + Ok(Arguments(args)) + } + } + de.deserialize_map(Visitor) + } + } + let mut de = serde_json::Deserializer::from_str(text); + let args = Arguments::deserialize(&mut de).map_err(|e| e.to_string())?; + de.end().map_err(|e| e.to_string())?; + Ok(args.0) +} + pub fn parse(text: &Value) -> Result<Value, String> { let s = match text { Value::Text(s) => s.as_str(), diff --git a/src/host/plugin.rs b/src/host/plugin.rs index ce4af87..b6f13f9 100644 --- a/src/host/plugin.rs +++ b/src/host/plugin.rs @@ -530,10 +530,26 @@ unsafe extern "C" fn host_query( .get("path") .and_then(|v| v.as_str()) .ok_or_else(|| "run_artifact requires `path`".to_string())?; - let p = std::path::PathBuf::from(path); + let p = ctx.resolve_path(path)?; if !p.is_file() { return Err(format!("run_artifact: not a file: {path}")); } + // A web site may narrow an existing filesystem grant. Child + // Documents keep that explicit root instead of defaulting to pages/. + let fs_root = match args.get("root") { + None | Some(serde_json::Value::Null) => ctx.fs_root.clone(), + Some(serde_json::Value::String(root)) => { + let selected = ctx.resolve_path(root)?; + if !selected.is_dir() { return Err("run_artifact: root is not a directory".into()); } + let actual = p.canonicalize().map_err(|_| "run_artifact: cannot resolve source")?; + let base = selected.canonicalize().map_err(|_| "run_artifact: cannot resolve root")?; + if !actual.starts_with(&base) { + return Err("run_artifact: source is outside selected site root".into()); + } + Some(selected) + } + Some(_) => return Err("run_artifact: root must be text".into()), + }; let mut binds: Vec<(String, String)> = Vec::new(); if let Some(obj) = args.get("args").and_then(|v| v.as_object()) { for (k, v) in obj { @@ -547,6 +563,7 @@ unsafe extern "C" fn host_query( } let opts = crate::RunOptions { binds, + fs_root, allow_fs_write: ctx.caps.fs_write, allow_exec: ctx.caps.exec, allow_net: ctx.caps.net, diff --git a/src/host/writeback.rs b/src/host/writeback.rs index 91ad329..7a65e8d 100644 --- a/src/host/writeback.rs +++ b/src/host/writeback.rs @@ -495,28 +495,38 @@ fn append_eof(source: &str, block: &str) -> String { trimmed } +fn entry_target(path: &std::path::Path) -> Result<std::path::PathBuf,String> { + if path.is_absolute() { return Ok(path.to_path_buf()); } + // Entry paths originate at the caller's process cwd, as in the runner. + std::env::current_dir().map(|base|base.join(path)).map_err(|e|format!("writeback entry path: {e}")) +} +fn entry_path_text(path: &std::path::Path) -> Result<Value,String> { + let path=entry_target(path)?; + Ok(Value::Text(path.to_str().ok_or("writeback path must be UTF-8")?.to_string())) +} fn persist(ctx: &mut HostContext, source: &str) -> Result<(), String> { if !ctx.allow_fs_write() { return Err("writeback disabled (fs_write capability off)".into()); } - let path = ctx - .entry_path - .as_ref() - .ok_or_else(|| "writeback: no entry file".to_string())?; - std::fs::write(path, source).map_err(|e| format!("writeback write {}: {e}", path.display()))?; - ctx.entry_source = Some(source.to_string()); + let path=ctx.entry_path.as_ref().ok_or("writeback: no entry file")?; + let path=entry_path_text(path)?; + // Use the same root, symlink and CoW rules as ordinary native file writes. + super::fs::write_text(ctx,&path,&Value::Text(source.to_string()))?; + ctx.entry_source=Some(source.to_string()); Ok(()) } - fn load_entry_source(ctx: &HostContext) -> Result<String, String> { - if let Some(path) = &ctx.entry_path { - if let Ok(text) = std::fs::read_to_string(path) { - return Ok(text); + if let Some(path)=&ctx.entry_path { + let target=entry_target(path)?; + match super::fs::read_text(ctx,&entry_path_text(path)?) { + Ok(Value::Text(text))=>return Ok(text), + Ok(_)=>return Err("writeback entry source must be text".into()), + // In-memory entry buffers may intentionally precede file creation. + Err(_) if !target.exists()=>{}, + Err(error)=>return Err(error), } } - ctx.entry_source - .clone() - .ok_or_else(|| "writeback: no entry source".to_string()) + ctx.entry_source.clone().ok_or_else(||"writeback: no entry source".to_string()) } fn with_writeback_lock<T>(f: impl FnOnce() -> Result<T, String>) -> Result<T, String> { diff --git a/src/main.rs b/src/main.rs index 23299b3..069e651 100644 --- a/src/main.rs +++ b/src/main.rs @@ -175,6 +175,16 @@ enum Commands { #[arg(long, default_value = "none")] effects: String, + /// Literal named arguments as a JSON object; '-' reads stdin (no shell/argv size limit). + /// JSON strings never resolve call-session $name or @name references. + #[arg(long, value_name = "FILE_OR_STDIN")] + args_json: Option<PathBuf>, + + /// Return a failing exit status when the function returns Result {ok:false}. + /// The JSON result is preserved; no effect is retried or rolled back. + #[arg(long)] + require_ok: bool, + /// Directory available to file tools; defaults to the called file directory. #[arg(long)] fs_root: Option<PathBuf>, @@ -850,6 +860,8 @@ fn try_main(cli: Cli) -> Result<i32> { file, function, args, + args_json, + require_ok, json, backend, effects, @@ -861,16 +873,32 @@ fn try_main(cli: Cli) -> Result<i32> { let effects = marqdo::call::CallEffects::parse(&effects)?; let (arg_tokens, trailing_toget) = marqdo::call::split_toget(&args)?; let toget = toget.or(trailing_toget); - let parsed = marqdo::call::parse_call_args(&arg_tokens)?; + let literal_args = args_json.is_some(); + let parsed = if let Some(input) = args_json { + use std::io::Read; + if !arg_tokens.is_empty() { + anyhow::bail!("--args-json cannot be combined with name=value arguments"); + } + let mut source = String::new(); + if input.as_os_str() == "-" { + std::io::stdin().take(64 * 1024 * 1024 + 1).read_to_string(&mut source)?; + } else { + std::fs::File::open(&input)?.take(64 * 1024 * 1024 + 1).read_to_string(&mut source)?; + } + if source.len() > 64 * 1024 * 1024 { anyhow::bail!("--args-json exceeds 64 MiB"); } + marqdo::call::parse_call_args_json(&source)? + } else { + marqdo::call::parse_call_args(&arg_tokens)? + }; let session = session.or_else(|| { if toget.is_some() - || parsed.iter().any(|(_, v)| { + || (!literal_args && parsed.iter().any(|(_, v)| { matches!( v, marqdo::value::Value::Text(t) if t.starts_with('$') || t.starts_with('@') ) - }) + })) { Some(marqdo::call_session::default_session_id()) } else { @@ -887,6 +915,7 @@ fn try_main(cli: Cli) -> Result<i32> { fs_root, session, toget, + literal_args, }, ) })(); @@ -902,7 +931,10 @@ fn try_main(cli: Cli) -> Result<i32> { } else { println!("{}", value.as_display()); } - Ok(0) + let failed = require_ok && matches!(&value, + marqdo::value::Value::Map(fields) if fields.iter().any(|(k,v)| + k == "ok" && matches!(v, marqdo::value::Value::Bool(false)))); + Ok(if failed { 1 } else { 0 }) } Err(err) => { let diag = Diagnostic::find(&err).cloned().unwrap_or_else(|| { diff --git a/src/parse/expr.rs b/src/parse/expr.rs index 3ef18b1..6ed2e4c 100644 --- a/src/parse/expr.rs +++ b/src/parse/expr.rs @@ -124,7 +124,9 @@ fn parse_call_arg_value_mode(input: &str, prefer_var: bool, allow_call: bool) -> Err(_) => Ok(parse_interp(s)), }; } - if has_hyphenated_prose(s) { + // Nested calls may contain hyphenated paths in their own quoted args. + // The inner argument parser still preserves plain hyphenated prose. + if has_hyphenated_prose(s) && !(allow_call && s.contains('(')) { return Ok(parse_interp(s)); } match parse_expr_opts(s, prefer_var, allow_call) { @@ -577,6 +579,16 @@ impl<'a> Parser<'a> { if !self.eat("`") { bail!("unterminated `name`"); } + // Parse a quoted receiver's explicit method before its value. + if self.allow_paren_call && self.rest().starts_with('.') { + let call_start = start - 1; + if let Some((call, used)) = try_paren_call(&self.src[call_start..], self.prefer_var)? { + if call.receiver.is_some() { + self.i = call_start + used; + return Ok(Expr::Call(call)); + } + } + } return self.parse_index_chain(Expr::Var(name)); } // `礼貌 [问候] x` — after quotes/ticks so `[DONE]` inside strings is safe. @@ -1109,11 +1121,13 @@ pub fn parse_call_tail(s: &str, prefer_var: bool) -> Result<(CallExpr, usize)> { } let callee_tok = { - let mut parts = s.split_whitespace(); - parts - .next() - .ok_or_else(|| anyhow::anyhow!("missing callee"))? - .to_string() + let mut quoted = false; + let end = s.char_indices().find_map(|(i,c)| { + if c == '`' { quoted = !quoted; } + (!quoted && (c.is_whitespace() || c == ')')).then_some(i) + }).unwrap_or(s.len()); + if end == 0 { bail!("missing callee"); } + s[..end].to_string() }; let (receiver, callee, path) = split_callee(&callee_tok); @@ -1435,7 +1449,7 @@ fn try_named_arg(s: &str) -> Option<(String, &str)> { } return Some((key.to_string(), &s[i + 1..])); } - if c.is_whitespace() { + if c.is_whitespace() || matches!(c, '(' | ')' | '[' | ']' | '{' | '}' | ',' | '"' | '\'' | '`') { return None; } } @@ -1695,6 +1709,31 @@ pub fn parse_call_after_gt(after_gt: &str, prefer_var: bool) -> Result<CallExpr> mod tests { use super::*; + #[test] + fn occlusion_keeps_receiver_calls_and_closing_delimiters_separate() { + for source in ["[Read probabilities](`c`.probabilities())", +"[Read probabilities](> `c`.probabilities)", +"[Set angle](`c`.rotate(angle=access(m, \"angle\")))"] { + let e = parse_expr_markup(source,true,Markup::Occlusion).unwrap(); + let Expr::Occluded { payload: Some(payload), .. } = e else { panic!("{source}") }; + let Expr::Call(call) = *payload else { panic!("{source}") }; + assert_eq!(call.receiver.as_deref(),Some("c")); + assert!(!call.callee.contains(')')); + } + assert!(parse_expr_markup("[Read file size](access(fs.stat(path=\"a\"), \"size\"))", + true,Markup::Occlusion).is_ok()); + } + + + + #[test] + fn nested_call_with_a_hyphenated_file_path_stays_executable() { + let e = parse_expr_prefer_var("toml.parse(text=fs.read_text(path=\"crates/marqdo-wasm/Cargo.toml\"))").unwrap(); + let Expr::Call(c) = e else { panic!("expected outer call") }; + let crate::ast::Arg::Named { value, .. } = &c.args[0] else { panic!("expected named argument") }; + assert!(matches!(value, Expr::Call(_)), "{value:?}"); + } + #[test] fn bare_var_footnote_index() { let e = parse_expr("ev[^result]").unwrap(); diff --git a/src/parse/mod.rs b/src/parse/mod.rs index e12f06d..a67398f 100644 --- a/src/parse/mod.rs +++ b/src/parse/mod.rs @@ -13,6 +13,7 @@ pub use prose::{ }; use anyhow::{bail, Result}; +use std::collections::HashSet; use crate::ast::{ BranchArm, Expr, Function, Import, IndexKey, Literal, Module, Param, Stmt, Use, @@ -44,7 +45,7 @@ pub fn parse_classified(lines: &[ClassifiedLine]) -> Result<Module> { continue; } if is_heading(trimmed) { - functions.push(cur.parse_function(1)?); + functions.push(cur.parse_function(1, &HashSet::new())?); } else if line.kind == LineKind::Comment { // Intro paragraphs may still contain return-shaped italics (`返回*值*`) // or leftover soft emphasis; executable prose belongs inside functions. @@ -78,6 +79,18 @@ pub fn parse_classified(lines: &[ClassifiedLine]) -> Result<Module> { Ok(module) } +/// Parse one GFM table with the source language's cell and shape rules. +/// Document readers reject nonliteral expressions before using the value. +pub(crate) fn parse_gfm_table(source: &str) -> Result<Expr> { + let lines = classify_source(source); + let mut cursor = Cursor::new(&lines); + let table = cursor.consume_table()?; + if cursor.skip_noise() { + bail!("unexpected content after the selected GFM table"); + } + Ok(table) +} + struct Cursor<'a> { lines: &'a [ClassifiedLine], i: usize, @@ -282,7 +295,7 @@ impl<'a> Cursor<'a> { Ok(()) } - fn parse_function(&mut self, min_level: u8) -> Result<Function> { + fn parse_function(&mut self, min_level: u8, inherited: &HashSet<String>) -> Result<Function> { let line = self.bump().unwrap(); let (level, raw_name) = parse_heading(line.text.trim()) .ok_or_else(|| anyhow::anyhow!("{}:1: expected heading", line.line_no))?; @@ -317,7 +330,13 @@ impl<'a> Cursor<'a> { if is_heading(trimmed) { let (nl, _) = parse_heading(trimmed).unwrap(); if nl > level { - fun.children.push(self.parse_function(level + 1)?); + let mut visible = inherited.clone(); + let mut unused_reads = HashSet::new(); + let mut unused_declarations = Vec::new(); + collect_names_needing_input(&fun.body, &mut visible, &mut unused_reads, &HashSet::new(), &mut unused_declarations); + visible.extend(prose_decls.iter().map(|(name, _, _)| name.clone())); + visible.extend(fun.params.iter().map(|param| param.name.clone())); + fun.children.push(self.parse_function(level + 1, &visible)?); continue; } break; @@ -369,7 +388,13 @@ impl<'a> Cursor<'a> { if is_heading(trimmed) { let (nl, _) = parse_heading(trimmed).unwrap(); if nl > level { - fun.children.push(self.parse_function(level + 1)?); + let mut visible = inherited.clone(); + let mut unused_reads = HashSet::new(); + let mut unused_declarations = Vec::new(); + collect_names_needing_input(&fun.body, &mut visible, &mut unused_reads, &HashSet::new(), &mut unused_declarations); + visible.extend(prose_decls.iter().map(|(name, _, _)| name.clone())); + visible.extend(fun.params.iter().map(|param| param.name.clone())); + fun.children.push(self.parse_function(level + 1, &visible)?); continue; } break; @@ -445,7 +470,7 @@ impl<'a> Cursor<'a> { // 契约提取(T2.1)必须在升参推断**之前**:契约表的单元不污染推断。 extract_function_contract(&mut fun, self.lines)?; - merge_inferred_params(&mut fun, &prose_decls)?; + merge_inferred_params(&mut fun, &prose_decls, inherited)?; Ok(fun) } @@ -2104,11 +2129,15 @@ fn extract_function_contract(fun: &mut Function, lines: &[ClassifiedLine]) -> Re fn merge_inferred_params( fun: &mut Function, prose_decls: &[(String, Option<String>, u32)], + inherited: &HashSet<String>, ) -> Result<()> { use std::collections::HashSet; let mut needs_input = HashSet::new(); - let mut bound = HashSet::new(); + // Captured entry/object bindings are available before the child body. + // An explicit prose input still shadows an outer binding of the same name. + let explicit: HashSet<_> = prose_decls.iter().map(|(name, _, _)| name.clone()).collect(); + let mut bound: HashSet<_> = inherited.difference(&explicit).cloned().collect(); let mut assign_decls = Vec::new(); // Defaults execute before the body. Reads used only there still require // declared inputs; later body assignments cannot satisfy those reads. @@ -2129,6 +2158,8 @@ fn merge_inferred_params( &mut assign_decls, ); + needs_input.retain(|name| !inherited.contains(name) || explicit.contains(name)); + // Declaration order is source order: backtick mentions and first assignment // left-hand sides. An assignment promotes only when its right-hand side (or a // later read) still needs an external value. @@ -2211,7 +2242,7 @@ fn collect_names_needing_input( let mut reads = std::collections::HashSet::new(); collect_reads_expr(value, &mut reads); for r in reads { - if !bound.contains(&r) { + if !bound.contains(&r) && !loop_items.contains(&r) { needs.insert(r); } } @@ -2220,7 +2251,7 @@ fn collect_names_needing_input( let mut reads = std::collections::HashSet::new(); collect_reads_call(call, &mut reads); for r in reads { - if !bound.contains(&r) { + if !bound.contains(&r) && !loop_items.contains(&r) { needs.insert(r); } } @@ -2229,7 +2260,7 @@ fn collect_names_needing_input( let mut reads = std::collections::HashSet::new(); collect_reads_expr(value, &mut reads); for r in reads { - if !bound.contains(&r) { + if !bound.contains(&r) && !loop_items.contains(&r) { needs.insert(r); } } @@ -2242,7 +2273,7 @@ fn collect_names_needing_input( let mut reads = std::collections::HashSet::new(); collect_reads_expr(c, &mut reads); for r in reads { - if !bound.contains(&r) { + if !bound.contains(&r) && !loop_items.contains(&r) { needs.insert(r); } } @@ -2931,3 +2962,30 @@ mod escaped_gfm_cell_tests { assert!(format!("{:?}", module.functions[0].body).contains("source|skill")); } } + +#[cfg(test)] +mod lexical_input_tests { + use super::*; + #[test] + fn child_updates_capture_existing_entry_state_without_extra_inputs() { + let source="# main\n\n**count = 0**\n\n## bump\n\nWe **count = count + 1** and return *count*.\n"; + let module=parse_source(source).unwrap(); + assert!(module.functions[0].children[0].params.is_empty()); + } + #[test] + fn explicit_prose_inputs_can_shadow_parent_bindings() { + let source="# main\n\n**count = 0**\n\n## add\n\nUse `count` for this independent call.\nReturn *(count + 1)*.\n"; + let module=parse_source(source).unwrap(); + let params=&module.functions[0].children[0].params; + assert_eq!(params.len(),1); + assert_eq!(params[0].name,"count"); + } + #[test] + fn reading_a_loop_item_in_a_branch_does_not_promote_a_later_local() { + let source="## select\n\nUse `values`.\n- [Inspect values](for values as item)\n 1. `item` != \"\"\n We **output = item**.\n\nWe **item = \"done\"** and return *item*.\n"; + let module=parse_source(source).unwrap(); + let params=&module.functions[0].params; + assert_eq!(params.len(),1); + assert_eq!(params[0].name,"values"); + } +} diff --git a/src/parse/prose.rs b/src/parse/prose.rs index 672b6da..4e82f0c 100644 --- a/src/parse/prose.rs +++ b/src/parse/prose.rs @@ -292,7 +292,7 @@ fn scan_backtick_decl(line: &str, start: usize) -> Option<(ProseBit, usize)> { if let Some(stripped) = after.strip_prefix('=') { // Quoted defaults may contain prose delimiters, glob stars or spaces. // Keep the same quoted literal accepted by explicit parameter defaults. - let def_end = if let Some(quote @ ('"' | '\'')) = stripped.chars().next() { + let mut def_end = if let Some(quote @ ('"' | '\'')) = stripped.chars().next() { let mut escaped = false; stripped .char_indices() @@ -316,6 +316,13 @@ fn scan_backtick_decl(line: &str, start: usize) -> Option<(ProseBit, usize)> { }) .unwrap_or(stripped.len()) }; + // English sentence punctuation belongs to narration after a literal. + // Keep quoted strings, dotted names and decimal syntax unchanged. + if let Some(literal) = stripped[..def_end].strip_suffix('.') { + if matches!(literal, "True" | "False" | "true" | "false" | "None" | "真" | "假" | "无" | "空") { + def_end -= 1; + } + } let default = stripped[..def_end].to_string(); let next = after_tick + 1 + def_end; return Some(( @@ -389,6 +396,25 @@ mod tests { } } + #[test] + fn sentence_period_after_boolean_or_none_is_not_part_of_the_default() { + for (line, expected) in [ + ("Use `flag`=False. Continue.", "False"), + ("Use `flag`=True.", "True"), + ("Use `value`=None.", "None"), + ("使用`值`=假. 继续。", "假"), + ("Use `text`=\"False.\".", "\"False.\""), + ("Use `text`=module.value.", "module.value."), + ("Use `rate`=0.5.", "0.5."), + ] { + let bits = scan_prose_line(line); + match &bits[..] { + [ProseBit::Decl { default: Some(actual), .. }] => assert_eq!(actual, expected, "{line}"), + _ => panic!("unexpected prose scan: {bits:?}"), + } + } + } + #[test] fn quoted_defaults_keep_delimiters_and_escaped_quotes() { let line = r#"输入 `pattern`="**";`mime`="text/plain;charset=utf-8";`label`="a, b \"quoted\""。"#; diff --git a/src/view/html.rs b/src/view/html.rs index 3b722bc..98cebd7 100644 --- a/src/view/html.rs +++ b/src/view/html.rs @@ -4032,6 +4032,12 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM "stream", "Streaming in the panel below…".to_string(), ) + } else if vm.library_document { + ( + "pending", + "module", + "这是可调用模块,未自动执行。通过 marqdo call 选择函数并提供参数。".to_string(), + ) } else if vm.ok { ( "ok", @@ -4047,7 +4053,7 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM } else { ("fail", "fail", escape(&vm.stderr)) }; - let stdin_panel = if vm.input_prompts.is_empty() { + let stdin_panel = if vm.library_document || vm.input_prompts.is_empty() { String::new() } else { let placeholder = vm.input_prompts.join("\n"); diff --git a/src/view/mod.rs b/src/view/mod.rs index fbe4431..64c9a32 100644 --- a/src/view/mod.rs +++ b/src/view/mod.rs @@ -430,9 +430,18 @@ pub(crate) fn build_file_view_with_exec( Vec::new(), ), }; + // Named tools are readable modules, not failed programs. Preserve actual + // execution for main, object entries and Artifact declarations. + let library_document = module_opt.as_ref().is_some_and(|module| { + !module.functions.is_empty() + && module.functions.iter().all(|f| !f.is_object() && f.name != "main") + && !module.metadata_raw.iter().any(|(key, _)| key == "type" || key == "类型") + }); let effective = effective_stdin(&source, stdin_lines); - let awaiting_input = awaiting_preset_input(&input_prompts, stdin_lines, &source); - let show_stream = module_opt.as_ref().map(uses_stream_panel).unwrap_or(false); + let awaiting_input = !library_document + && awaiting_preset_input(&input_prompts, stdin_lines, &source); + let show_stream = !library_document + && module_opt.as_ref().map(uses_stream_panel).unwrap_or(false); // Live + LLM/agent import + has `input` + stdin ready → stream via client `/api/run`. let auto_stream = live && show_stream @@ -454,6 +463,14 @@ pub(crate) fn build_file_view_with_exec( Vec::new(), String::from(r#"<p class="vars-skipped">skipped</p>"#), ) + } else if library_document { + ( + String::new(), + String::new(), + true, + Vec::new(), + String::from(r#"<p class="vars-skipped">Choose a named function with marqdo call.</p>"#), + ) } else if awaiting_input || auto_stream { ( String::new(), @@ -481,7 +498,7 @@ pub(crate) fn build_file_view_with_exec( } }; // Re-read after run so writeback slots / workbook edits show in Structure. - if execute && !awaiting_input && !auto_stream { + if execute && !library_document && !awaiting_input && !auto_stream { if let Ok(next) = fs::read_to_string(abs) { source = next; } @@ -579,6 +596,7 @@ pub(crate) fn build_file_view_with_exec( stdout, stderr, ok, + library_document, preset_stdin: effective.join("\n"), input_prompts, awaiting_input, diff --git a/src/view/render.rs b/src/view/render.rs index 2aaf0fd..da40e87 100644 --- a/src/view/render.rs +++ b/src/view/render.rs @@ -30,6 +30,8 @@ pub struct FileViewModel { pub stdout: String, pub stderr: String, pub ok: bool, + /// A callable-only module has no automatic program entry. + pub library_document: bool, /// Text shown in the live-view preset stdin box. pub preset_stdin: String, /// One entry per `input` / `输入` call (prompt text; may be empty). diff --git a/tests/browser_handbook.mjs b/tests/browser_handbook.mjs new file mode 100644 index 0000000..d3d8143 --- /dev/null +++ b/tests/browser_handbook.mjs @@ -0,0 +1,416 @@ +// Real-browser validation; development orchestration is skills/marqdo-dev/browser.mq.md. +import test from "node:test"; +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { createServer } from "node:net"; +import { once } from "node:events"; +import { fileURLToPath } from "node:url"; +import { chromium } from "../.marqdo/browser-tests/node_modules/playwright/index.mjs"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +const pause = ms => new Promise(resolve => setTimeout(resolve, ms)); +async function freePort() { + const listener = createServer(); + listener.listen(0, "127.0.0.1"); + await once(listener, "listening"); + const port = listener.address().port; + await new Promise(resolve => listener.close(resolve)); + return port; +} +async function serve(project, t, options = {}) { + const port = await freePort(); + const child = spawn(root + "target/debug/marqdo", [ + "call", project + "/index.mq.md", "serve", "--args-json", "-", + "--effects", options.effects || "plugin,fs.read,network.write", "--fs-root", project, "--json" + ], { + cwd: root, + env: { + ...process.env, + MARQDO_EXT: root + "ext", + MARQDO_LIB: root + "lib", + MARQDO_WEB_PLUGIN: root + "plugins/web/build/libweb.so" + }, + stdio: ["pipe", "pipe", "pipe"] + }); + child.stdin.end(JSON.stringify({...options.args, port})); + let logs = ""; + child.stdout.on("data", data => { logs = (logs + data).slice(-65536); }); + child.stderr.on("data", data => { logs = (logs + data).slice(-65536); }); + t.after(async () => { + if (child.exitCode === null && child.signalCode === null) { + child.kill("SIGTERM"); + await Promise.race([once(child, "exit"), pause(1000)]); + if (child.exitCode === null && child.signalCode === null) { + child.kill("SIGKILL"); + await once(child, "exit"); + } + } + if (options.cleanup) await options.cleanup(); + }); + const url = "http://127.0.0.1:" + port; + const deadline = Date.now() + 15000; + while (Date.now() < deadline) { + assert.equal(child.exitCode, null, "Marqdo call exited: " + logs); + try { + const response = await fetch(url); + if (response.ok) return { url, logs: () => logs }; + } catch (_) {} + await pause(40); + } + assert.fail("Marqdo call did not listen: " + logs); +} +async function openBrowser(t) { + const browser = await chromium.launch({ headless: true }); + t.after(() => browser.close()); + return browser; +} +async function waitText(page, selector, text) { + await page.waitForFunction(({selector,text}) => document.querySelector(selector)?.textContent === text, {selector,text}); +} +async function waitValue(page, selector, value) { + await page.waitForFunction(({selector,value}) => document.querySelector(selector)?.value === value, {selector,value}); +} +test("SPA uses current WASM for list/detail/edit and browser history", {timeout: 60000}, async t => { + const server = await serve("examples/web-spa-app", t); + const browser = await openBrowser(t); + const page = await browser.newPage(); + const errors = []; + page.on("pageerror", error => errors.push(String(error))); + try { + await page.goto(server.url); + await page.waitForSelector('#items li[data-id="1"]'); + assert.equal(await page.locator("#items li").count(), 2); + await page.locator('#items li[data-id="1"]').click(); + await waitText(page, "#title", "Detail"); + await waitText(page, "#detail-body", "Alpha"); + await page.locator("#btn-edit").click(); + await waitValue(page, "#edit-title", "Alpha"); + const title = 'A <tag> "quoted" & literal'; + await page.locator("#edit-title").fill(title); + await page.locator("#btn-save").click(); + await waitText(page, "#detail-body", title); + assert.equal(await page.locator('#items li[data-id="1"]').textContent(), title); + assert.equal(await page.locator("#items tag, #items script").count(), 0); + await page.locator("#nav-new").click(); + await page.locator("#edit-title").fill("Gamma"); + await page.locator("#btn-save").click(); + await page.waitForSelector('#items li[data-id="3"]', {state:"attached"}); + assert.equal(await page.locator("#items li").count(), 3); + await page.goBack(); + await page.waitForFunction(() => location.pathname === "/edit" && !document.querySelector("#view-edit").hidden); + await page.goBack(); + await page.waitForFunction(() => location.pathname === "/item" && !document.querySelector("#view-detail").hidden); + await page.setViewportSize({width:380, height:780}); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true); + assert.deepEqual(errors, []); + await page.goto(server.url + "/item"); + await page.waitForSelector('#items li[data-id="1"]'); + assert.equal(new URL(page.url()).pathname, "/"); + } catch (error) { + error.message += "\nBrowser: " + errors.join("\n") + "\nPage: " + await page.locator("body").innerText() + "\nServer: " + server.logs(); + throw error; + } +}); +test("two real browser tabs exchange text, empty snapshots and presence", {timeout:60000}, async t => { + const server = await serve("examples/web-collab-doc", t); + const browser = await openBrowser(t); + const first = await browser.newPage(); + const second = await browser.newPage(); + const errors = []; + for (const page of [first,second]) page.on("pageerror", error => errors.push(String(error))); + try { + await first.goto(server.url); + await first.waitForFunction(() => document.querySelector("#log")?.textContent.includes("ws open")); + await second.goto(server.url); + await second.waitForFunction(() => document.querySelector("#log")?.textContent.includes("ws open")); + await first.waitForFunction(() => document.querySelector("#presence")?.textContent.includes('"type":"presence"')); + const text = 'First <tag> "text" & 中文'; + await first.locator("#doc").fill(text); + await waitValue(second, "#doc", text); + await second.locator("#doc").fill("the next local edit after a remote update"); + await waitValue(first, "#doc", "the next local edit after a remote update"); + await second.locator("#doc").fill(""); + await waitValue(first, "#doc", ""); + await first.setViewportSize({width:380,height:780}); + const viewport = await first.evaluate(() => ({ + width: innerWidth, scroll: document.documentElement.scrollWidth, + overflowing: [...document.querySelectorAll("body *")].filter(el => el.getBoundingClientRect().right > innerWidth + 1).map(el => ({ + tag:el.tagName, id:el.id, width:el.getBoundingClientRect().width, text:el.textContent.slice(0,120) + })) + })); + assert.equal(viewport.scroll <= viewport.width, true, JSON.stringify(viewport)); + assert.deepEqual(errors, []); + } catch (error) { + error.message += "\nBrowser: " + errors.join("\n") + "\nPage: " + await first.locator("body").innerText() + "\nServer: " + server.logs(); + throw error; + } +}); + +async function nativeFileTask(functionName, args, effects, project) { + const child = spawn(root + "target/debug/marqdo", [ + "call", "lib/fs.mq.md", functionName, "--args-json", "-", "--effects", effects, + "--fs-root", project, "--require-ok", "--json" + ], {cwd: root, stdio:["pipe","pipe","pipe"]}); + let stdout="", stderr=""; + child.stdout.on("data", chunk => { stdout += chunk; }); + child.stderr.on("data", chunk => { stderr += chunk; }); + child.stdin.end(JSON.stringify(args)); + const [code] = await once(child,"exit"); + assert.equal(code,0,"native file task failed: "+stdout+" "+stderr); + const envelope=JSON.parse(stdout); + assert.equal(envelope.ok,true); + return envelope.result; +} +for (const [site, requiredCopy] of [["web-net-site", "Title is required"], ["web-net-site-zh", "标题不能为空"]]) { +test(site+" keeps native echo, current data, form retry and authenticated administration", {timeout:60000}, async t => { + const project="examples/"+site; + const owned=await nativeFileTask("temp_dir",{prefix:".browser-network"},"fs.write",project); + const filename=await nativeFileTask("resolve",{path:owned+"/site.db"},"fs.read",project); + const server=await serve(project,t,{ + args:{url:"sqlite:"+filename}, + effects:"plugin,fs.write,network.write", + cleanup:()=>nativeFileTask("remove_tree",{path:owned},"fs.write",project) + }); + const browser=await openBrowser(t); + const page=await browser.newPage(); + const errors=[]; + page.on("pageerror",error=>errors.push(String(error))); + try { + await page.goto(server.url); + await waitText(page,"#live-status","connected"); + const echoed='echo <tag> "quoted" & literal'; + await page.locator("#live-msg").fill(echoed); + await page.locator("#live-send").click(); + await waitText(page,"#live-out","echo: "+echoed+"\n"); + await page.locator("#live-msg").fill(" again "); + await page.locator("#live-msg").press("Enter"); + await waitText(page,"#live-out","echo: "+echoed+"\necho: again\n"); + await page.locator("#live-msg").fill(" "); + await page.locator("#live-msg").press("Enter"); + await page.waitForTimeout(120); + assert.equal(await page.locator("#live-out").textContent(),"echo: "+echoed+"\necho: again\n"); + assert.equal(await page.locator("#live-out tag").count(),0); + await page.goto(server.url+"/tools"); + const tools=await page.locator("body").innerText(); + assert.ok(tools.includes("http_only") && tools.includes("pic.png") && tools.includes("image/png")); + await page.goto(server.url+"/new"); + await page.locator('form[action="/_form/article"]').evaluate(form=>{form.noValidate=true;}); + await page.locator('form[action="/_form/article"] button[type="submit"]').click(); + await page.waitForFunction(copy=>document.body.textContent.includes(copy),requiredCopy); + assert.ok(await page.locator('input[name="_csrf"]').inputValue()); + const title='Browser article <strong>literal</strong>'; + await page.locator('input[name="title"]').fill(title); + await page.locator('textarea[name="body"]').fill("Actual submitted body"); + await page.locator('form[action="/_form/article"] button[type="submit"]').click(); + await page.waitForFunction(title=>document.body.textContent.includes(title),title); + assert.equal(await page.locator(".cards h2 strong").count(),0); + await page.goto(server.url+"/admin"); + await page.locator('input[name="username"]').fill("admin"); + await page.locator('input[name="password"]').fill("secret"); + await page.locator('form[action="/admin/login"] button[type="submit"]').click(); + await page.waitForFunction(()=>document.querySelector("h1")?.textContent==="Admin"); + assert.ok((await page.locator("body").innerText()).includes(title)); + await page.goto(server.url); + await waitText(page,"#live-status","connected"); + await page.setViewportSize({width:380,height:780}); + assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true); + assert.deepEqual(errors,[]); + } catch(error) { + error.message += "\nBrowser: "+errors.join("\n")+"\nPage: "+await page.locator("body").innerText()+"\nServer: "+server.logs(); + throw error; + } +}); + +} + +for (const [site, requiredCopy] of [["web-site", "Title is required"], ["web-site-zh", "标题不能为空"]]) { +test(site+" preserves the literary theme, slug detail, session navigation and gated desk", {timeout:60000}, async t => { + const project="examples/"+site; + const owned=await nativeFileTask("temp_dir",{prefix:".browser-literary"},"fs.write",project); + const filename=await nativeFileTask("resolve",{path:owned+"/site.db"},"fs.read",project); + const server=await serve(project,t,{ + args:{url:"sqlite:"+filename},effects:"plugin,fs.write,network.write", + cleanup:()=>nativeFileTask("remove_tree",{path:owned},"fs.write",project) + }); + const browser=await openBrowser(t),page=await browser.newPage(),errors=[]; + page.on("pageerror",error=>errors.push(String(error))); + // Resource declarations remain real, but this local acceptance uses font + // fallbacks and makes no claim about external font-service availability. + await page.route("https://fonts.googleapis.com/**",route=>route.abort()); + await page.route("https://fonts.gstatic.com/**",route=>route.abort()); + try { + await page.goto(server.url); + assert.equal(await page.locator(".cards article.card").count(),8); + assert.equal(await page.locator('head meta[property="og:type"]').getAttribute("content"),"website"); + assert.equal(await page.locator('head link[rel="stylesheet"][href*="fonts.googleapis.com"]').count(),1); + assert.equal(await page.locator('header.topnav a[href="/login"]').count(),1); + assert.equal(await page.locator('header.topnav a[href="/admin"]').count(),0); + const wide=await page.evaluate(()=>{ + const css=selector=>getComputedStyle(document.querySelector(selector)); + return { + ink:css("body").backgroundColor,gold:css(".topnav a").color, + display:css(".site-layout").display,columns:css(".site-layout").gridTemplateColumns, + titleFont:css(".main-intro h1").fontFamily,titleSize:parseFloat(css(".main-intro h1").fontSize), + nav:document.querySelector(".topnav").getBoundingClientRect().top, + side:document.querySelector("aside.side").getBoundingClientRect().left, + main:document.querySelector("section.main").getBoundingClientRect().left, + claims:css(".main-intro ul").display,stepPanel:css(".main-intro ol").borderLeftWidth + }; + }); + assert.equal(wide.ink,"rgb(10, 8, 9)"); + assert.equal(wide.gold,"rgb(212, 175, 55)"); + assert.equal(wide.display,"grid"); + assert.ok(wide.main>wide.side+150,JSON.stringify(wide)); + assert.ok(wide.titleFont.includes("Great Vibes") && wide.titleSize>=48,JSON.stringify(wide)); + assert.equal(wide.claims,"flex"); + assert.equal(wide.stepPanel,"2px"); + await page.locator(".cards a.card-link").first().click(); + assert.ok(new URL(page.url()).pathname.startsWith("/post/")); + assert.equal(await page.locator(".article .article-body.md").count(),1); + const created='Published <strong>literal</strong>'; + const summary="A short current summary",body="## Actual full Markdown body\n\nDistinct from summary."; + await page.goto(server.url+"/new"); + await page.locator('form[action="/_form/article"]').evaluate(form=>{form.noValidate=true;}); + await page.locator('form[action="/_form/article"] button[type="submit"]').click(); + await page.waitForFunction(copy=>document.body.textContent.includes(copy),requiredCopy); + assert.ok(await page.locator('input[name="_csrf"]').inputValue()); + await page.locator('input[name="title"]').fill(created); + await page.locator('input[name="slug"]').fill("after-startup"); + await page.locator('textarea[name="summary"]').fill(summary); + await page.locator('textarea[name="body"]').fill(body); + await page.locator('form[action="/_form/article"] button[type="submit"]').click(); + await page.waitForFunction(()=>document.querySelectorAll(".cards article.card").length===9); + assert.equal(await page.locator(".cards h2 strong").count(),0); + assert.ok((await page.locator(".cards").innerText()).includes(summary)); + assert.ok(!(await page.locator(".cards").innerText()).includes("Actual full Markdown body")); + await page.goto(server.url+"/post/after-startup?slug=other"); + assert.equal(await page.locator(".article-body h2").textContent(),"Actual full Markdown body"); + assert.ok(!(await page.locator(".article").innerText()).includes(summary)); + await page.goto(server.url+"/admin"); + assert.equal(new URL(page.url()).pathname,"/login"); + await page.locator('input[name="username"]').fill("admin"); + await page.locator('input[name="password"]').fill("demo"); + await page.locator('form[action="/login"] button[type="submit"]').click(); + await page.waitForURL(server.url+"/admin"); + assert.equal(await page.locator("aside.side").count(),0); + assert.equal(await page.locator(".is-desk").count(),1); + assert.equal(await page.locator(".cards article.card").count(),9); + assert.equal(await page.locator('form[action="/_form/article"]').count(),1); + await page.goto(server.url); + assert.equal(await page.locator('header.topnav a[href="/login"]').count(),0); + assert.equal(await page.locator('header.topnav a[href="/admin"]').count(),1); + await page.setViewportSize({width:380,height:780}); + const narrow=await page.evaluate(()=>({ + width:innerWidth,scroll:document.documentElement.scrollWidth, + side:document.querySelector("aside.side").getBoundingClientRect().top, + main:document.querySelector("section.main").getBoundingClientRect().top, + columns:getComputedStyle(document.querySelector(".site-layout")).gridTemplateColumns + })); + assert.ok(narrow.scroll<=narrow.width && narrow.side>narrow.main,JSON.stringify(narrow)); + await page.goto(server.url+"/admin/logout"); + assert.equal(await page.locator('header.topnav a[href="/login"]').count(),1); + await page.goto(server.url+"/admin"); + assert.equal(new URL(page.url()).pathname,"/login"); + assert.deepEqual(errors,[]); + } catch(error) { + error.message+="\nBrowser: "+errors.join("\n")+"\nPage: "+await page.locator("body").innerText()+"\nServer: "+server.logs(); + throw error; + } +}); +} + +test("browser effects preserve literal duplicate rows, history, storage and local transports", {timeout:60000}, async t => { + const server = await serve("examples/browser-app", t, {effects:"plugin,fs.write,network.write"}); + const browser = await openBrowser(t); + const context = await browser.newContext({permissions:["clipboard-read", "clipboard-write"],acceptDownloads:true}); + const page = await context.newPage(); + const errors = []; + page.on("pageerror", error => errors.push(String(error))); + let requests = 0; + await page.route("https://httpbin.org/uuid", route => { + requests++; + return route.fulfill({status:requests === 1 ? 200 : 503,body:requests === 1 ? "controlled-success" : "controlled-failure",headers:{"access-control-allow-origin":"*"}}); + }); + try { + await page.goto(server.url); + await page.waitForFunction(() => !document.querySelector("#draft")?.disabled); + const literal = 'A <tag> "quoted" & literal'; + for (let i=0;i<2;i++) { + await page.locator("#draft").fill(literal); + await page.locator("#add").click(); + await page.waitForFunction(n => document.querySelectorAll("#items li").length === n, i+1); + } + assert.deepEqual(await page.locator("#items li span").allTextContents(), [literal,literal]); + assert.equal(await page.locator("#items tag, #items script").count(), 0); + await page.locator('#items button[data-id="1"]').click(); + assert.equal(await page.locator("#items li").count(), 1); + assert.equal(await page.locator("#items li span").textContent(), literal); + await page.locator("#draft").fill("third"); + await page.locator("#add").click(); + await page.waitForSelector('#items button[data-id="3"]'); + assert.equal(await page.locator("#items li").count(), 2); + await page.locator("#copy-log").click(); + await page.waitForFunction(expected => navigator.clipboard.readText().then(actual=>actual===expected), literal+"\nthird"); + const downloadEvent = page.waitForEvent("download"); + await page.locator("#dl-list").click(); + const download = await downloadEvent; + assert.equal(download.suggestedFilename(),"items.txt"); + const stream = await download.createReadStream(); + const chunks = []; + for await (const chunk of stream) chunks.push(chunk); + assert.equal(Buffer.concat(chunks).toString(),literal+"\nthird"); + await page.locator("#start-tick").click(); + await waitText(page,"#tick","1"); + await page.locator("#stop-tick").click(); + await page.waitForTimeout(1200); + await waitText(page,"#tick","1"); + await page.locator("#draft").fill('saved <draft> "text"'); + await page.locator("#save").click(); + await waitText(page,"#log","draft saved"); + assert.equal(await page.evaluate(()=>localStorage.getItem("mq-draft")),'saved <draft> "text"'); + await page.locator("#draft").fill("changed"); + await page.locator("#load").click(); + await waitValue(page,"#draft",'saved <draft> "text"'); + const initialHistory = await page.evaluate(()=>history.length); + await page.locator("#nav-about").click(); + await page.waitForFunction(()=>location.pathname==="/about" && !document.querySelector("#panel-about").hidden); + await page.locator("#nav-net").click(); + await page.waitForFunction(()=>location.pathname==="/net" && !document.querySelector("#panel-net").hidden); + assert.equal(await page.evaluate(()=>history.length),initialHistory+2); + await page.goBack(); + await page.waitForFunction(()=>location.pathname==="/about" && !document.querySelector("#panel-about").hidden); + await page.goBack(); + await page.waitForFunction(()=>location.pathname==="/" && !document.querySelector("#panel-home").hidden); + await page.goForward(); + await page.goForward(); + await page.waitForFunction(()=>location.pathname==="/net" && !document.querySelector("#panel-net").hidden); + assert.equal(await page.evaluate(()=>history.length),initialHistory+2); + await page.locator("#fetch-all").click(); + await page.waitForFunction(()=> { + const text=document.querySelector("#net-out").textContent; + return text.includes("controlled-success") && text.includes("503") && text.includes("controlled-failure"); + }); + await page.locator("#ws-open").click(); + await waitText(page,"#net-out","ws open"); + const message='local <echo> "message"'; + await page.locator("#ws-msg").fill(message); + await page.locator("#ws-send").click(); + await waitText(page,"#net-out","ws ← "+message); + await page.locator("#ws-close").click(); + await waitText(page,"#net-out","ws closed"); + const styles = await page.evaluate(()=>({body:getComputedStyle(document.body).color,button:getComputedStyle(document.querySelector("#fetch-all")).backgroundColor})); + assert.equal(styles.body,"rgb(26, 31, 28)"); + assert.equal(styles.button,"rgb(47, 111, 78)"); + await page.setViewportSize({width:380,height:780}); + assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true); + await page.goto(server.url+"/about"); + await page.waitForFunction(()=>!document.querySelector("#draft")?.disabled); + assert.equal(new URL(page.url()).pathname,"/"); + await waitValue(page,"#draft",'saved <draft> "text"'); + assert.equal(await page.locator("#items li").count(),0); + assert.deepEqual(errors,[]); + } catch(error) { + error.message+="\nBrowser: "+errors.join("\n")+"\nPage: "+await page.locator("body").innerText()+"\nServer: "+server.logs(); + throw error; + } +}); diff --git a/tests/document_data.rs b/tests/document_data.rs new file mode 100644 index 0000000..368cd4f --- /dev/null +++ b/tests/document_data.rs @@ -0,0 +1,71 @@ +//! Native document data and filesystem addresses must compose under an explicit root. +use marqdo::{Backend, call::{call_file_with, parse_call_args_json, CallEffects, CallOptions}, value::Value}; +use std::{fs, path::PathBuf, sync::atomic::{AtomicU64, Ordering}}; +static SEQUENCE:AtomicU64=AtomicU64::new(0); +struct Scratch(PathBuf); +impl Scratch { + fn new()->Self { + let root=std::env::temp_dir().join(format!("mq-document-data-{}-{}",std::process::id(),SEQUENCE.fetch_add(1,Ordering::Relaxed))); + fs::create_dir_all(&root).unwrap();Self(root.canonicalize().unwrap()) + } +} +impl Drop for Scratch {fn drop(&mut self){let _=fs::remove_dir_all(&self.0);}} +fn root()->PathBuf {PathBuf::from(env!("CARGO_MANIFEST_DIR"))} +fn invoke(file:&str,function:&str,args:serde_json::Value,backend:Backend,work:&Scratch)->anyhow::Result<Value>{ + call_file_with(&root().join(file),function,&parse_call_args_json(&args.to_string()).unwrap(),backend, + CallOptions{effects:CallEffects::parse("fs.read").unwrap(),fs_root:Some(work.0.clone()),..Default::default()}) +} +fn field<'a>(value:&'a Value,key:&str)->&'a Value { + let Value::Map(fields)=value else {panic!("expected record: {value:?}")}; + &fields.iter().find(|(name,_)|name==key).unwrap().1 +} +#[test] +fn markdown_data_reading_is_inert_and_preserves_native_values_on_both_backends(){ + let work=Scratch::new(); + fs::write(work.0.join("marker"),"keep").unwrap(); + let backtick=char::from(96); + let source=format!("---\nmarkup: occlusion\nimport:\n fs: lib/fs.mq.md\n---\n# main\n\n**[Remove the marker](fs.remove(path=\"marker\"))**\n\n{b}{b}{b}node\nthrow new Error(\"must not run\");\n{b}{b}{b}\n\n## 数据\n\n| @ | id | enabled | count | body | empty |\n|---|---|---|---|---|---|\n| 1 | \"a\" | False | -3 | \"*literal*\" | None |\n",b=backtick); + fs::write(work.0.join("data.md"),source).unwrap(); + for backend in [Backend::Tree,Backend::Bytecode] { + for (file,function,args) in [ + ("lib/document.mq.md","read_table",serde_json::json!({"path":"data.md","title":"数据"})), + ("lib/文档.mq.md","读取表值",serde_json::json!({"路径":"data.md","标题":"数据"})), + ] { + let actual=invoke(file,function,args,backend,&work).unwrap(); + let Value::List(rows)=actual else {panic!("expected record rows")}; + assert_eq!(rows.len(),1); + assert_eq!(field(&rows[0],"enabled"),&Value::Bool(false)); + assert_eq!(field(&rows[0],"count"),&Value::Int(-3)); + assert_eq!(field(&rows[0],"body"),&Value::Text("*literal*".into())); + assert_eq!(field(&rows[0],"empty"),&Value::None); + assert_eq!(fs::read_to_string(work.0.join("marker")).unwrap(),"keep"); + } + } +} +#[test] +fn filesystem_resolution_uses_the_granted_root_and_creates_nothing(){ + let work=Scratch::new(); + for backend in [Backend::Tree,Backend::Bytecode] { + for (file,function,args) in [ + ("lib/fs.mq.md","resolve",serde_json::json!({"path":"unused/../db/new.sqlite"})), + ("lib/文件.mq.md","解析路径",serde_json::json!({"路径":"unused/../db/new.sqlite"})), + ] { + let actual=invoke(file,function,args,backend,&work).unwrap(); + assert_eq!(actual,Value::Text(work.0.join("db/new.sqlite").to_str().unwrap().into())); + assert!(!work.0.join("db").exists()); + } + let outside=work.0.parent().unwrap().join("mq-not-authorized.sqlite"); + let error=invoke("lib/fs.mq.md","resolve",serde_json::json!({"path":outside}),backend,&work).unwrap_err(); + assert!(error.to_string().contains("escapes sandbox root"),"{error:#}"); + } +} +#[cfg(unix)] +#[test] +fn filesystem_resolution_rejects_links_outside_the_root(){ + let work=Scratch::new(); + std::os::unix::fs::symlink(work.0.parent().unwrap(),work.0.join("escape")).unwrap(); + for backend in [Backend::Tree,Backend::Bytecode] { + let error=invoke("lib/fs.mq.md","resolve",serde_json::json!({"path":"escape/new.sqlite"}),backend,&work).unwrap_err(); + assert!(error.to_string().contains("escapes sandbox root"),"{error:#}"); + } +} diff --git a/tests/example_databases.rs b/tests/example_databases.rs new file mode 100644 index 0000000..7b0caf4 --- /dev/null +++ b/tests/example_databases.rs @@ -0,0 +1,66 @@ +//! Execute the documented SQLite initializer against disposable site roots. +use serde_json::{json, Value}; +use std::{ + fs, + io::Write, + path::PathBuf, + process::{Command, Stdio}, +}; + +fn root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) +} + +struct Scratch(PathBuf); +impl Drop for Scratch { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +#[test] +fn article_initializers_use_real_resources_and_preserve_user_rows_on_both_backends() { + for (site, module, table, function, expected, has_slug) in [ + ("web-site", "index", "articles", "open", 8, true), + ("web-site-zh", "index", "articles", "open", 8, true), + ("web-net-site", "index", "articles", "open", 3, false), + ("web-net-site-zh", "index", "articles", "打开", 3, false), + ("marqdo-blog", "posts", "posts", "open", 2, true), + ] { + for backend in ["tree", "bytecode"] { + let work = Scratch(std::env::temp_dir().join(format!( + "mq-article-init-{}-{site}-{backend}", std::process::id() + ))); + fs::create_dir_all(work.0.join("db")).unwrap(); + let leaf=if site=="marqdo-blog" {"db/posts.tables.md"} else {"db/articles.tables.md"}; + fs::copy(root().join("examples").join(site).join(leaf),work.0.join(leaf)).unwrap(); + let driver = work.0.join("verify.mq.md"); + fs::write(&driver, format!( + "---\nmarkup: occlusion\nimport:\n site: {}/examples/{site}/db/{module}.mq.md\n---\n\n## main\n\nUse `url` for the owned database and `rows` for a business write.\n\nWe **store = site.{function}(url=`url`)** and **before = [Observe seeds](> `store`.count table=\"{table}\")**.\nWe **[Insert a user article](> `store`.insert table=\"{table}\" rows=`rows`)** and **again = site.{function}(url=`url`)** and **after = [Observe preserved writes](> `again`.count table=\"{table}\")**.\n\n`counts` =\n\n| before | after |\n|---|---|\n| `before` | `after` |\n\nReturn *counts*.\n", + root().display() + )).unwrap(); + let library = if cfg!(target_os = "macos") {"libweb.dylib"} else if cfg!(windows) {"web.dll"} else {"libweb.so"}; + let mut child = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .current_dir(root()) + .env("MARQDO_LIB", root().join("lib")) + .env("MARQDO_EXT", root().join("ext")) + .env("MARQDO_WEB_PLUGIN", root().join("plugins/web/build").join(library)) + .env("MARQDO_CALL_SESSION_DIR", work.0.join("sessions")) + .args(["call", driver.to_str().unwrap(), "main", "--backend", backend, + "--args-json", "-", "--effects", "plugin,fs.write", "--fs-root", + work.0.to_str().unwrap(), "--json"]) + .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()) + .spawn().unwrap(); + let mut row = if site=="marqdo-blog" {json!({"title":"Retained user article","content":"User text"})} else {json!({"title":"Retained user article","body":"User text"})}; + if has_slug { row["slug"] = json!("retained-user"); } + let args = json!({"url":format!("sqlite:{}", work.0.join("site.db").display()),"rows":row}); + child.stdin.take().unwrap().write_all(args.to_string().as_bytes()).unwrap(); + let out=child.wait_with_output().unwrap(); + assert!(out.status.success(), "{site} [{backend}] {}\n{}", + String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); + let envelope:Value=serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(envelope["result"]["before"],expected,"{envelope}"); + assert_eq!(envelope["result"]["after"],expected+1,"{envelope}"); + } + } +} diff --git a/tests/executable_knowledge.rs b/tests/executable_knowledge.rs index e12c2fb..176575a 100644 --- a/tests/executable_knowledge.rs +++ b/tests/executable_knowledge.rs @@ -1429,44 +1429,15 @@ fn m05_skill_front_has_occlusion_core_not_classic_index() { "{rel} still teaches the inverted marker polarity" ); } - let skill = std::fs::read_to_string(root.join("skills/marqdo/SKILL.md")).unwrap(); - let golden = fence_after(&skill, "## Call one function"); - let dir = std::env::temp_dir().join(format!("mq-skill-call-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let file = dir.join("calculator.mq.md"); - std::fs::write(&file, golden).unwrap(); - let out = std::process::Command::new(env!("CARGO_BIN_EXE_marqdo")) - .args([ - "call", - file.to_str().unwrap(), - "计算器.加法", - "a=2", - "b=3", - ]) - .output() - .unwrap(); - assert_eq!( - out.status.code(), - Some(0), - "skill golden failed\nstderr={}\nstdout={}\nsource=\n{golden}", - String::from_utf8_lossy(&out.stderr), - String::from_utf8_lossy(&out.stdout) - ); - assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "5"); -} -fn fence_after<'a>(body: &'a str, heading: &str) -> &'a str { - let rest = body - .split_once(heading) - .unwrap_or_else(|| panic!("missing {heading}")) - .1; - let start = rest - .find("```markdown\n") - .unwrap_or_else(|| panic!("{heading} has no markdown fence")); - let rest = &rest[start + "```markdown\n".len()..]; - let end = rest.find("\n```").expect("fence end"); - rest[..end].trim() + // Exercise the authoritative executable handbook rather than a copied + // Markdown fence that could drift from the skill's actual task entry. + let file = root.join("doc/library-development.mq.md"); + let out = std::process::Command::new(env!("CARGO_BIN_EXE_marqdo")) + .args(["call",file.to_str().unwrap(),"计算金额","单价=2","数量=3"]) + .output().unwrap(); + assert_eq!(out.status.code(),Some(0),"handbook call failed: {}",String::from_utf8_lossy(&out.stderr)); + assert_eq!(String::from_utf8_lossy(&out.stdout).trim(),"6"); } #[test] diff --git a/tests/native_foreign_handbook.rs b/tests/native_foreign_handbook.rs new file mode 100644 index 0000000..15bd546 --- /dev/null +++ b/tests/native_foreign_handbook.rs @@ -0,0 +1,101 @@ +//! Native analysis and real persistent view cells must agree on observable values. +use marqdo::{Backend,call::{CallEffects,CallOptions,call_file_with,parse_call_args_json},value::Value}; +use std::path::PathBuf; +fn root()->PathBuf {PathBuf::from(env!("CARGO_MANIFEST_DIR"))} +fn field<'a>(value:&'a Value,key:&str)->&'a Value { + let Value::Map(fields)=value else {panic!("expected map: {value:?}")}; + &fields.iter().find(|(k,_)|k==key).unwrap_or_else(||panic!("missing {key}: {value:?}")).1 +} +fn list(value:&Value)->&[Value] {let Value::List(values)=value else {panic!("expected list: {value:?}")};values} +fn number(value:&Value)->f64 { + match value {Value::Int(n)=>*n as f64,Value::Num(n)=>*n,_=>panic!("expected number: {value:?}")} +} +fn analyze(data:&str,backend:Backend)->Value { + call_file_with(&root().join("examples/foreign-native-report/index.mq.md"),"analyze_orders", + &parse_call_args_json(data).unwrap(),backend,CallOptions::default()).unwrap() +} +#[test] +fn native_grouping_handles_nonintegral_means_equal_groups_and_empty_input() { + for backend in [Backend::Tree,Backend::Bytecode] { + let report=analyze(r#"{"orders":[{"region":"b","amount":3},{"region":"a","amount":2},{"region":"a","amount":2}]}"#,backend); + assert_eq!(number(field(&report,"total")),7.); + assert_eq!(number(field(&report,"count")),3.); + assert!((number(field(&report,"average"))-7./3.).abs()<1e-12); + let rows=list(field(&report,"regions")); + assert_eq!(rows.len(),2); + assert_eq!(field(&rows[0],"region"),&Value::Text("a".into())); + for row in rows {assert_eq!(number(field(row,"z_span")),0.);} + let empty=analyze(r#"{"orders":[]}"#,backend); + assert!(list(field(&empty,"regions")).is_empty()); + assert_eq!(number(field(&empty,"total")),0.); + assert_eq!(number(field(&empty,"average")),0.); + } +} +#[test] +fn public_views_run_three_actual_cells_with_shared_and_isolated_formatters() { + if !std::process::Command::new("node").arg("--version").output().is_ok_and(|o|o.status.success()) { + eprintln!("Node Intl unavailable; native report remains covered independently");return; + } + for file in ["public/features/19-foreign-view-cells.mq.md","public/features/19-外联视图单元.mq.md"] { + let path=root().join(file); + let result=call_file_with(&path,"main",&[],Backend::Tree,CallOptions{ + effects:CallEffects::parse("process.exec").unwrap(),fs_root:Some(root()),..Default::default() + }).unwrap(); + let report=field(&result,"report"); + assert_eq!(number(field(report,"total")),950.); + assert!((number(field(report,"average"))-950./6.).abs()<1e-12); + let formatted=field(&result,"formatting"); + assert!(field(formatted,"total").as_display().contains("950.00")); + assert!(field(formatted,"average").as_display().contains("158.33")); + let mut session=marqdo::host::foreign_doc::DocumentSession::open(&path,&root()).unwrap(); + let actual=session.run_all(false).unwrap(); + assert_eq!(field(&actual,"ok"),&Value::Bool(true),"{file}: {actual:?}"); + assert_eq!(number(field(&actual,"ran")),3.); + assert_eq!(number(field(&actual,"failed")),0.); + let records=list(field(&actual,"records")); + assert_eq!(records.len(),3); + for record in records {assert_eq!(field(record,"ok"),&Value::Bool(true),"{record:?}");} + assert!(field(&records[1],"stdout").as_display().contains("158.33")); + assert!(field(&records[2],"stdout").as_display().contains("950.00")); + drop(session); + } +} + +#[test] +fn showcase_uses_native_reports_and_keeps_one_shot_and_persistent_formats_equivalent() { + if !std::process::Command::new("node").arg("--version").output().is_ok_and(|o|o.status.success()) { + eprintln!("Node unavailable; native report cases are independent");return; + } + for backend in [Backend::Tree,Backend::Bytecode] { + let observed=call_file_with(&root().join("examples/oa2026-showcase/foreign-node.mq.md"),"main",&[],backend, + CallOptions{effects:CallEffects::parse("process.exec").unwrap(),fs_root:Some(root()),..Default::default()}).unwrap(); + assert_eq!(field(&observed,"ok"),&Value::Bool(true),"{observed:?}"); + let values=field(&observed,"value"); + assert_eq!(number(field(field(values,"before"),"total")),870.); + assert_eq!(number(field(field(values,"after"),"total")),950.); + let ranked=list(field(values,"updated_ranking")); + for (row,total) in ranked.iter().zip([420.,300.,230.]) {assert_eq!(number(field(row,"total")),total);} + let once=field(values,"one_shot");let initial=field(values,"persistent_initial"); + for key in ["total","average"] {assert_eq!(field(once,key),field(initial,key));} + assert!(field(field(values,"persistent_updated"),"average").as_display().contains("158.33")); + } +} + +#[test] +fn public_foreign_guides_execute_batches_and_persistent_state_in_both_languages() { + if !std::process::Command::new("node").arg("--version").output().is_ok_and(|o|o.status.success()) { + eprintln!("Node unavailable; native report cases remain independent");return; + } + for backend in [Backend::Tree,Backend::Bytecode] { + for file in ["public/stdlib/foreign.mq.md","public/stdlib/外联.mq.md"] { + let captured=marqdo::run_file_capture(&root().join(file),&marqdo::RunOptions{backend,fs_root:Some(root()),..Default::default()}).unwrap(); + assert!(captured.stdout.contains("4.00"),"{file}: {}",captured.stdout); + assert!(captured.stdout.contains("21.00") && captured.stdout.contains("0.08"),"{file}: {}",captured.stdout); + assert!(!captured.stdout.contains("NaN"),"{file}: {}",captured.stdout); + } + for file in ["public/00-welcome.mq.md","public/00-欢迎.mq.md"] { + let captured=marqdo::run_file_capture(&root().join(file),&marqdo::RunOptions{backend,fs_root:Some(root()),..Default::default()}).unwrap(); + assert!(captured.stdout.contains("950.00"),"{file}: {}",captured.stdout); + } + } +} diff --git a/tests/release_handbook.rs b/tests/release_handbook.rs new file mode 100644 index 0000000..1264787 --- /dev/null +++ b/tests/release_handbook.rs @@ -0,0 +1,356 @@ +//! Isolated publication ordering and package-role checks through the real handbooks. +use std::{fs,io::{Read,Write},net::{TcpListener,TcpStream},path::PathBuf,process::{Command,Stdio}, + sync::{Arc,atomic::{AtomicBool,Ordering}},thread,time::{Duration,Instant}}; +use serde_json::{json,Value}; +fn root()->PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) } +fn native()->Command { let mut cmd=Command::new(env!("CARGO_BIN_EXE_marqdo"));cmd.current_dir(root());cmd } +fn invoke(file:&str,function:&str,args:Value,effects:&str,work:&std::path::Path,env:&[(String,String)])->Value { + let mut cmd=native(); + cmd.args(["call",file,function,"--args-json","-","--effects",effects,"--fs-root",work.to_str().unwrap(),"--json"]); + for (k,v) in env {cmd.env(k,v);} + let mut child=cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); + child.stdin.take().unwrap().write_all(args.to_string().as_bytes()).unwrap(); + let out=child.wait_with_output().unwrap(); + assert!(out.status.success(),"{}",String::from_utf8_lossy(&out.stdout)); + let answer:Value=serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(answer["ok"],true,"{answer}");answer["result"].clone() +} +fn engineering()->PathBuf { + let name=if cfg!(target_os="windows"){"engineering.dll"}else if cfg!(target_os="macos"){"libengineering.dylib"}else{"libengineering.so"}; + let lib=root().join("target/debug").join(name); + if !lib.is_file() { + let result=invoke("lib/sys.mq.md","exec",json!({"cmd":"cargo","args":["build","-p","marqdo_plugin_engineering","--offline"],"capture":true}),"process.exec",&root(),&[]); + assert_eq!(result["code"],0,"{result}"); + } + assert!(lib.is_file());lib +} +#[derive(Debug)] +struct Request { path:String, body:Vec<u8>, headers:String } +fn request(mut stream:TcpStream)->Request { + stream.set_read_timeout(Some(Duration::from_secs(3))).unwrap(); + let mut data=Vec::new();let mut chunk=[0u8;4096]; + let header_end=loop { + let n=stream.read(&mut chunk).unwrap();assert!(n>0);data.extend_from_slice(&chunk[..n]); + assert!(data.len()<65536); + if let Some(i)=data.windows(4).position(|v|v==b"\r\n\r\n"){break i+4;} + }; + let headers=String::from_utf8(data[..header_end].to_vec()).unwrap(); + let length=headers.lines().find_map(|line|line.split_once(':').filter(|(k,_)|k.eq_ignore_ascii_case("content-length")) + .map(|(_,v)|v.trim().parse::<usize>().unwrap())).unwrap_or(0); + while data.len()<header_end+length { + let n=stream.read(&mut chunk).unwrap();assert!(n>0);data.extend_from_slice(&chunk[..n]); + } + let path=headers.lines().next().unwrap().split_whitespace().nth(1).unwrap().to_string(); + Request{path,body:data[header_end..header_end+length].to_vec(),headers} +} +fn upload(fail_at:Option<usize>)->(Value,Vec<Request>) { + let work=std::env::temp_dir().join(format!("mq-r2-order-{}-{}",std::process::id(),fail_at.unwrap_or(0))); + fs::create_dir_all(&work).unwrap(); + let lib=engineering(); + let listener=TcpListener::bind("127.0.0.1:0").unwrap();listener.set_nonblocking(true).unwrap(); + let address=listener.local_addr().unwrap(); + let done=Arc::new(AtomicBool::new(false));let server_done=done.clone(); + let server=thread::spawn(move||{ + let started=Instant::now();let mut events=Vec::new(); + while started.elapsed()<Duration::from_secs(30) { + match listener.accept() { + Ok((mut stream,_))=>{ + let event=request(stream.try_clone().unwrap()); + events.push(event); + let status=if fail_at==Some(events.len()){"503 Service Unavailable"}else{"200 OK"}; + stream.write_all(format!("HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").as_bytes()).unwrap(); + }, + Err(e) if e.kind()==std::io::ErrorKind::WouldBlock=>{ + if server_done.load(Ordering::SeqCst){break;} + thread::sleep(Duration::from_millis(5)); + }, + Err(e)=>panic!("{e}"), + } + } + events + }); + let names=["marqdo-9.8.7-ext.zip","marqdo-9.8.7-native-x86_64-pc-windows-msvc.zip","marqdo-9.8.7-native-x86_64-unknown-linux-gnu.zip"]; + let mut files=Vec::new(); + for name in names { + fs::write(work.join(name),b"isolated transport fixture\n").unwrap(); + let digest=invoke("lib/fs.mq.md","file_hash",json!({"path":name}),"fs.read",&work,&[]); + files.push(json!({"name":name,"path":name,"sha256":digest})); + } + let env=vec![ + ("MARQDO_ENGINEERING_PLUGIN".into(),lib.display().to_string()), + ("MARQDO_RELEASE_CREDENTIAL_HOME".into(),work.display().to_string()), + ("R2_ENDPOINT".into(),format!("http://{address}")), + ("R2_BUCKET".into(),"fixture".into()), + ("R2_REGION".into(),"auto".into()), + ("R2_ACCESS_KEY_ID".into(),"fixture-key".into()), + ("R2_SECRET_ACCESS_KEY".into(),"fixture-secret-never-real".into()), + ]; + let result=invoke("skills/marqdo-release/asset_io.mq.md","upload",json!({"version":"9.8.7","files":files}),"plugin",&work,&env); + done.store(true,Ordering::SeqCst); + let events=server.join().unwrap(); + assert!(!result.to_string().contains("fixture-secret")); + fs::remove_dir_all(work).unwrap(); + (result,events) +} +#[test] +fn all_six_packs_are_written_before_either_version_pointer() { + let (result,events)=upload(None);assert_eq!(result["ok"],true,"{result}"); + assert_eq!(events.len(),8,"{events:?}"); + for request in &events[..6] { + assert!(request.path.ends_with(".zip"));assert_eq!(request.body,b"isolated transport fixture\n"); + assert!(request.headers.contains("AWS4-HMAC-SHA256")); + assert!(!request.headers.contains("fixture-secret")); + } + assert_eq!(events[6].path,"/fixture/v9.8.7/VERSION"); + assert_eq!(events[7].path,"/fixture/latest/VERSION"); + assert_eq!(events[6].body,b"9.8.7\n");assert_eq!(events[7].body,b"9.8.7\n"); +} +#[test] +fn failed_pack_upload_stops_before_publication_pointers() { + let (result,events)=upload(Some(4));assert_eq!(result["ok"],false,"{result}"); + assert_eq!(events.len(),4,"{events:?}"); + assert!(events.iter().all(|r|!r.path.ends_with("/VERSION"))); +} +#[test] +fn source_role_checks_package_version_and_declared_native_capability() { + let bad=invoke("skills/marqdo-release/assets.mq.md","content",json!({ + "version":"9.8.7","record":{"name":"marqdo-9.8.7-source.zip","entries":["Cargo.toml"], + "metadata":{"Cargo.toml":"[package]\nname=\"fixture\"\nversion = \"1.0.0\"\n[dependencies.fake]\nversion = \"9.8.7\"\n"}} + }),"none",&root(),&[]); + assert_eq!(bad["ok"],false);assert_eq!(bad["error"]["code"],"release.source_version"); + let bad=invoke("skills/marqdo-release/assets.mq.md","matrix",json!({"records":[ + {"name":"marqdo-9.8.7-ext.zip","entries":["ext/engineering/index.mq.md"]}, + {"name":"marqdo-9.8.7-native-x86_64-pc-windows-msvc.zip","entries":[]}, + {"name":"marqdo-9.8.7-native-x86_64-unknown-linux-gnu.zip","entries":["native/libengineering.so"]} + ]}),"none",&root(),&[]); + assert_eq!(bad["ok"],false);assert_eq!(bad["error"]["code"],"release.native_capability"); +} + +#[test] +fn source_audit_keeps_failed_evidence_and_does_not_execute_documents() { + let work=std::env::temp_dir().join(format!("mq-handbook-audit-{}",std::process::id())); + fs::create_dir_all(&work).unwrap(); + fs::write(work.join("content.mq.md"),"# Read this page\n\nThis heading contains explanatory prose only.\n").unwrap(); + fs::write(work.join("uncontracted.mq.md"),"---\nmarkup: occlusion\n---\n\n## task\n\nAfter choosing this fixed result we return *42*.\n").unwrap(); + fs::write(work.join("broken.mq.md"),"---\nmarkup: occlusion\n---\n\n## task\n\nWe **x = [Broken expression](1 +)**.\n").unwrap(); + let env=vec![("MARQDO_ENGINEERING_PLUGIN".into(),engineering().display().to_string())]; + let report=invoke("skills/marqdo-dev/files.mq.md","audit",json!({"paths":["content.mq.md","uncontracted.mq.md","broken.mq.md"]}),"plugin,fs.read",&work,&env); + assert_eq!(report["ok"],false,"{report}"); + assert_eq!(report["error"]["code"],"authoring.incomplete"); + let records=report["value"]["reports"].as_array().unwrap(); + assert_eq!(records.len(),3); + assert_eq!(records[0]["ok"],true,"{records:?}"); + assert_eq!(records[1]["missing_contracts"][0]["name"],"task"); + assert_eq!(records[2]["ok"],false); + assert!(!records[2]["diagnostics"].as_array().unwrap().is_empty()); + fs::remove_dir_all(work).unwrap(); +} + +#[test] +fn release_commit_preflight_preserves_wrong_branch_directory_and_unrelated_index() { + let work=std::env::temp_dir().join(format!("mq-commit-scope-{}",std::process::id())); + fs::create_dir_all(work.join("nested")).unwrap(); + let git=|args:&[&str]|{ + let out=Command::new("git").current_dir(&work).args(args).output().unwrap(); + assert!(out.status.success(),"{}",String::from_utf8_lossy(&out.stderr));out.stdout + }; + git(&["init","-b","main"]); + git(&["config","user.name","Isolated handbook fixture"]); + git(&["config","user.email","fixture@example.invalid"]); + git(&["config","commit.gpgSign","false"]); + fs::write(work.join("base.txt"),"base\n").unwrap(); + git(&["add","base.txt"]);git(&["commit","-m","prepare fixture"]); + fs::write(work.join("reviewed.txt"),"reviewed\n").unwrap(); + fs::write(work.join("other.txt"),"unrelated\n").unwrap(); + fs::write(work.join("nested/leaf.txt"),"leaf\n").unwrap(); + let env=vec![("MARQDO_ENGINEERING_PLUGIN".into(),engineering().display().to_string())]; + let args=|paths:Vec<&str>|json!({"paths":paths,"message":"must remain a preflight"}); + git(&["checkout","-b","topic"]); + let result=invoke("skills/marqdo-release/local.mq.md","commit",args(vec!["reviewed.txt"]),"plugin,fs.read",&work,&env); + assert_eq!(result["error"]["code"],"release.commit_branch","{result}"); + assert!(git(&["diff","--cached","--name-only"]).is_empty()); + git(&["checkout","main"]); + let result=invoke("skills/marqdo-release/local.mq.md","commit",args(vec!["nested"]),"plugin,fs.read",&work,&env); + assert_eq!(result["error"]["code"],"release.commit_paths","{result}"); + assert!(git(&["diff","--cached","--name-only"]).is_empty()); + git(&["add","other.txt"]);let index=git(&["diff","--cached","--name-only"]); + let result=invoke("skills/marqdo-release/local.mq.md","commit",args(vec!["reviewed.txt"]),"plugin,fs.read",&work,&env); + assert_eq!(result["error"]["code"],"release.staged_unrelated","{result}"); + assert_eq!(git(&["diff","--cached","--name-only"]),index); + assert_eq!(String::from_utf8(git(&["log","-1","--format=%s"])).unwrap().trim(),"prepare fixture"); + git(&["restore","--staged","other.txt"]); + fs::remove_file(work.join("base.txt")).unwrap(); + git(&["add","--","base.txt"]); + let committed=invoke("skills/marqdo-release/local.mq.md","commit", + json!({"paths":["base.txt","reviewed.txt"],"message":"retry preserves staged removal"}), + "plugin,fs.read",&work,&env); + assert_eq!(committed["ok"],true,"{committed}"); + assert_eq!(String::from_utf8(git(&["log","-1","--format=%s"])).unwrap().trim(),"retry preserves staged removal"); + assert!(git(&["ls-files","base.txt"]).is_empty()); + assert_eq!(String::from_utf8(git(&["ls-files","reviewed.txt"])).unwrap().trim(),"reviewed.txt"); + assert!(!git(&["status","--porcelain","other.txt"]).is_empty()); + fs::remove_dir_all(work).unwrap(); +} + +#[test] +fn packaging_metadata_and_vendor_preparation_use_the_native_handbook() { + let work=std::env::temp_dir().join(format!("mq-package-native-{}",std::process::id())); + fs::create_dir_all(work.join("debian")).unwrap(); + fs::create_dir_all(work.join("vendor/fixture/src")).unwrap(); + fs::write(work.join("Cargo.toml"),"[package]\nname=\"fixture\"\nversion=\"9.8.7\"\n[dependencies.other]\nversion=\"1.0.0\"\n").unwrap(); + fs::write(work.join("debian/changelog"),"marqdo (8.0.0-2ppa4~jammy) jammy; urgency=medium\n\nKeep the reviewed history.\n").unwrap(); + let package="skills/marqdo-release/package.mq.md"; + assert_eq!(invoke(package,"upstream",json!({}),"fs.read",&work,&[]),"9.8.7"); + assert_eq!(invoke(package,"debian_version",json!({"series":"noble"}),"fs.read",&work,&[]),"9.8.7-2ppa4~noble"); + let invalid=invoke(package,"debian_version",json!({"series":"noble;invalid"}),"fs.read",&work,&[]); + assert_eq!(invalid["ok"],false); + assert_eq!(invoke(package,"vendor_config",json!({}),"fs.write",&work,&[])["ok"],true); + assert_eq!(fs::read_to_string(work.join(".cargo/config.toml")).unwrap(),"[source.crates-io]\nreplace-with = \"vendored-sources\"\n\n[source.vendored-sources]\ndirectory = \"vendor\"\n"); + fs::write(work.join("vendor/fixture/Cargo.toml.orig"),"generated backup").unwrap(); + fs::write(work.join("vendor/fixture/src/lib.rs"),"retained source").unwrap(); + fs::write(work.join("vendor/fixture/.cargo-checksum.json"),json!({"package":"retained-package-hash","files":{"Cargo.toml.orig":"backup-hash","src/lib.rs":"retained-file-hash"}}).to_string()).unwrap(); + let cleaned=invoke(package,"sanitize_vendor",json!({}),"fs.write",&work,&[]); + assert_eq!(cleaned["ok"],true,"{cleaned}"); + assert_eq!(cleaned["value"]["removed"],1);assert_eq!(cleaned["value"]["changed"],1); + let checksum:Value=serde_json::from_slice(&fs::read(work.join("vendor/fixture/.cargo-checksum.json")).unwrap()).unwrap(); + assert_eq!(checksum["package"],"retained-package-hash"); + assert_eq!(checksum["files"]["src/lib.rs"],"retained-file-hash"); + assert!(checksum["files"].get("Cargo.toml.orig").is_none()); + assert!(!work.join("vendor/fixture/Cargo.toml.orig").exists()); + assert_eq!(fs::read_to_string(work.join("vendor/fixture/src/lib.rs")).unwrap(),"retained source"); + fs::remove_dir_all(work).unwrap(); +} + +#[test] +fn independent_pack_build_preserves_sources_requires_all_libraries_and_never_overwrites() { + let work=std::env::temp_dir().join(format!("mq-independent-packs-{}",std::process::id())); + fs::create_dir_all(work.join("ext/example")).unwrap(); + fs::create_dir_all(work.join("ext/native")).unwrap(); + fs::create_dir_all(work.join("compiled")).unwrap(); + fs::write(work.join("ext/VERSION"),"9.8.7\n").unwrap(); + fs::write(work.join("ext/example/index.mq.md"),"Readable source retained byte-for-byte.\n").unwrap(); + fs::write(work.join("ext/native/unrelated.so"),"do not include in sources").unwrap(); + let env=vec![("MARQDO_ENGINEERING_PLUGIN".into(),engineering().display().to_string())]; + let args=json!({"version":"9.8.7","platform":"x86_64-unknown-linux-gnu","directory":"out","native_dir":"compiled"}); + let invoke_pack=||invoke("skills/marqdo-release/packs.mq.md","build",args.clone(),"plugin,fs.write",&work,&env); + let missing=invoke_pack(); + assert_eq!(missing["error"]["code"],"packs.library","{missing}"); + assert!(!work.join("out").exists()); + for name in ["libweb.so","libagent.so","libquantum.so","liblinalg.so","libllm.so","libengineering.so"] { + fs::write(work.join("compiled").join(name),format!("format-only fixture: {name}\n")).unwrap(); + } + let built=invoke_pack(); + assert_eq!(built["ok"],true,"{built}"); + let value=&built["value"]; + let sources=&value["source"]; + assert!(sources["archive"]["entries"].as_array().unwrap().contains(&json!("ext/example/index.mq.md"))); + assert!(!sources["archive"]["entries"].as_array().unwrap().iter().any(|v|v.as_str().unwrap().contains("unrelated.so"))); + assert_eq!(sources["archive"]["metadata"]["ext/VERSION"],"9.8.7\n"); + let native_path=work.join(value["native"]["path"].as_str().unwrap()); + let native_before=fs::read(&native_path).unwrap(); + let mut archive=zip::ZipArchive::new(std::io::Cursor::new(&native_before)).unwrap(); + let mut selected=String::new(); + archive.by_name("native/libengineering.so").unwrap().read_to_string(&mut selected).unwrap(); + assert_eq!(selected,"format-only fixture: libengineering.so\n"); + assert_eq!(invoke_pack()["error"]["code"],"packs.output_exists"); + assert_eq!(fs::read(native_path).unwrap(),native_before); + assert!(!fs::read_dir(&work).unwrap().any(|e|e.unwrap().file_name().to_string_lossy().starts_with(".release-pack"))); + assert_eq!(fs::read_to_string(work.join("ext/example/index.mq.md")).unwrap(),"Readable source retained byte-for-byte.\n"); + fs::remove_dir_all(work).unwrap(); +} + +#[test] +fn independent_release_creation_checks_exact_tag_and_preserves_existing_publication() { + let work=std::env::temp_dir().join(format!("mq-ext-create-{}",std::process::id())); + fs::create_dir_all(&work).unwrap(); + let notes="本次变更 / Changes\nOnly isolated fixture data; no live publication.\n"; + fs::write(work.join("notes.md"),notes).unwrap(); + let listener=TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let address=listener.local_addr().unwrap(); + let done=Arc::new(AtomicBool::new(false));let server_done=done.clone(); + let sha="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + let server=thread::spawn(move||{ + let mut events=Vec::new();let mut created=false;let started=Instant::now(); + while started.elapsed()<Duration::from_secs(30) { + match listener.accept() { + Ok((mut stream,_))=>{ + let event=request(stream.try_clone().unwrap()); + let (status,body)=if event.path.ends_with("/git/ref/tags/ext-v9.8.7") { + ("200 OK",json!({"object":{"type":"commit","sha":sha}})) + } else if event.headers.starts_with("POST ") && event.path=="/repos/cflmy/marqdo/releases" { + created=true; + ("201 Created",json!({"id":77,"tag_name":"ext-v9.8.7","assets":[]})) + } else if event.path.ends_with("/releases/tags/ext-v9.8.7") { + if created {("200 OK",json!({"id":77,"tag_name":"ext-v9.8.7","assets":[]}))} + else {("404 Not Found",json!({"message":"not found"}))} + } else {panic!("unexpected fixture request: {event:?}")}; + events.push(event); + let body=body.to_string(); + write!(stream,"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",body.len()).unwrap(); + } + Err(e) if e.kind()==std::io::ErrorKind::WouldBlock=>{ + if server_done.load(Ordering::SeqCst){break} + thread::sleep(Duration::from_millis(5)); + } + Err(e)=>panic!("{e}"), + } + } + events + }); + let env=vec![ + ("MARQDO_ENGINEERING_PLUGIN".into(),engineering().display().to_string()), + ("MARQDO_RELEASE_API_BASE".into(),format!("http://{address}")), + ("GH_TOKEN".into(),"isolated-fixture-token".into()), + ]; + let file="skills/marqdo-release/github.mq.md"; + let wrong=invoke(file,"create_ext",json!({"version":"9.8.7","path":"notes.md","sha":"different","root":work}),"plugin,fs.read",&work,&env); + assert_eq!(wrong["error"]["code"],"release.source_mismatch","{wrong}"); + let args=json!({"version":"9.8.7","path":"notes.md","sha":sha,"root":work}); + let first=invoke(file,"create_ext",args.clone(),"plugin,fs.read",&work,&env); + assert_eq!(first["ok"],true,"{first}");assert_eq!(first["value"]["id"],77); + let again=invoke(file,"create_ext",args,"plugin,fs.read",&work,&env); + assert_eq!(again["ok"],true,"{again}");assert_eq!(again["value"]["id"],77); + done.store(true,Ordering::SeqCst); + let events=server.join().unwrap(); + let posts:Vec<_>=events.iter().filter(|e|e.headers.starts_with("POST ")).collect(); + assert_eq!(posts.len(),1,"{events:?}"); + let body:Value=serde_json::from_slice(&posts[0].body).unwrap(); + assert_eq!(body["tag_name"],"ext-v9.8.7"); + assert_eq!(body["target_commitish"],sha); + assert_eq!(body["body"],notes); + assert_eq!(body["draft"],false); + assert!(events.iter().all(|e|!e.headers.starts_with("PATCH ") && !e.headers.starts_with("DELETE "))); + fs::remove_dir_all(work).unwrap(); +} + +#[test] +fn extension_ci_rejects_receipt_path_and_byte_drift_before_remote_mutation() { + let work=std::env::temp_dir().join(format!("mq-ext-receipt-{}",std::process::id())); + fs::create_dir_all(work.join(".marqdo/release")).unwrap(); + fs::create_dir_all(work.join("dist/ext-release")).unwrap(); + let source="dist/ext-release/marqdo-9.8.7-ext.zip"; + let native_file="dist/ext-release/marqdo-9.8.7-native-x86_64-unknown-linux-gnu.zip"; + for path in [source,native_file] {fs::write(work.join(path),"reviewed fixture bytes").unwrap();} + let source_sha=invoke("lib/fs.mq.md","file_hash",json!({"path":source}),"fs.read",&work,&[]); + let native_sha=invoke("lib/fs.mq.md","file_hash",json!({"path":native_file}),"fs.read",&work,&[]); + let mut receipt=json!({"version":"9.8.7","platform":"x86_64-unknown-linux-gnu", + "source":{"path":source,"sha256":source_sha},"native":{"path":native_file,"sha256":native_sha}}); + let save=|value:&Value|fs::write(work.join(".marqdo/release/packs.json"),value.to_string()).unwrap(); + save(&receipt); + let env=vec![ + ("MARQDO_ENGINEERING_PLUGIN".into(),engineering().display().to_string()), + ("GITHUB_REF_NAME".into(),"ext-v9.8.7".into()), + ("RUNNER_OS".into(),"Linux".into()), + ("GITHUB_SHA".into(),"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into()), + ("MARQDO_RELEASE_API_BASE".into(),"http://127.0.0.1:1".into()), + ("GH_TOKEN".into(),"isolated-fixture-token".into()), + ]; + fs::write(work.join(native_file),"changed after verification").unwrap(); + let changed=invoke("skills/marqdo-release/packs.mq.md","attach_ci",json!({}),"plugin,fs.read,environment.read",&work,&env); + assert_eq!(changed["error"]["code"],"packs.changed","{changed}"); + receipt["source"]["path"]=json!("another-candidate.zip");save(&receipt); + let foreign=invoke("skills/marqdo-release/packs.mq.md","attach_ci",json!({}),"plugin,fs.read,environment.read",&work,&env); + assert_eq!(foreign["error"]["code"],"packs.receipt_path","{foreign}"); + fs::remove_dir_all(work).unwrap(); +} diff --git a/tests/repository_handbooks.rs b/tests/repository_handbooks.rs new file mode 100644 index 0000000..f1dcd6e --- /dev/null +++ b/tests/repository_handbooks.rs @@ -0,0 +1,220 @@ +//! Real CLI data transport, executable handbooks and repository authoring checks. +use std::{fs,path::PathBuf,process::{Command,Stdio},io::Write}; +fn root()->PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) } +fn native()->Command { let mut c=Command::new(env!("CARGO_BIN_EXE_marqdo"));c.current_dir(root());c } +#[test] +fn legacy_quoted_text_keeps_raw_backslashes_and_source() { + let work=std::env::temp_dir().join(format!("mq-native-authoring-{}",std::process::id())); + fs::create_dir_all(&work).unwrap(); + let source="---\nmarkup: occlusion\n---\n\n## 加一\n\n输入\u{0060}n\u{0060}之后,返回*[结果](n + 1)*。\n\n\"quotes\" 'single' \\\\ $HOME 😀\n"; + let out=native().args(["call","lib/fs.mq.md","write_text","path=\"source.mq.md\"", + &format!("text={}",format!("\"{source}\"")),"--effects","fs.write","--fs-root",work.to_str().unwrap(),"--json"]).output().unwrap(); + assert!(out.status.success(),"{}",String::from_utf8_lossy(&out.stdout)); + assert_eq!(fs::read_to_string(work.join("source.mq.md")).unwrap(),source); + let out=native().args(["call","lib/fs.mq.md","write_text","path=\"raw.txt\"", + "text='C:\\new\\file'","--effects","fs.write","--fs-root",work.to_str().unwrap(),"--json"]).output().unwrap(); + assert!(out.status.success(),"{}",String::from_utf8_lossy(&out.stdout)); + assert_eq!(fs::read_to_string(work.join("raw.txt")).unwrap(),"C:\\new\\file"); + let parsed=marqdo::call::parse_call_args(&[r#"text="C:\new\file\q""#.into()]).unwrap(); + assert_eq!(parsed[0].1,marqdo::value::Value::Text(r"C:\new\file\q".into())); + fs::remove_dir_all(work).unwrap(); +} + +fn call_stdin(args:&[&str],data:&str)->std::process::Output { + let mut cmd=native();cmd.args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); + let mut child=cmd.spawn().unwrap();child.stdin.take().unwrap().write_all(data.as_bytes()).unwrap(); + child.wait_with_output().unwrap() +} +#[test] +fn call_json_stdin_carries_large_literal_source_and_rejects_ambiguous_data() { + let work=std::env::temp_dir().join(format!("mq-native-json-{}",std::process::id()));fs::create_dir_all(&work).unwrap(); + let source=format!("$literal\n{}\n\"q\" \\\\ @literal", "源码与文档 😀\n".repeat(20000)); + let args=["call","lib/fs.mq.md","write_text","--args-json","-","--effects","fs.write","--fs-root",work.to_str().unwrap(),"--json"]; + let out=call_stdin(&args,&serde_json::json!({"path":"large.mq.md","text":source}).to_string()); + assert!(out.status.success(),"{}",String::from_utf8_lossy(&out.stdout)); + assert_eq!(fs::read_to_string(work.join("large.mq.md")).unwrap(),source); + for data in ["[]",r#"{"text":"a","text":"b"}"#] { + let out=call_stdin(&["call","lib/bytes.mq.md","from_text","--args-json","-","--json"],data); + assert!(!out.status.success(),"ambiguous data accepted: {data}"); + } + let out=call_stdin(&["call","lib/bytes.mq.md","from_text","text=\"named\"","--args-json","-","--json"],r#"{"text":"json"}"#); + assert!(!out.status.success(),"mixed argument channels accepted"); + fs::remove_dir_all(work).unwrap(); +} +#[test] +fn literal_json_strings_remain_literal_in_a_call_session() { + let work=std::env::temp_dir().join(format!("mq-native-json-session-{}",std::process::id()));fs::create_dir_all(&work).unwrap(); + let args=["call","lib/bytes.mq.md","from_text","--args-json","-","--session","literal","--toget","data","--json"]; + let mut cmd=native();cmd.args(args).env("MARQDO_CALL_SESSION_DIR",&work).stdin(Stdio::piped()).stdout(Stdio::piped()); + let mut child=cmd.spawn().unwrap();child.stdin.take().unwrap().write_all(br#"{"text":"$not_a_reference"}"#).unwrap(); + let out=child.wait_with_output().unwrap();assert!(out.status.success(),"{}",String::from_utf8_lossy(&out.stdout)); + let file=work.join("literal.json"); + let mut journal:serde_json::Value=serde_json::from_slice(&fs::read(&file).unwrap()).unwrap(); + assert_eq!(journal["steps"][0]["literal_args"],true); + journal["bindings"].as_object_mut().unwrap().remove("data"); + journal["journal_bindings"]["data"]=serde_json::json!(1); + fs::write(&file,serde_json::to_vec(&journal).unwrap()).unwrap(); + let out=native().env("MARQDO_CALL_SESSION_DIR",&work) + .args(["call","lib/bytes.mq.md","to_text","data=$data","--session","literal","--json"]).output().unwrap(); + assert!(out.status.success(),"{}",String::from_utf8_lossy(&out.stdout)); + let answer:serde_json::Value=serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(answer["result"],"$not_a_reference"); + fs::remove_dir_all(work).unwrap(); +} + +#[test] +fn json_argument_envelope_allows_independent_lists_but_preserves_value_domain() { + let parsed=marqdo::call::parse_call_args_json(r#"{"a":[1],"b":[2,3]}"#).unwrap(); + assert_eq!(parsed.len(),2); + for bad in [r#"{"a":{"x":[1],"y":[2,3]}}"#,r#"{"a":9007199254740992}"#,r#"{"a":{"x":1,"x":2}}"#] { + assert!(marqdo::call::parse_call_args_json(bad).is_err(),"{bad}"); + } +} + +#[test] +fn require_ok_preserves_failed_result_and_stops_external_execution_flow() { + let args=["call","lib/result.mq.md","error","code=\"fixture\"","message=\"stop here\"","--json"]; + let ordinary=native().args(args).output().unwrap(); + assert!(ordinary.status.success()); + let checked=native().args(args).arg("--require-ok").output().unwrap(); + assert!(!checked.status.success()); + let value:serde_json::Value=serde_json::from_slice(&checked.stdout).unwrap(); + assert_eq!(value["result"]["ok"],false); + assert_eq!(value["result"]["error"]["code"],"fixture"); + let success=native().args(["call","lib/result.mq.md","ok","value=False","--require-ok","--json"]).output().unwrap(); + assert!(success.status.success()); +} + +#[test] +fn native_writeback_call_uses_entry_source_and_the_native_filesystem_root() { + use marqdo::{Backend,call::{CallEffects,CallOptions,call_file_with}}; + let work=std::env::temp_dir().join(format!("mq-call-writeback-{}",std::process::id())); + fs::create_dir_all(work.join("restricted")).unwrap(); + let import=root().join("lib/writeback.mq.md").display().to_string().replace('\\',"/"); + let file=work.join("task.mq.md"); + let source=format!("---\nmarkup: occlusion\nimport:\n wb: {import}\n---\n\n## task\n\nWe **written = [Record the real source-local result](wb.record(value=\"observed\", key=\"summary\"))**.\nReturn *[Read the recorded slot](wb.get(key=\"summary\"))*.\n"); + fs::write(&file,&source).unwrap(); + let opts=||CallOptions{effects:CallEffects::parse("fs.write").unwrap(),fs_root:Some(work.clone()),..Default::default()}; + for _ in 0..2 { + let value=call_file_with(&file,"task",&[],Backend::Tree,opts()).unwrap(); + assert!(value.as_display().contains("observed"),"{value:?}"); + } + let recorded=fs::read_to_string(&file).unwrap(); + assert_eq!(recorded.matches("<!-- marqdo-out summary").count(),1); + assert!(call_file_with(&file,"task",&[],Backend::Tree,CallOptions{fs_root:Some(work.join("restricted")),..opts()}).is_err()); + assert_eq!(fs::read_to_string(&file).unwrap(),recorded); + fs::remove_dir_all(work).unwrap(); +} + +#[test] +fn native_review_receipts_and_stale_batch_preflight_preserve_exact_sources() { + let work=std::env::temp_dir().join(format!("mq-native-review-{}",std::process::id())); + fs::create_dir_all(&work).unwrap(); + let first="\u{feff}source\r\n$literal 😀\r\n"; + fs::write(work.join("first.txt"),first).unwrap(); + fs::write(work.join("second.txt"),"keep second\n").unwrap(); + let run=|function:&str,args:serde_json::Value|{ + let out=call_stdin(&["call","skills/marqdo-dev/files.mq.md",function,"--args-json","-","--effects","fs.write","--fs-root",work.to_str().unwrap(),"--json"],&args.to_string()); + assert!(out.status.success(),"{}",String::from_utf8_lossy(&out.stdout)); + serde_json::from_slice::<serde_json::Value>(&out.stdout).unwrap()["result"].clone() + }; + let observed=run("read_many",serde_json::json!({"paths":["first.txt","second.txt"]})); + assert_eq!(observed[0]["source"],first); + let digest=call_stdin(&["call","lib/hash.mq.md","sha256","--args-json","-","--json"],&serde_json::json!({"text":first}).to_string()); + assert!(digest.status.success()); + let digest:serde_json::Value=serde_json::from_slice(&digest.stdout).unwrap(); + assert_eq!(observed[0]["sha256"],digest["result"]); + fs::write(work.join("first.txt"),"concurrently changed\n").unwrap(); + let result=run("apply",serde_json::json!({"updates":[ + {"path":"second.txt","source":"must not be written\n","expected_sha256":observed[1]["sha256"]}, + {"path":"first.txt","source":"stale proposal\n","expected_sha256":observed[0]["sha256"]} + ]})); + assert_eq!(result["ok"],false); + assert_eq!(result["error"]["code"],"authoring.changed"); + assert_eq!(fs::read_to_string(work.join("first.txt")).unwrap(),"concurrently changed\n"); + assert_eq!(fs::read_to_string(work.join("second.txt")).unwrap(),"keep second\n"); + fs::remove_dir_all(work).unwrap(); +} + +#[test] +fn readable_syntax_tour_is_a_callable_program_on_both_backends() { + use marqdo::{Backend,call::{CallEffects,CallOptions,call_file_with},value::Value}; + for backend in [Backend::Tree,Backend::Bytecode] { + let report=call_file_with(&root().join("examples/syntax-tour/index.mq.md"),"main",&[],backend, + CallOptions{effects:CallEffects::parse("output.write").unwrap(),..Default::default()}).unwrap(); + let Value::Map(fields)=report else {panic!("expected actual demonstration values")}; + for (name,expected) in [("name_length",6),("sum",3),("comma_sum",3),("nested_sum",13),("spaced_name",32)] { + assert_eq!(fields.iter().find(|(k,_)|k==name).unwrap().1,Value::Int(expected),"{name}"); + } + assert_eq!(fields.iter().find(|(k,_)|k=="unfinished").unwrap().1,Value::None); + } +} + +#[test] +fn native_public_file_examples_preserve_caller_files_on_both_backends() { + use marqdo::{Backend,call::{CallEffects,CallOptions,call_file_with},value::Value}; + let work=std::env::temp_dir().join(format!("mq-public-files-{}",std::process::id())); + let kept=[("out/demo.txt","caller source"),("out/demo-copy.txt","caller copy"), + ("m9-demo/readme.txt","caller English"),("m9-演示/说明.txt","caller Chinese")]; + for (name,text) in kept { + let path=work.join(name);fs::create_dir_all(path.parent().unwrap()).unwrap();fs::write(path,text).unwrap(); + } + for backend in [Backend::Tree,Backend::Bytecode] { + for file in ["public/features/09-path-fs.mq.md","public/features/09-路径文件.mq.md", + "public/features/16-fs-mid2.mq.md","public/features/16-文件mid2.mq.md"] { + let observed=call_file_with(&root().join(file),"main",&[],backend, + CallOptions{effects:CallEffects::parse("fs.write").unwrap(),fs_root:Some(work.clone()),..Default::default()}).unwrap(); + let Value::Map(fields)=observed else {panic!("expected actual file observations")}; + if file.contains("/09-") { + assert_eq!(fields.iter().find(|(k,_)|k=="copied_text").unwrap().1,Value::Text("path-m2".into())); + } else { + let expected=if file.contains("16-fs"){2}else{3}; + assert_eq!(fields.iter().find(|(k,_)|k=="size").unwrap().1,Value::Int(expected)); + assert_eq!(fields.iter().find(|(k,_)|k=="entries").unwrap().1,Value::Int(2)); + } + for (name,text) in kept {assert_eq!(fs::read_to_string(work.join(name)).unwrap(),text);} + assert_eq!(fs::read_dir(&work).unwrap().count(),3,"temporary tree leaked: {file}"); + } + } + fs::remove_dir_all(work).unwrap(); +} + +#[test] +fn native_excerpt_keeps_one_based_locations_and_clips_long_unicode_lines() { + let work=std::env::temp_dir().join(format!("mq-native-excerpt-{}",std::process::id())); + fs::create_dir_all(&work).unwrap(); + fs::write(work.join("lines.txt"),format!("before\r\n{}\r\nafter\r\n","文".repeat(2500))).unwrap(); + for backend in ["tree","bytecode"] { + let args=["call","skills/marqdo-dev/files.mq.md","excerpt","--backend",backend,"--args-json","-","--effects","fs.read","--fs-root",work.to_str().unwrap(),"--json"]; + let output=call_stdin(&args,r#"{"path":"lines.txt","start":2,"count":2}"#); + assert!(output.status.success(),"{}",String::from_utf8_lossy(&output.stdout)); + let actual:serde_json::Value=serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(actual["result"]["total_lines"],3); + assert_eq!(actual["result"]["lines"][0]["line"],2); + assert_eq!(actual["result"]["lines"][0]["text"].as_str().unwrap().chars().count(),2000); + assert_eq!(actual["result"]["lines"][1]["text"],"after"); + let output=call_stdin(&args,r#"{"path":"lines.txt","count":201}"#); + let actual:serde_json::Value=serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(actual["result"]["ok"],false); + } + fs::remove_dir_all(work).unwrap(); +} + +#[test] +fn request_query_resource_defaults_remain_native_values_on_both_backends() { + for backend in ["tree","bytecode"] { + for (file,function,args) in [ + ("ext/data/view.mq.md","query",r#"{"source":"articles"}"#), + ("ext/data/视图.mq.md","查询",r#"{"源":"articles"}"#), + ] { + let out=call_stdin(&["call",file,function,"--backend",backend,"--args-json","-","--json"],args); + assert!(out.status.success(),"{}",String::from_utf8_lossy(&out.stdout)); + let body:serde_json::Value=serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(body["result"]["_type"],"data_query"); + assert_eq!(body["result"]["detail"],false); + assert_eq!(body["result"]["tenant_scope"],false); + assert_eq!(body["result"]["limit"],50); + assert!(body["result"]["where"].is_null()); + } + } +} diff --git a/tests/view_readability.rs b/tests/view_readability.rs index 6f44765..516bf30 100644 --- a/tests/view_readability.rs +++ b/tests/view_readability.rs @@ -125,3 +125,31 @@ fn knowledge_cards_use_real_contracts_and_keep_verification_states_separate() { structure.contains("由作者补充具体业务</button><span class=\"occl-stub\">待补充实际逻辑") ); } + +#[test] +fn automatic_reader_marks_callable_modules_without_executing_tools_or_hiding_program_errors() { + let temp = Scratch::new(); + let source = temp.0.join("tools.mq.md"); + fs::write(&source, "---\nmarkup: occlusion\nimport:\n fs: lib/fs.mq.md\n---\n\n## write_marker\n\nWe **[Write only when explicitly called](fs.write_text(path=\"must-not-exist\", text=\"unexpected automatic call\"))**.\nReturn *None*.\n\n## ask\n\nReturn *[Read only when called](input(prompt=\"Tool input\"))*.\n").unwrap(); + let render = |file: &std::path::Path, output: &std::path::Path| { + let out = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .current_dir(env!("CARGO_MANIFEST_DIR")) + .args(["view", "output", "--out"]).arg(output).arg(file).output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let mut paths = Vec::new(); html_files(output, &mut paths); + paths.iter().map(|p| fs::read_to_string(p).unwrap()) + .find(|s| s.contains("id=\"structure\"")).unwrap() + }; + let html = render(&source, &temp.0.join("library-out")); + assert!(html.contains(">module</span>"), "module status was lost"); + assert!(html.contains("这是可调用模块,未自动执行")); + assert!(!html.contains(">fail</span>"), "a callable library became a failed program"); + assert!(!temp.0.join("must-not-exist").exists()); + assert!(!html.contains("<form class=\"stdin-form\""), "a helper's input prompted during library reading"); + + let broken = temp.0.join("broken.mq.md"); + fs::write(&broken, "---\nmarkup: occlusion\n---\n\n## main\n\nReturn *[Real program failure](1 / 0)*.\n").unwrap(); + let html = render(&broken, &temp.0.join("broken-out")); + assert!(html.contains(">fail</span>"), "a real entry failure was hidden"); + assert!(!html.contains(">module</span>")); +} diff --git a/tests/wasm/counter.mq.md b/tests/wasm/counter.mq.md new file mode 100644 index 0000000..6bae4d1 --- /dev/null +++ b/tests/wasm/counter.mq.md @@ -0,0 +1,51 @@ +--- +markup: occlusion +title: browser counter (C3) +description: wire table + browser.set_text — no json glue +import: + browser: lib/browser.mq.md +--- + +# main + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Browser event registration rows | + +Initialize one browser counter and register two click handlers against the host page's bump and reset controls. The table is an event-routing list: each row identifies a selector, event and actual callback. Returning it does not simulate a click or increment the count. + +The browser runtime preserves this instance's state between callbacks. To verify behavior, click bump and observe the displayed count, then reset it to zero. A native CLI run can inspect the registration value but does not establish that a browser applied it. + +We first **count = 0** for the next step. + +`wire` = + +| @ | 选择器 | 事件 | 调用 | +|---|--------|------|------| +| 1 | "#bump" | click | bump | +| 2 | "#reset" | click | reset | + +After these steps, return *wire*. + +## bump + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | A plain set_text instruction with the next counter value | + +This click callback reads the count already retained by the browser session. It takes no event input and does not ask the caller to supply the current state. After incrementing the native integer, convert it to text for the existing count target. Returning an instruction still relies on the official bridge to update the visible page. + +We **count = count + 1** and **label = [Convert the updated native count to text](str(count))**. +Return *[Display this session's new count](browser.set_text(sel="#count", text=`label`))*. + + +## reset + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | A plain set_text instruction showing zero | + +Reset changes the same session count used by bump. It takes no argument and does not create a new browser instance. The displayed text and retained integer are set together, so the next bump should show one. The callback describes a DOM effect and performs no direct server or file operation. + +We **count = 0** before describing the visible result. +Return *[Show the reset state](browser.set_text(sel="#count", text="0"))*. diff --git a/tests/wasm/list-records.mjs b/tests/wasm/list-records.mjs new file mode 100644 index 0000000..f591f30 --- /dev/null +++ b/tests/wasm/list-records.mjs @@ -0,0 +1,27 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import {renderListItems} from "../../crates/marqdo-wasm/js/marqdo-bridge.js"; + +test("typed list children retain text, controls and literal identities",()=>{ + const html=renderListItems({tag:"li",items:[{attrs:{"data-id":"row-1"},children:[ + {tag:"span",text:'A <tag> "quote" & literal'}, + {tag:"button",text:"删",attrs:{type:"button","data-id":'id" & value',disabled:false}} + ]}]}); + assert.ok(html.includes("A <tag> "quote" & literal")); + assert.ok(html.includes('<button type="button" data-id="id" & value">删</button>')); + assert.ok(!html.includes("<tag>") && !html.includes(" disabled")); + assert.equal(renderListItems({items:["a",{text:"b"}]}),"<li>a</li><li>b</li>"); + assert.equal(renderListItems({items:[{html:"<em>explicit legacy</em>"}]}),"<li><em>explicit legacy</em></li>"); +}); +test("structural lists reject malformed nodes and bounded recursion",()=>{ + for(const item of [ + {tag:'button onclick="x"',text:"x"},{tag:"script",text:"x"}, + {attrs:{"data-id onload":"x"},text:"x"},{attrs:{onclick:"x"},text:"x"}, + {attrs:{href:"javascript:alert(1)"},text:"x"}, + {children:"not a list"},{text:"ambiguous",children:[]},{tag:"input",children:[{text:"x"}]} + ]) assert.throws(()=>renderListItems({items:[item]}),/render_list/); + let deep={text:"leaf"}; + for(let i=0;i<34;i++)deep={children:[deep]}; + assert.throws(()=>renderListItems({items:[deep]}),/limit/); + assert.throws(()=>renderListItems({items:Array(10001).fill("x")}),/limit/); +}); diff --git a/tests/wasm/smoke.mjs b/tests/wasm/smoke.mjs index 15f76ee..eded42a 100644 --- a/tests/wasm/smoke.mjs +++ b/tests/wasm/smoke.mjs @@ -18,12 +18,12 @@ const root = path.resolve(__dirname, "../.."); const wasmPath = process.argv[2] || - path.join(root, "examples/browser-hello/marqdo_wasm.wasm"); -const srcPath = path.join(root, "examples/browser-hello/counter.mq.md"); + path.join(root, ".marqdo/browser-handbook-assets/marqdo_wasm.wasm"); +const srcPath = path.join(root, "tests/wasm/counter.mq.md"); if (!fs.existsSync(wasmPath)) { console.error("missing wasm:", wasmPath); - console.error("build: marqdo wasm build -o examples/browser-hello"); + console.error("build: marqdo call skills/marqdo-dev/index.mq.md build_browser --effects plugin,process.exec,fs.write --fs-root . --json"); process.exit(2); } diff --git a/tests/wasm_smoke.rs b/tests/wasm_smoke.rs index ce3fe7f..68cf37d 100644 --- a/tests/wasm_smoke.rs +++ b/tests/wasm_smoke.rs @@ -11,7 +11,7 @@ fn wasm_artifact() -> Option<PathBuf> { cands.push(PathBuf::from( "target/wasm32-unknown-unknown/release-wasm/marqdo_wasm.wasm", )); - cands.push(PathBuf::from("examples/browser-hello/marqdo_wasm.wasm")); + cands.push(PathBuf::from(".marqdo/browser-handbook-assets/marqdo_wasm.wasm")); cands.into_iter().find(|p| p.is_file()) } @@ -29,11 +29,11 @@ fn wasm_node_abi_smoke() { return; } let status = Command::new(env!("CARGO_BIN_EXE_marqdo")) - .args(["wasm", "build", "-o", "examples/browser-hello"]) + .args(["wasm", "build", "-o", ".marqdo/browser-handbook-assets"]) .status() .expect("marqdo wasm build"); assert!(status.success(), "marqdo wasm build failed"); - PathBuf::from("examples/browser-hello/marqdo_wasm.wasm") + PathBuf::from(".marqdo/browser-handbook-assets/marqdo_wasm.wasm") } }; assert!(wasm.is_file(), "missing {}", wasm.display()); diff --git a/tests/web_handbook.rs b/tests/web_handbook.rs index 637866f..7dd65a4 100644 --- a/tests/web_handbook.rs +++ b/tests/web_handbook.rs @@ -292,12 +292,18 @@ fn decomposition_projects_preview_and_serve_the_same_structure() { command(&scratch.0) .current_dir(&site) .args([ - "run", - "serve.mq.md", + "call", + if zh { root().join("ext/web/网页.mq.md") } else { root().join("ext/web/web.mq.md") }.to_str().unwrap(), + if zh { "服务" } else { "serve" }, "--backend", backend, - "--bind", + &format!("{}={}", if zh { "根" } else { "root" }, serde_json::to_string(&site).unwrap()), &format!("{}={port}", if zh { "端口" } else { "port" }), + "--effects", + "plugin,fs.read,network.write", + "--fs-root", + site.to_str().unwrap(), + "--json", ]) .stdout(Stdio::from(log.try_clone().unwrap())) .stderr(Stdio::from(log)) @@ -351,3 +357,461 @@ fn metadata_only_endpoint_has_the_same_result_on_both_backends() { } assert_eq!(results[0], results[1]); } + +fn browser_json(value: &marqdo::value::Value) -> Value { + marqdo::browser_session::value_as_json(value).unwrap() +} +#[test] +fn spa_client_keeps_native_records_selection_history_and_text_effects() { + let source = fs::read_to_string(root().join("examples/web-spa-app/static/client.mq.md")).unwrap(); + let (mut session, boot) = marqdo::browser_session::BrowserSession::boot(&source).unwrap(); + let boot = browser_json(&boot); + assert_eq!(boot["render_list"]["#items"]["items"].as_array().unwrap().len(), 2); + assert!(boot.get("navigate").is_none(), "boot must not push history: {boot}"); + let detail = browser_json(&session.call("open_item", r#"{"data_id":"1"}"#).unwrap()); + assert_eq!(detail["set_text"]["#title"], "Detail"); + assert_eq!(detail["set_text"]["#detail-body"], "Alpha"); + assert_eq!(detail["set_text"]["#log"], "/item"); + assert_eq!(detail["set_attr"]["#view-list"]["hidden"], true); + let edit = browser_json(&session.call("go_edit", "{}").unwrap()); + assert_eq!(edit["set_value"]["#edit-title"], "Alpha"); + let saved = browser_json(&session.call("save_item", r#"{"value":"A <tag> \"quoted\""}"#).unwrap()); + assert_eq!(saved["set_text"]["#detail-body"], "A <tag> \"quoted\""); + assert_eq!(saved["render_list"]["#items"]["items"][0]["attrs"]["data-id"], "1"); + assert!(saved.get("set_html").is_none(), "user text became HTML: {saved}"); + session.call("go_new", "{}").unwrap(); + let created = browser_json(&session.call("save_item", r#"{"value":"Gamma"}"#).unwrap()); + assert_eq!(created["render_list"]["#items"]["items"].as_array().unwrap().len(), 3); + assert_eq!(created["render_list"]["#items"]["items"][2]["attrs"]["data-id"], "3"); + let pop = browser_json(&session.call("on_pop", r#"{"path":"/"}"#).unwrap()); + assert_eq!(pop["set_text"]["#title"], "Items"); + assert_eq!(pop["set_attr"]["#view-list"]["hidden"], false); + assert!(pop.get("navigate").is_none(), "Back created another history entry: {pop}"); + let empty = browser_json(&session.call("save_item", r#"{"value":""}"#).unwrap()); + assert_eq!(empty["set_text"]["#log"], "title required"); +} + +#[test] +fn collaborative_client_keeps_the_next_local_edit_after_a_remote_snapshot() { + let source=fs::read_to_string(root().join("examples/web-collab-doc/static/client.mq.md")).unwrap(); + let (mut session, boot)=marqdo::browser_session::BrowserSession::boot(&source).unwrap(); + assert_eq!(browser_json(&boot)["ws"]["url"],"/live/demo"); + let remote=browser_json(&session.call("on_msg",r#"{"data":"DOC\tremote"}"#).unwrap()); + assert_eq!(remote["set_value"]["#doc"],"remote"); + let local=browser_json(&session.call("on_edit",r#"{"value":"next local"}"#).unwrap()); + assert_eq!(local["ws"]["data"],"DOC\tnext local"); + let echoed=session.call("on_msg",r#"{"data":"DOC\tnext local"}"#).unwrap(); + assert_eq!(echoed,marqdo::value::Value::None); + let empty=browser_json(&session.call("on_edit",r#"{"value":""}"#).unwrap()); + assert_eq!(empty["ws"]["data"],"DOC\t"); +} + +#[test] +fn callable_tenant_site_scopes_queries_and_preserves_data_across_restart() { + let scratch = Scratch::new("tenant"); + fs::create_dir_all(scratch.0.join("db")).unwrap(); + for file in ["index.mq.md", "intro.md", "db/index.mq.md"] { + fs::copy(root().join("examples/web-tenant-saas").join(file), scratch.0.join(file)).unwrap(); + } + let insert = scratch.0.join("insert.mq.md"); + fs::write(&insert, "---\nmarkup: occlusion\nimport:\n db: ext/data/db.mq.md\n---\n\n## add\n\nUse `url` for this owned database.\n\nWe **store = db.db(url=`url`)**.\n\n`row` =\n\n| title | tenant_id |\n|---|---|\n| User note | acme |\n\nReturn *[Insert a business record](> `store`.insert table=\"items\" rows=`row`)*.\n").unwrap(); + for backend in ["tree", "bytecode"] { + let db_file = scratch.0.join(format!("{backend}.db")); + for pass in 0..2 { + let port = TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + let logpath = scratch.0.join(format!("{backend}-{pass}.log")); + let log = fs::File::create(&logpath).unwrap(); + let mut server = Server(command(&scratch.0).args([ + "call", "examples/web-tenant-saas/index.mq.md", "serve", + "--backend", backend, + &format!("root={}", serde_json::to_string(&scratch.0).unwrap()), + &format!("port={port}"), + &format!("url={}", serde_json::to_string(&format!("sqlite:{}", db_file.display())).unwrap()), + "--effects", "plugin,fs.write,network.write", + "--fs-root", scratch.0.to_str().unwrap(), "--json", + ]).stdout(Stdio::from(log.try_clone().unwrap())).stderr(Stdio::from(log)).spawn().unwrap()); + let deadline = Instant::now() + Duration::from_secs(8); + let home = loop { + if let Ok(response) = get(port, "/") { break response; } + assert!(server.0.try_wait().unwrap().is_none() && Instant::now() < deadline, + "tenant startup failed: {}", fs::read_to_string(&logpath).unwrap()); + thread::sleep(Duration::from_millis(30)); + }; + assert!(home.contains("200 OK") && home.contains("Two-tenant query demonstration"), "{home}"); + for (scope, count) in [("acme", pass + 1), ("beta", 1), ("unknown", 0)] { + let response = get(port, &format!("/api/items?t={scope}")).unwrap(); + assert!(response.contains("200 OK"), "{response}"); + let body: Value = serde_json::from_str(response.split_once("\r\n\r\n").unwrap().1).unwrap(); + let rows = body["rows"].as_array().unwrap_or_else(|| panic!("unexpected JSON query body: {body}")); + assert_eq!(rows.len(), count, "[{backend}] pass {pass}: {body}"); + assert!(rows.iter().all(|row| row["tenant_id"] == scope), "{body}"); + } + let missing = get(port, "/api/items").unwrap(); + assert!(missing.contains("400 Bad Request") && missing.contains("tenant required"), "{missing}"); + server.0.kill().unwrap(); + server.0.wait().unwrap(); + if pass == 0 { + let out = command(&scratch.0).args([ + "call", insert.to_str().unwrap(), "add", "--backend", backend, + &format!("url={}", serde_json::to_string(&format!("sqlite:{}", db_file.display())).unwrap()), + "--effects", "plugin", "--fs-root", scratch.0.to_str().unwrap(), "--json", + ]).output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stdout)); + } + } + } +} + +#[test] +fn recursive_network_site_retains_live_data_forms_tools_and_native_admin() { + fn copy_sources(from: &Path, to: &Path) { + fs::create_dir_all(to).unwrap(); + for entry in fs::read_dir(from).unwrap() { + let entry=entry.unwrap(); let name=entry.file_name(); + if name.to_string_lossy().starts_with('.') || name=="data" || name=="generated" { continue; } + let src=entry.path(); let dst=to.join(name); + if src.is_dir() { copy_sources(&src,&dst); } + else { fs::copy(src,dst).unwrap(); } + } + } + fn request(port:u16,method:&str,path:&str,form:&str,cookie:&str)->String { + let mut stream=TcpStream::connect(("127.0.0.1",port)).unwrap(); + stream.set_read_timeout(Some(Duration::from_secs(3))).unwrap(); + write!(stream,"{method} {path} HTTP/1.0\r\nHost: localhost\r\nConnection: close\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: {}\r\nCookie: {cookie}\r\n\r\n{form}",form.len()).unwrap(); + let mut out=String::new();stream.read_to_string(&mut out).unwrap();out + } + fn cookie(response:&str)->String { + response.lines().find_map(|line|line.split_once(':') + .filter(|(key,_)|key.eq_ignore_ascii_case("set-cookie")) + .map(|(_,value)|value.trim().split(';').next().unwrap().to_string())).unwrap() + } + for (site, welcome, about_copy, required_copy, bytes_copy) in [ + ("web-net-site", "Welcome to the web-net site", "Each responsibility", "Title is required", "<bytes>"), + ("web-net-site-zh", "网络扩展站", "各个职责", "标题不能为空", "<字节>"), + ] { + for backend in ["tree","bytecode"] { + let scratch=Scratch::new(&format!("network-{site}-{backend}")); + copy_sources(&root().join("examples").join(site),&scratch.0); + fs::create_dir_all(scratch.0.join("public/generated")).unwrap(); + // HTTP behavior does not execute these browser assets. The real-browser + // suite separately uses an actual current WASM build. + for name in ["marqdo_wasm.wasm","marqdo-bridge.js"] { + fs::write(scratch.0.join("public/generated").join(name),"HTTP-only fixture").unwrap(); + } + let port=TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + let logpath=scratch.0.join("server.log"); + let log=fs::File::create(&logpath).unwrap(); + let mut server=Server(command(&scratch.0).args([ + "call",&format!("examples/{site}/index.mq.md"),"serve","--backend",backend, + &format!("root={}",serde_json::to_string(&scratch.0).unwrap()), + &format!("port={port}"),"--effects","plugin,fs.write,network.write", + "--fs-root",scratch.0.to_str().unwrap(),"--json", + ]).stdout(Stdio::from(log.try_clone().unwrap())).stderr(Stdio::from(log)).spawn().unwrap()); + let deadline=Instant::now()+Duration::from_secs(10); + let home=loop { + if let Ok(body)=get(port,"/") { break body; } + assert!(server.0.try_wait().unwrap().is_none() && Instant::now()<deadline, + "network startup failed [{backend}]: {}",fs::read_to_string(&logpath).unwrap()); + thread::sleep(Duration::from_millis(30)); + }; + for expected in ["200 OK",welcome,"live-send","/static/client.mq.md"] { + assert!(home.contains(expected),"missing {expected}: {home}"); + } + let about=get(port,"/about").unwrap(); + assert!(about.contains("200 OK") && about.contains(about_copy),"{about}"); + let tools=get(port,"/tools").unwrap(); + for expected in ["200 OK","http_only","pic.png","image/png",bytes_copy] { + assert!(tools.contains(expected),"missing {expected}: {tools}"); + } + let denied=get(port,"/admin").unwrap(); + assert!(denied.contains("303 See Other") && denied.contains("/admin/login"),"{denied}"); + let new=get(port,"/new").unwrap(); + let guest=cookie(&new); + let csrf=regex::Regex::new(r#"name="_csrf" value="([^"]+)""#).unwrap() + .captures(&new).unwrap()[1].to_string(); + let invalid=request(port,"POST","/_form/article",&format!("_csrf={csrf}&title="),&guest); + assert!(invalid.contains("200 OK") && invalid.contains(required_copy) && + invalid.contains(&format!("value=\"{csrf}\"")),"{invalid}"); + let created=request(port,"POST","/_form/article", + &format!("_csrf={csrf}&title=Created+after+startup&body=Current+body"),&guest); + assert!(created.contains("303 See Other"),"{created}"); + let current=get(port,"/").unwrap(); + assert!(current.contains("Created after startup"),"{current}"); + let fragment=get(port,"/_part/articles").unwrap(); + assert!(fragment.contains("200 OK") && fragment.contains("Created after startup") && + !fragment.contains("Try the capabilities") && !fragment.contains("<!DOCTYPE"),"{fragment}"); + let form_fragment=get(port,"/new/_part/article-form").unwrap(); + assert!(form_fragment.contains("200 OK") && form_fragment.contains("name=\"_csrf\"") && + !form_fragment.contains("Try the capabilities"),"{form_fragment}"); + let missing=get(port,"/_part/not-declared").unwrap(); + assert!(missing.contains("404 Not Found"),"{missing}"); + + let login=request(port,"POST","/admin/login", + &format!("_csrf={csrf}&username=admin&password=secret"),&guest); + assert!(login.contains("303 See Other"),"{login}"); + let authenticated=cookie(&login); + let admin=request(port,"GET","/admin/","",&authenticated); + assert!(admin.contains("200 OK") && admin.contains("articles") && admin.contains("Created after startup"),"{admin}"); + } + } +} +#[test] +fn callable_inspection_observes_later_resources_instead_of_the_prepare_snapshot() { + let scratch=Scratch::new("inspect-resources"); + fs::write(scratch.0.join("index.mq.md"),"---\ntype: web\nroute: /\ntitle: Inspection fixture\n---\n\n# Metadata page\n").unwrap(); + let program=scratch.0.join("inspect.mq.md"); + fs::write(&program,"---\nmarkup: occlusion\nimport:\n web: ext/web/web.mq.md\n socket: ext/net/websocket.mq.md\n form: ext/data/form.mq.md\n auth: ext/security/auth.mq.md\n---\n\n## main\n\nUse `root` for the owned site.\n\nWe **app = web.prepare(root=`root`)** and **app = socket.route(app=`app`, path=\"/live\", mode=\"echo\", require_auth=False)** and **selected = form.form(table=\"articles\")** and **app = form.mount(app=`app`, id=\"article\", form=`selected`)**.\n\n`users` =\n\n| username | password | role |\n|---|---|---|\n| fixture | do-not-return-this-password | admin |\n\nWe **app = auth.attach(app=`app`, users=`users`, login_path=\"/members/login\")**.\nReturn *web.inspect(app=`app`)*.\n").unwrap(); + for backend in ["tree","bytecode"] { + let output=command(&scratch.0).args(["call",program.to_str().unwrap(),"main", + "--backend",backend,&format!("root={}",serde_json::to_string(&scratch.0).unwrap()), + "--effects","plugin,fs.read","--fs-root",scratch.0.to_str().unwrap(),"--json"]) + .output().unwrap(); + assert!(output.status.success(),"{}",String::from_utf8_lossy(&output.stdout)); + let report:Value=serde_json::from_slice(&output.stdout).unwrap(); + let value=&report["result"]; + assert_eq!(value["scope"],"registered","{report}"); + let declared=value["declared"].as_array().unwrap(); + assert!(declared.iter().any(|row|row["path"]=="/live" && row["kind"]=="websocket"),"{report}"); + assert!(declared.iter().any(|row|row["path"]=="/" && row["file"]=="index.mq.md"),"{report}"); + let system=value["system"].as_array().unwrap(); + assert!(system.iter().any(|row|row["path"]=="/members/login" && row["method"]=="POST"),"{report}"); + assert!(system.iter().any(|row|row["path"]=="/_form/{id}" && row["method"]=="POST"),"{report}"); + assert!(!output.stdout.windows("do-not-return-this-password".len()).any(|w|w==b"do-not-return-this-password")); + } +} + +#[test] +fn pure_head_resources_match_preview_and_serving_on_both_backends() { + let scratch=Scratch::new("pure-head"); + let entry=scratch.0.join("index.mq.md"); + fs::write(&entry,"---\nmarkup: occlusion\ntype: web\nview: main\nroute: /\ntitle: Actual head fixture\nimport:\n component: ext/web/component/index.mq.md\n head: ext/web/head.mq.md\n zh: ext/web/页头.mq.md\n web: ext/web/web.mq.md\n---\n\n## main\n\nThe head is pure; body remains ordinary Markdown nodes.\n\n`meta` =\n\n| key | value |\n|---|---|\n| description | Real <literal> \"value\" |\n| og:title | Head resource |\n\n`links` =\n\n| rel | href | crossorigin |\n|---|---|---|\n| preconnect | https://fonts.example.test | anonymous |\n| stylesheet | /theme.css | |\n\nWe **resource = head.resource(meta=`meta`, links=`links`)** and **declared = component.resource(value=`resource`)** and **content = component.markdown(text=\"# Actual content\", slot=\"content\")**.\nReturn *component.merge(a=`declared`, b=`content`)*.\n\n## preview\n\nPreview requires the real native renderer but no network.\n\nWe **nodes = main()**.\nReturn *web.render(nodes=`nodes`, title=\"Actual head fixture\")*.\n").unwrap(); + for backend in ["tree","bytecode"] { + let output=command(&scratch.0).args(["call",entry.to_str().unwrap(),"preview","--backend",backend, + "--effects","plugin","--fs-root",scratch.0.to_str().unwrap(),"--json"]).output().unwrap(); + assert!(output.status.success(),"{}",String::from_utf8_lossy(&output.stdout)); + let value:Value=serde_json::from_slice(&output.stdout).unwrap(); + let preview=value["result"].as_str().unwrap(); + let (head,body)=preview.split_once("</head>").unwrap(); + for expected in ["Real <literal> "value"","og:title","fonts.example.test","/theme.css"] { + assert!(head.contains(expected),"{preview}"); + } + assert!(body.contains("Actual content") && !body.contains("fonts.example") && !body.contains("slot-head"),"{preview}"); + let port=TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + let logpath=scratch.0.join(format!("head-{backend}.log")); + let log=fs::File::create(&logpath).unwrap(); + let mut server=Server(command(&scratch.0).args(["call","ext/web/web.mq.md","serve","--backend",backend, + &format!("root={}",serde_json::to_string(&scratch.0).unwrap()),&format!("port={port}"), + "--effects","plugin,fs.read,network.write","--fs-root",scratch.0.to_str().unwrap(),"--json"]) + .stdout(Stdio::from(log.try_clone().unwrap())).stderr(Stdio::from(log)).spawn().unwrap()); + let deadline=Instant::now()+Duration::from_secs(8); + let served=loop { + if let Ok(response)=get(port,"/") {break response;} + assert!(server.0.try_wait().unwrap().is_none() && Instant::now()<deadline, + "head serving failed: {}",fs::read_to_string(&logpath).unwrap()); + thread::sleep(Duration::from_millis(30)); + }; + let html=served.split_once("\r\n\r\n").unwrap().1; + assert_eq!(html,preview); + let fragment=get(port,"/_part/content").unwrap(); + assert!(fragment.contains("200 OK") && fragment.contains("Actual content") && + !fragment.contains("fonts.example") && !fragment.contains("description"),"{fragment}"); + } +} + +#[test] +fn installed_web_package_contains_the_actual_public_resource_closure() { + let scratch=Scratch::new("install"); + let installed=scratch.0.join("installed"); + let out=command(&scratch.0).env("MARQDO_EXT",&installed).env("MARQDO_EXT_SOURCE",root().join("ext")) + .args(["ext","add","web"]).output().unwrap(); + assert!(out.status.success(),"{} {}",String::from_utf8_lossy(&out.stdout),String::from_utf8_lossy(&out.stderr)); + let mut maintained=Vec::new(); + for directory in ["web","data","security","net"] {files(&root().join("ext").join(directory),&mut maintained);} + for path in maintained { + let relative=path.strip_prefix(root().join("ext")).unwrap(); + let target=installed.join(relative); + assert!(target.is_file(),"installer omitted {}",relative.display()); + assert_eq!(fs::read(&target).unwrap(),fs::read(&path).unwrap(),"installed source drift: {}",relative.display()); + } + for (file,function,args) in [ + ("web/head.mq.md","resource",r#"{"meta":[{"key":"description","value":"Installed"}]}"#), + ("web/页头.mq.md","声明",r#"{"元数据":[{"key":"description","value":"已安装"}]}"#), + ("data/表单.mq.md","引用",r#"{"标识":"article"}"#), + ("data/后台.mq.md","启用",r#"{"应用":{}}"#), + ] { + let mut child=command(&scratch.0); + child.current_dir(&scratch.0).env("MARQDO_EXT",&installed) + .args(["call",installed.join(file).to_str().unwrap(),function,"--args-json","-","--json"]) + .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); + let mut child=child.spawn().unwrap(); + child.stdin.take().unwrap().write_all(args.as_bytes()).unwrap(); + let output=child.wait_with_output().unwrap(); + assert!(output.status.success(),"installed {file}: {} {}",String::from_utf8_lossy(&output.stdout),String::from_utf8_lossy(&output.stderr)); + } +} + +#[test] +fn recursive_literary_sites_preserve_theme_detail_forms_sessions_and_custom_desk() { + fn copy_sources(from:&Path,to:&Path) { + fs::create_dir_all(to).unwrap(); + for entry in fs::read_dir(from).unwrap() { + let entry=entry.unwrap();let name=entry.file_name(); + if name.to_string_lossy().starts_with('.') || name=="data" || name=="generated" {continue;} + if entry.path().is_dir() {copy_sources(&entry.path(),&to.join(name));} + else {fs::copy(entry.path(),to.join(name)).unwrap();} + } + } + fn request(port:u16,method:&str,path:&str,body:&str,cookie:&str)->String { + let mut stream=TcpStream::connect(("127.0.0.1",port)).unwrap(); + stream.set_read_timeout(Some(Duration::from_secs(3))).unwrap(); + write!(stream,"{method} {path} HTTP/1.0\r\nHost: localhost\r\nConnection: close\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: {}\r\nCookie: {cookie}\r\n\r\n{body}",body.len()).unwrap(); + let mut response=String::new();stream.read_to_string(&mut response).unwrap();response + } + fn cookie(response:&str)->String { + response.lines().find_map(|line|line.split_once(':').filter(|(key,_)|key.eq_ignore_ascii_case("set-cookie")) + .map(|(_,value)|value.trim().split(';').next().unwrap().to_string())).unwrap() + } + for (site,required_copy) in [("web-site","Title is required"),("web-site-zh","标题不能为空")] { + for backend in ["tree","bytecode"] { + let scratch=Scratch::new(&format!("literary-{site}-{backend}")); + copy_sources(&root().join("examples").join(site),&scratch.0); + // Exercise the actual executable preservation tool on an owned site copy. + let output=command(&scratch.0).args(["call",scratch.0.join("verify.mq.md").to_str().unwrap(),"theme_values", + "--backend",backend,"--effects","plugin,fs.read","--fs-root",scratch.0.to_str().unwrap(),"--json"]).output().unwrap(); + assert!(output.status.success(),"{}",String::from_utf8_lossy(&output.stdout)); + let checked:Value=serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(checked["result"]["ok"],true,"{checked}"); + assert_eq!(checked["result"]["value"]["preserved_rows"],412); + assert_eq!(checked["result"]["value"]["original_sha256"],"5889305c79210754b36a1ec858d57361f73a23e983f6a091568f12584fb8b8c9"); + let port=TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + let logpath=scratch.0.join("server.log");let log=fs::File::create(&logpath).unwrap(); + let mut server=Server(command(&scratch.0).args(["call",&format!("examples/{site}/index.mq.md"),"serve","--backend",backend, + &format!("root={}",serde_json::to_string(&scratch.0).unwrap()),&format!("port={port}"), + "--effects","plugin,fs.write,network.write","--fs-root",scratch.0.to_str().unwrap(),"--json"]) + .stdout(Stdio::from(log.try_clone().unwrap())).stderr(Stdio::from(log)).spawn().unwrap()); + let deadline=Instant::now()+Duration::from_secs(10); + let home=loop { + if let Ok(body)=get(port,"/") {break body;} + assert!(server.0.try_wait().unwrap().is_none() && Instant::now()<deadline, + "{site} [{backend}] startup: {}",fs::read_to_string(&logpath).unwrap()); + thread::sleep(Duration::from_millis(30)); + }; + assert!(home.contains("200 OK"),"{home}"); + assert_eq!(home.matches("<article class=\"card\">").count(),8,"{home}"); + let (head,body)=home.split_once("</head>").unwrap(); + assert!(head.contains("og:type") && head.contains("fonts.googleapis.com") && head.contains("/static/generated/theme.css"),"{home}"); + assert!(!body.contains("document-head") && body.contains("site-layout has-sidebar"),"{body}"); + assert!(body.contains("href=\"/login\"") && !body.contains("href=\"/admin\""),"{body}"); + let about=get(port,"/about").unwrap(); + assert!(about.contains("200 OK") && !about.contains("property=\"og:type\""),"{about}"); + let css=get(port,"/static/generated/theme.css").unwrap(); + for expected in ["--ink: #0a0809","--gold: #d4af37","@keyframes particleDrift","(max-width: 860px)",".site-layout.has-sidebar",".main-intro h1"] { + assert!(css.contains(expected),"missing {expected}: {css}"); + } + let denied=get(port,"/admin").unwrap(); + assert!(denied.contains("303 See Other") && denied.contains("/login?next="),"{denied}"); + let new=get(port,"/new").unwrap();let guest=cookie(&new); + let token=regex::Regex::new(r#"name="_csrf" value="([^"]+)""#).unwrap().captures(&new).unwrap()[1].to_string(); + let invalid=request(port,"POST","/_form/article",&format!("_csrf={token}&title=&slug="),&guest); + assert!(invalid.contains(required_copy) && invalid.contains(&format!("value=\"{token}\"")),"{invalid}"); + let created=request(port,"POST","/_form/article",&format!("_csrf={token}&title=After+startup&slug=current&summary=Short+summary&body=%23%23+Full+body%0A%0AMarkdown+content"),&guest); + assert!(created.contains("303 See Other"),"{created}"); + let current=get(port,"/").unwrap(); + assert_eq!(current.matches("<article class=\"card\">").count(),9,"{current}"); + assert!(current.contains("After startup") && current.contains("Short summary") && !current.contains("Full body"),"{current}"); + let detail=get(port,"/post/current?slug=wrong").unwrap(); + assert!(detail.contains("200 OK") && detail.contains("Full body</h2>") && detail.contains("Markdown content") && !detail.contains("Short summary"),"{detail}"); + let fragment=get(port,"/_part/articles").unwrap(); + assert!(fragment.contains("After startup") && !fragment.contains("<!DOCTYPE") && !fragment.contains("fonts.googleapis.com"),"{fragment}"); + let login=request(port,"POST","/login",&format!("_csrf={token}&username=admin&password=demo"),&guest); + assert!(login.contains("303 See Other"),"{login}");let signed=cookie(&login); + let desk=request(port,"GET","/admin","",&signed); + assert!(desk.contains("200 OK") && desk.contains("is-desk") && desk.contains("After startup") && + desk.contains("action=\"/_form/article\"") && !desk.contains("<aside"),"{desk}"); + let signed_home=request(port,"GET","/","",&signed); + assert!(signed_home.contains("href=\"/admin\"") && !signed_home.contains("href=\"/login\""),"{signed_home}"); + let logout=request(port,"GET","/admin/logout","",&signed);assert!(logout.contains("303 See Other"),"{logout}"); + let after_logout=request(port,"GET","/admin","",&signed); + assert!(after_logout.contains("303 See Other") && after_logout.contains("/login"),"{after_logout}"); + } + } +} + +#[test] +fn ordinary_blog_is_callable_and_resolves_default_sqlite_under_its_granted_site() { + for backend in ["tree","bytecode"] { + let scratch=Scratch::new(&format!("blog-{backend}")); + for directory in ["pages","api","db","public"] {fs::create_dir_all(scratch.0.join(directory)).unwrap();} + for file in ["index.mq.md","pages/about.mq.md","pages/post.mq.md","api/ping.mq.md","api/echo.mq.md","db/posts.tables.md"] { + fs::copy(root().join("examples/marqdo-blog").join(file),scratch.0.join(file)).unwrap(); + } + let port=TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + let logpath=scratch.0.join("server.log");let log=fs::File::create(&logpath).unwrap(); + let mut server=Server(command(&scratch.0).args(["call","examples/marqdo-blog/serve.mq.md","main", + "--backend",backend,&format!("root={}",serde_json::to_string(&scratch.0).unwrap()),&format!("port={port}"), + "--effects","plugin,fs.write,network.write","--fs-root",scratch.0.to_str().unwrap(),"--json"]) + .stdout(Stdio::from(log.try_clone().unwrap())).stderr(Stdio::from(log)).spawn().unwrap()); + let deadline=Instant::now()+Duration::from_secs(8); + let home=loop { + if let Ok(response)=get(port,"/") {break response;} + assert!(server.0.try_wait().unwrap().is_none() && Instant::now()<deadline,"blog startup: {}",fs::read_to_string(&logpath).unwrap()); + thread::sleep(Duration::from_millis(30)); + }; + assert!(home.contains("200 OK") && home.contains("Hello Marqdo") && home.contains("Artifact Web"),"{home}"); + assert!(scratch.0.join("data/blog.db").is_file(),"default database escaped the granted root"); + let detail=get(port,"/post/hello").unwrap(); + assert!(detail.contains("200 OK") && detail.contains("executable documents"),"{detail}"); + for path in ["/about","/api/ping"] {let response=get(port,path).unwrap();assert!(response.contains("200 OK"),"{response}");} + } +} + +#[test] +fn browser_effects_keep_typed_children_duplicate_identity_and_observed_results() { + let source = fs::read_to_string(root().join("examples/browser-app/static/app.mq.md")).unwrap(); + let (mut session, boot) = marqdo::browser_session::BrowserSession::boot(&source).unwrap(); + let boot = browser_json(&boot); + assert!(boot.get("navigate").is_none()); + let literal = "A <tag> \"quoted\" & data\nsecond line"; + for id in ["1", "2"] { + let added = browser_json(&session.call("add", &serde_json::json!({"value":literal}).to_string()).unwrap()); + let rows = added["render_list"]["#items"]["items"].as_array().unwrap(); + let last = rows.last().unwrap(); + assert_eq!(last["children"][0]["text"], literal); + assert_eq!(last["children"][1]["attrs"]["data-id"], id); + assert!(last.get("html").is_none()); + } + let remaining = browser_json(&session.call("on_item", r#"{"data_id":"1"}"#).unwrap()); + let rows = remaining["render_list"]["#items"]["items"].as_array().unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0]["children"][1]["attrs"]["data-id"], "2"); + assert_eq!(session.call("on_item", r#"{"data_id":"missing"}"#).unwrap(), marqdo::value::Value::None); + let third = browser_json(&session.call("add", r#"{"value":"third"}"#).unwrap()); + assert_eq!(third["render_list"]["#items"]["items"][1]["children"][1]["attrs"]["data-id"], "3"); + let about = browser_json(&session.call("go_about", "{}").unwrap()); + assert_eq!(about["navigate"]["url"], "/about"); + assert_eq!(about["set_attr"]["#panel-about"]["hidden"], false); + let pop = browser_json(&session.call("on_pop", r#"{"path":"/net?from=history"}"#).unwrap()); + assert!(pop.get("navigate").is_none()); + assert_eq!(pop["set_text"]["#path"], "path: /net"); + assert_eq!(pop["set_attr"]["#panel-net"]["hidden"], false); + let failed = browser_json(&session.call("on_draft", r#"{"ok":false,"found":false}"#).unwrap()); + assert_eq!(failed["set_text"]["#log"], "draft read failed"); + assert!(failed.get("set_value").is_none()); + let empty = browser_json(&session.call("on_draft", r#"{"ok":true,"found":true,"value":""}"#).unwrap()); + assert_eq!(empty["set_value"]["#draft"], ""); + let save = browser_json(&session.call("save_draft", r#"{"value":"saved draft"}"#).unwrap()); + assert_eq!(save["storage"]["then"], "on_saved"); + assert!(save.get("set_text").is_none(), "request was prematurely described as completion"); + let observed = serde_json::json!({"ok":true,"results":[ + {"ok":true,"status":200,"body":"actual-success"}, + {"ok":false,"status":503,"body":"actual-failure"} + ]}); + let batch = browser_json(&session.call("on_fetch_all", &observed.to_string()).unwrap()); + let output = batch["set_text"]["#net-out"].as_str().unwrap(); + assert!(output.contains("actual-success") && output.contains("503") && output.contains("actual-failure"), "{output}"); + let copy = browser_json(&session.call("copy_log", "{}").unwrap()); + assert_eq!(copy["clipboard"]["text"], format!("{literal}\nthird")); + assert_eq!(session.call("on_tick", r#"{"ok":false,"id":"tick"}"#).unwrap(), marqdo::value::Value::None); + let tick = browser_json(&session.call("on_tick", r#"{"ok":true,"id":"tick"}"#).unwrap()); + assert_eq!(tick["set_text"]["#tick"], "1"); +}