From 416914a3468bb55fa05b9d7b1847bf4e42e9f9ae Mon Sep 17 00:00:00 2001 From: cflmy Date: Sat, 29 Aug 2026 11:47:22 +0800 Subject: [PATCH] =?UTF-8?q?release:=20v0.3.1=20=E2=80=94=20W8=20favicon/he?= =?UTF-8?q?ad/images=20+=20entry=5Fdir=20fix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ship site icons, head asset tables, and image assembly; absolutize entry_dir for relative entry scripts so sqlite paths no longer nest. Co-authored-by: Cursor --- .cursor/skills/marqdo/SKILL.md | 8 +- .github/workflows/release.yml | 8 +- CHANGELOG.md | 18 + Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 12 +- doc/README.md | 1 + doc/design/ext-web.md | 6 +- doc/design/web-assets-and-images.md | 325 ++++++++++++++ doc/design/web-net-capabilities.md | 4 + examples/marqdo-blog/README.md | 6 +- examples/marqdo-blog/index.mq.md | 22 + examples/marqdo-blog/public/favicon.png | 2 + examples/marqdo-blog/public/favicon.svg | 1 + examples/marqdo-blog/public/logo.svg | 1 + examples/marqdo-blog/smoke.sh | 4 + ext/web/web.mq.md | 48 ++- ext/web/网页.mq.md | 43 +- plugins/web/src/assets.rs | 490 ++++++++++++++++++++++ plugins/web/src/http.rs | 90 +++- plugins/web/src/lib.rs | 153 +++++++ plugins/web/src/render.rs | 26 ++ skills/marqdo/SKILL.md | 8 +- src/host/plugin.rs | 26 +- tests/ext/web-assets-live-server.mq.md | 36 ++ tests/ext/web-assets-smoke.mq.md | 92 ++++ tests/ext/web-fixtures/public/favicon.png | 2 + tests/ext/web-fixtures/public/favicon.svg | 1 + tests/gold.rs | 96 +++++ 29 files changed, 1497 insertions(+), 36 deletions(-) create mode 100644 doc/design/web-assets-and-images.md create mode 100644 examples/marqdo-blog/public/favicon.png create mode 100644 examples/marqdo-blog/public/favicon.svg create mode 100644 examples/marqdo-blog/public/logo.svg create mode 100644 plugins/web/src/assets.rs create mode 100644 tests/ext/web-assets-live-server.mq.md create mode 100644 tests/ext/web-assets-smoke.mq.md create mode 100644 tests/ext/web-fixtures/public/favicon.png create mode 100644 tests/ext/web-fixtures/public/favicon.svg diff --git a/.cursor/skills/marqdo/SKILL.md b/.cursor/skills/marqdo/SKILL.md index 095fea9..6f03858 100644 --- a/.cursor/skills/marqdo/SKILL.md +++ b/.cursor/skills/marqdo/SKILL.md @@ -154,6 +154,7 @@ Import **one language file** — never mix EN/ZH API names in the same `.mq.md`: - Authors use **GFM tables + `#` classes** — no `json.parse` / `json.set` glue, no hand-built part JSON. - Table cells stay **literal strings**; path text like `` `posts`.`title` `` is resolved by web classes. +- **Quote path/MIME cells** that contain `/` (T5 cell expressions treat bare `/` as division): `"/static/logo.svg"`, `"image/png"`. - **`ext/**` never calls `host_*`** — hot path is native `plugins/web` ABI. - HTTPS: terminate at reverse proxy; set `cookie_secure=True` on auth (no in-process TLS). @@ -164,17 +165,18 @@ index.mq.md # entry + home page table + listen pages/ # sub-pages components/ # reusable |属性|值|样式| tables styles/ # CSS modules +public/ # static + favicon.ico|png|svg db/ # schema + open/init data/ # sqlite runtime (gitignore) ``` **Core objects (EN / ZH):** `# page`/`页面`, `# style`/`样式`, `# db`/`数据库`, `# form`/`表单`, `# app`/`应用`, `# auth`/`鉴权`, `# cache`/`缓存`, `# storage`/`存储`. -**Typical flow:** `db.init` → `page.compose_components` + `page.compose_main` → `page.render` → `app` with `route` / `static` / `configure` / `listen`. +**Typical flow:** `db.init` → `page.compose_components` + `page.compose_main` → `page.head` / `page.images` / `page.meta` → `app` with `route` / `static` / `icons` / `configure` / `listen`. -**Shipped surface (W0–W7 + P3):** middleware + JSON API (`app.configure`); transactions, pagination, FTS search (`db.migrate`, `db.fts`, `db.search`); security (argon2, CSRF, SQLite sessions, login rate limit); SEO / RSS / Markdown (`page.meta`, `route_rss`, `lib/net.markdown_parse`); upload / download / gallery; sitemap / robots / error pages / redirects; RBAC (`app.gate`, user `role`); audit timestamps + FK in `db.init`; ETag on downloads. +**Shipped surface (W0–W7 + P3 + W8):** middleware + JSON API (`app.configure`); transactions, pagination, FTS search (`db.migrate`, `db.fts`, `db.search`); security (argon2, CSRF, SQLite sessions, login rate limit); SEO / RSS / Markdown (`page.meta`, `route_rss`, `lib/net.markdown_parse`); upload / download / gallery; sitemap / robots / error pages / redirects; RBAC (`app.gate`, user `role`); audit timestamps + FK in `db.init`; ETag on downloads; **W8** site icons (`app.icons` → `/favicon.ico`), head resource tables (`page.head`), image assembly (`make_images` / `page.images`). -Design: [ext-web.md](../../doc/design/ext-web.md) · capability matrix: [web-net-capabilities.md](../../doc/design/web-net-capabilities.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/). +Design: [ext-web.md](../../doc/design/ext-web.md) · assets: [web-assets-and-images.md](../../doc/design/web-assets-and-images.md) · capability matrix: [web-net-capabilities.md](../../doc/design/web-net-capabilities.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/). Web patterns: [examples.md](examples.md) §13 · API index: [reference.md](reference.md). diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index fee591c..bd6a998 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -92,10 +92,10 @@ jobs: body: | ## Marqdo ${{ github.ref_name }} - ### Highlights — v0.3 - - **`ext/web`**: W0–W7 + P3 complete (sessions, cache, upload, WebSocket, style assembly); see marqdo-blog - - **`ext/quantum`**: Q7 linalg + Q8 themed SVG viz - - **`ext/agent`**: A1–A4 (OKF reuse, events, context budget, RAG/MCP fixtures) + ### Highlights — v0.3.1 + - **W8**: favicon / head assets / image assembly (`app.icons`, `page.head`, `make_images`) + - Fix: absolute `entry_dir` for relative entry scripts (no nested `tests/ext/tests/ext`) + - **`ext/web`**: W0–W7 + P3 + W8; **`ext/quantum`** Q7/Q8; **`ext/agent`** A1–A4 - Install: `marqdo ext list` / `marqdo ext add llm|agent|web|quantum` - Native plugins: `cargo build --release -p marqdo_plugin_*` then `ext add` - Details: [CHANGELOG](https://github.com/cflmy/marqdo/blob/main/CHANGELOG.md) · [README](https://github.com/cflmy/marqdo/blob/main/README.md) diff --git a/CHANGELOG.md b/CHANGELOG.md index db2ed06..a0a3265 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,24 @@ ## Unreleased +## v0.3.1 — 2026-08-29 + +### Highlights + +**W8 站点资源**:favicon / Head 资源表 / 图片装配一次补齐;并修复相对入口路径下 `entry_dir` 双重拼接导致的嵌套目录问题。 + +```bash +git checkout v0.3.1 +cargo build --release +marqdo ext add web # 改插件后请重新 add +``` + +### Added +- **`ext/web` W8(站点图标 / Head / 图片装配)** ([web-assets-and-images.md](doc/design/web-assets-and-images.md)):`app.icons` / `应用.图标` 挂 `GET /favicon.ico`;`page.head` / `头装配`;`make_images` / `图片装配`;`meta` 认 `icon`/`favicon`/`apple-touch-icon`;`static` 约定 `favicon.*`;金样 `web-assets-smoke` / `web-assets-live`;[marqdo-blog](examples/marqdo-blog/) 接入。 + +### Fixed +- **`host_query("entry_dir")`**:相对入口脚本(如 `tests/ext/….mq.md`)时对进程 cwd 绝对化,避免与 `for_run` 已设的脚本目录 cwd 再次拼接成 `tests/ext/tests/ext/…`。 + ## v0.3.0 — 2026-08-29 ### Highlights diff --git a/Cargo.lock b/Cargo.lock index dfdaea9..6c7382e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1018,7 +1018,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" [[package]] name = "marqdo" -version = "0.3.0" +version = "0.3.1" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index 1ca62de..3a9e205 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "marqdo" -version = "0.3.0" +version = "0.3.1" edition = "2021" license = "Apache-2.0" description = "Marqdo — Markdown markers as an interpreted programming language" diff --git a/README.md b/README.md index 75dd5b6..98b3dfe 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,7 @@ marqdo catalog public -o .marqdo --- -## 现状(v0.3.0) +## 现状(v0.3.1) - 映射与解释器:Phase I 树遍历 + 字节码后端可用;金样例在 `tests/` - **对象**:`#` = 类型/构造,`##`+ = 函数/方法;见 [objects.md](doc/design/objects.md) @@ -109,7 +109,7 @@ marqdo catalog public -o .marqdo - **`marqdo version --check`**:与 GitHub 最新 release 对比 - 标准库:**内置于二进制**(v0.1.2+);磁盘 `lib/` 或 `MARQDO_LIB` 可覆盖。模块含文本、文件、系统、时间、JSON、网络、数学、外联、插件、**自写回**、**子任务** - **官方扩展库 `ext/`**(**非** stdlib,本版收口): - - **`web`**:W0–W7 + P3 完结(会话 / 缓存 / 上传 / WebSocket / 样式装配等);示例 [marqdo-blog](examples/marqdo-blog/);生产路径见 [web-asgi-servers-and-marqdo.md](doc/design/web-asgi-servers-and-marqdo.md)(反向代理 → 嵌入式 `listen`,非 Daphne/Uvicorn) + - **`web`**:W0–W7 + P3 + **W8**(favicon / Head 资源 / 图片装配,见 [web-assets-and-images.md](doc/design/web-assets-and-images.md));示例 [marqdo-blog](examples/marqdo-blog/);生产路径见 [web-asgi-servers-and-marqdo.md](doc/design/web-asgi-servers-and-marqdo.md)(反向代理 → 嵌入式 `listen`,非 Daphne/Uvicorn) - **`quantum`**:Q0–Q7 + Q8a/b 主题 SVG;示例 [quantum-entanglement](examples/quantum-entanglement/) - **`agent`**:A1–A4(OKF 复用、过程事件、上下文预算、RAG/MCP fixture);下一波缺口 [agent-framework-gaps-after-a4.md](doc/research/agent-framework-gaps-after-a4.md) - **`llm`**:OpenAI 兼容对话 @@ -119,12 +119,12 @@ marqdo catalog public -o .marqdo - **VS Code 扩展**:分支 **`vscode-extension`**(`main` 不跟踪源码;见 [vscode-extension-commit.md](doc/design/vscode-extension-commit.md));Release 附带 `.vsix` - 选型:[ADR 0001 — Rust](doc/adr/0001-implementation-language.md) -### 如何使用最新 Marqdo(v0.3.0) +### 如何使用最新 Marqdo(v0.3.1) ```bash # 1) 源码安装(跟 tag 或 main) git clone https://github.com/cflmy/marqdo.git && cd marqdo -git checkout v0.3.0 # 或留在 main +git checkout v0.3.1 # 或留在 main cargo build --release export PATH="$PWD/target/release:$PATH" marqdo version @@ -146,10 +146,10 @@ marqdo ext add llm # 或:大模型 # 4) 动态站示例(扩展装好后) marqdo run examples/marqdo-blog/index.mq.md -# 浏览器打开终端打印的 listen 地址 +# 浏览器打开终端打印的 listen 地址;/favicon.ico 与 logo 装配见 W8 # 5) Windows:也可从 GitHub Releases 下载 exe / zip / vsix -# https://github.com/cflmy/marqdo/releases/tag/v0.3.0 +# https://github.com/cflmy/marqdo/releases/tag/v0.3.1 ``` 开发期也可用 `cargo run -- …` 代替已安装的 `marqdo`: diff --git a/doc/README.md b/doc/README.md index f6a1ac4..d9897f7 100644 --- a/doc/README.md +++ b/doc/README.md @@ -40,6 +40,7 @@ | [design/ext-agent-plan.md](design/ext-agent-plan.md) | **`## 多步` / `## plan` 锁定设计**(工作簿文件、subtask 执行、修订循环、`step` 默认写回) | | [design/ext-cli.md](design/ext-cli.md) | **`marqdo ext list/add/remove` 官方扩展安装器** | | [design/ext-web.md](design/ext-web.md) | **官方扩展 `ext/web`(页面/库表/绑定/后台;ABI + CLI;设计锁定)** | +| [design/web-assets-and-images.md](design/web-assets-and-images.md) | **W8:favicon / Head 资源表 / 图片装配**(一次补齐) | | [design/web-asgi-servers-and-marqdo.md](design/web-asgi-servers-and-marqdo.md) | **Daphne/Uvicorn 等 vs Marqdo**:不能直接托管;反代 + axum `listen` | | [design/call-arguments.md](design/call-arguments.md) | **调用:具名 + 位置实参** | | [design/examples-and-tests.md](design/examples-and-tests.md) | **tests/ 金样例目录布局** | diff --git a/doc/design/ext-web.md b/doc/design/ext-web.md index 7b319b0..80404af 100644 --- a/doc/design/ext-web.md +++ b/doc/design/ext-web.md @@ -2,9 +2,9 @@ | | | |---|---| -| 状态 | **Accepted · W0–W7 + P3 完结**(SQLite/Postgres 作者面:页面装配 / db CRUD+`where` / form / 嵌入主区 / `app.route` / 路由 `/_part` / admin UI / RBAC / 上传相册 / SEO·RSS·sitemap;Postgres 等见 §9) | -| 日期 | 2026-08-11 | -| 相关 | [markdown-mapping.md](markdown-mapping.md) · [module-namespace.md](module-namespace.md) · [objects.md](objects.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [stdlib-i18n.md](stdlib-i18n.md) | +| 状态 | **Accepted · W0–W7 + P3 + W8(站点图标/Head/图片装配)完结**(SQLite/Postgres 作者面:页面装配 / db CRUD+`where` / form / 嵌入主区 / `app.route` / 路由 `/_part` / admin UI / RBAC / 上传相册 / SEO·RSS·sitemap / **favicon·头资源·图片装配**;Postgres 等见 §9) | +| 日期 | 2026-08-11(W8:2026-08-29) | +| 相关 | [markdown-mapping.md](markdown-mapping.md) · [module-namespace.md](module-namespace.md) · [objects.md](objects.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [stdlib-i18n.md](stdlib-i18n.md) · [web-assets-and-images.md](web-assets-and-images.md) | | 安装(目标) | `marqdo ext add web`(中英:`web` / `网页`) | | 本文目的 | 锁定**作者面**与**类 API**;指导实现 | diff --git a/doc/design/web-assets-and-images.md b/doc/design/web-assets-and-images.md new file mode 100644 index 0000000..21368f0 --- /dev/null +++ b/doc/design/web-assets-and-images.md @@ -0,0 +1,325 @@ +# `ext/web` — 站点图标、Head 资源与图片装配 + +| | | +|---|---| +| 状态 | **Accepted · W8 已落地** | +| 日期 | 2026-08-29 | +| 父设计 | [ext-web.md](ext-web.md) · [web-net-capabilities.md](web-net-capabilities.md) | +| 相关 | [web-asgi-servers-and-marqdo.md](web-asgi-servers-and-marqdo.md)(静态仍由嵌入式 `listen` 提供) | +| 硬约束 | `ext/**` 不调 `host_*`;作者面禁止袋胶水;中英库文件分文件 | + +--- + +## 0. 一句话 + +把 **浏览器默认图标(`/favicon.ico`)**、**`` 里的 link/script**、**正文/品牌图片** 都做成与 `样式装配` 同构的能力:**GFM 表即数据,装配即函数**;由 `plugins/web` ABI 渲染/挂路由,`ext/web` 只做 L1 包装。 + +--- + +## 1. 动机与现状缺口 + +### 1.1 已有 + +| 能力 | 说明 | +|------|------| +| `app.static` / `应用.静态` | 目录挂到 `/static`(或自定义 mount) | +| `page.meta` / `页面.元数据` | `title` / `description` / `canonical` / `og:*` → `` | +| `app.upload` + `gallery` | **运行时**用户上传媒体,不是站点品牌资源 | + +### 1.2 缺口(本设计一次补齐) + +| # | 缺口 | 影响 | +|---|------|------| +| G1 | 浏览器默认请求 **`GET /favicon.ico`**,静态挂在 `/static` 时根路径 404 | 标签页无图标 | +| G2 | `page.meta` 未知键一律变成 ``,**不能**正确写出 `` | 作者写 `icon` 无效 | +| G3 | 无 **Head 资源表**(stylesheet / preload / script / manifest / apple-touch-icon) | 只能手写进 `intro` 或改插件 | +| G4 | 无 **图片装配**(表 → `
`/``),与样式装配不对齐 | logo / 头图 / 插图只能拼 HTML 字符串 | +| G5 | 无 **站点级图标表 → 根路径文件服务 + 默认 head 注入** | 多页站点要在每页重复声明 | + +--- + +## 2. 设计原则 + +1. **配置即数据、装配即函数** — 与 `web_style` / `应用.装配` 同构。 +2. **应用层管「可达性」**(磁盘文件 → HTTP 路径);**页面层管「声明」**(`` / 正文 HTML)。 +3. **站点图标可自动注入所有页面**,页面仍可用 `头装配` / `元数据` 覆盖或追加。 +4. **约定优于配置**:若已 `静态` 且目录内存在 `favicon.ico`(或 `favicon.png` / `favicon.svg`),未显式配置时仍挂 `GET /favicon.ico`(及对应静态 URL 由作者自选)。 +5. **中英分文件**:`web.mq.md` ↔ `网页.mq.md`,禁止混排。 + +--- + +## 3. 作者面 API(一次交付全集) + +### 3.1 模块级装配(返回字符串,可与主题拼装) + +| EN | ZH | FFI | 输入 | 输出 | +|----|----|-----|------|------| +| `make_style`(已有) | `样式装配` | `web_style` | 样式表 | CSS 文本 | +| **`make_images`** | **`图片装配`** | **`web_images`** | 图片表 | HTML 片段 | +| **`make_head`** | **`头资源装配`** | **`web_head`** | Head 表 | 供调试/预览的 HTML 片段(可选;页面方法主路径不强制调用) | + +### 3.2 `# page` / `# 页面` + +| EN | ZH | FFI | 作用 | +|----|----|-----|------| +| `meta`(增强) | `元数据` | `web_page_meta` | 认 `icon` / `favicon` / `apple-touch-icon` → ``,不再误写成 `` | +| **`head`** | **`头装配`** | **`web_page_head`** | 挂 Head 资源表到 `page.head`,渲染时写入 `` | +| **`images`** | **`图片装配`**(方法) | **`web_page_images`** | 图片表 → HTML,写入 `page.images_html`,渲染进主区 | + +### 3.3 `# app` / `# 应用` + +| EN | ZH | FFI | 作用 | +|----|----|-----|------| +| **`icons`** | **`图标`** | **`web_app_icons`** | 站点图标表:根路径文件服务 + 默认 head 链接注入全站 | +| `static`(增强) | `静态`(增强) | `web_app_static` | 约定:目录内 `favicon.ico|png|svg` → 自动注册 `/favicon.ico`(可被 `icons` 显式行覆盖) | + +--- + +## 4. 表形约定 + +单元格仍为**字面量**;列名中英等价(任选一套,勿混列名语义)。 + +### 4.1 站点图标表(`app.icons` / `应用.图标`) + +| 列(ZH) | 列(EN) | 必填 | 说明 | +|----------|----------|------|------| +| `路径` | `path` | ✅* | 磁盘路径(相对进程 cwd 或入口目录解析规则与 `static` 一致) | +| `关系` | `rel` | | 默认 `icon`;常用 `icon` / `apple-touch-icon` / `mask-icon` | +| `类型` | `type` | | 缺省按扩展名推断 | +| `尺寸` | `sizes` | | 如 `16x16`、`180x180`、`any` | +| `地址` | `url` / `href` | | 对外 URL。缺省:首个 `rel=icon` 且扩展名为 `.ico` → `/favicon.ico`;否则 `/icons/{文件名}` | + +\* 若仅提供 `地址` 指向已由 `静态` 提供的 URL、不落盘服务,则 `路径` 可空(只注入 head,不挂新路由)。 + +**Listen 行为** + +1. 规范化为数组 `{path, rel, type, sizes, url}`。 +2. 对每个非空 `path`:注册 **`GET {url}`**,读文件返回,`Content-Type` = `type` 或推断;`Cache-Control` 可用 `public, max-age=86400`。 +3. 若存在至少一个 `rel` 含 `icon` 的行,保证浏览器默认路径:若没有任何 `url=/favicon.ico`,则把**第一行 icon** 额外挂到 `/favicon.ico`(同一文件,可选)。 +4. 将图标行转为默认 head 链接列表,存入 `app.site_head`,listen 时写入 `AppState`,渲染任意页面前 **merge**(页面自有 `head` / meta 图标 **追加且可同 href 去重**)。 + +**`static` 约定自动图标** + +在 `listen` 解析完 `static_dir` 后:若 `app.icons` 为空,且 `{static_dir}/favicon.ico` 或 `.png` / `.svg` 存在,则等价注册: + +```text +path = {static_dir}/favicon.{ico|png|svg} +rel = icon +url = /favicon.ico +``` + +(文件仍可通过 `/static/favicon.*` 访问;根路径额外可达。) + +### 4.2 Head 资源表(`page.head` / `页面.头装配`) + +| 列(ZH) | 列(EN) | 说明 | +|----------|----------|------| +| `关系` | `rel` | `icon` / `apple-touch-icon` / `stylesheet` / `preload` / `modulepreload` / `manifest` / `canonical` / **`script`** / **`module`** | +| `地址` | `href` / `src` / `url` | 资源 URL | +| `类型` | `type` | MIME 或 `module` | +| `尺寸` | `sizes` | icons | +| `媒体` | `media` | CSS media | +| `作为` | `as` | preload `as` | +| `跨域` | `crossorigin` | 空 / `anonymous` / `use-credentials` | + +**渲染规则** + +| `rel` | 输出 | +|-------|------| +| `script` | ``(`type` 非空则写出) | +| `module` | `` | +| 其他 | ``(按列附加 `type`/`sizes`/`media`/`as`/`crossorigin`) | + +空 `地址` 的行跳过。 + +### 4.3 元数据表增强(`page.meta`) + +| 键 | 行为 | +|----|------| +| `title` / `description` / `canonical` / `og:*` | **不变** | +| **`icon`** / **`favicon`** | ``(可选若值含空格后 MIME:本切片仅 href) | +| **`apple-touch-icon`** | `` | +| 其他 | 仍为 `` | + +### 4.4 图片表(`make_images` / `page.images`) + +| 列(ZH) | 列(EN) | 说明 | +|----------|----------|------| +| `源` | `src` | 必填,图片 URL | +| `替代` | `alt` | `alt` 文本,默认空 | +| `标题` | `title` | `title` 属性 | +| `类` | `class` | 加在 `
`(无 figure 时加在 ``) | +| `链接` | `href` / `link` | 非空则用 `` 包裹 `` | +| `宽度` | `width` | 像素,可选 | +| `高度` | `height` | 像素,可选 | +| `加载` | `loading` | `lazy` / `eager`;默认 `lazy`(首行可写 `eager`) | +| `图注` | `caption` | 非空则 `
` | +| `槽` | `slot` | 预留:`main`(默认)。本切片只支持主区 | + +**输出 HTML(多行)** + +```html +
+
…
+ … +
+``` + +单行且无图注/类时仍包在 `div.mq-images` 内,保证主题可统一选中。 + +**`page.images`**:调用 `web_images` 逻辑,结果写入 `page.images_html`。 + +**渲染位置**:`render_page` 主区中,在 `intro` **之前**插入 `images_html`(品牌图/头图常见需求);`render_fragment` 的 main 槽同样插入。 + +路径与 MIME 单元格若含 `/`,须写成引号字面量(T5 单元格表达式会把裸 `/` 当除法):`"/favicon.ico"`、`"image/png"`。 + +--- + +## 5. 插件 / 状态形状 + +### 5.1 页面对象新增字段 + +```json +{ + "meta": { "title": "…", "icon": "/favicon.ico" }, + "head": [ + { "rel": "stylesheet", "href": "/static/print.css", "media": "print" } + ], + "images_html": "
…
" +} +``` + +### 5.2 应用对象新增字段 + +```json +{ + "static_dir": "public", + "static_mount": "/static", + "icons": [ + { + "path": "public/favicon.ico", + "rel": "icon", + "type": "image/x-icon", + "sizes": "32x32", + "url": "/favicon.ico" + } + ], + "site_head": [ + { "rel": "icon", "href": "/favicon.ico", "type": "image/x-icon", "sizes": "32x32" } + ] +} +``` + +`site_head` 由 `web_app_icons`(及 static 约定)生成,作者不必手写。 + +### 5.3 `AppState` / `listen` 签名 + +新增: + +- `icon_routes: Vec` +- `site_head: Vec` + +在 `home` / 动态与静态 `route` 渲染前:`merge_site_head(&mut page, &state.site_head)`。 + +--- + +## 6. MIME 推断 + +| 扩展名 | Content-Type | +|--------|----------------| +| `.ico` | `image/x-icon` | +| `.png` | `image/png` | +| `.svg` | `image/svg+xml` | +| `.webp` | `image/webp` | +| `.jpg` / `.jpeg` | `image/jpeg` | +| `.gif` | `image/gif` | +| `.webmanifest` / `.json` | `application/manifest+json` | +| 其他 | `application/octet-stream` | + +--- + +## 7. 作者示例(中文) + +```markdown +## 站点图标 + +|路径|关系|类型|尺寸|地址| +|---|---|---|---|---| +|public/favicon.ico|icon|image/x-icon|32x32|/favicon.ico| +|public/apple-touch-icon.png|apple-touch-icon|image/png|180x180|/static/apple-touch-icon.png| + +## 头资源 + +|关系|地址|类型|媒体| +|---|---|---|---| +|icon|/favicon.ico|image/x-icon| +|stylesheet|/static/print.css|text/css|print| +|script|/static/live.js|| + +## 品牌图 + +|源|替代|类|链接|宽度|加载| +|---|---|---|---|---|---| +|/static/logo.svg|Marqdo|brand-logo|/|48|eager| + +# main + +*page = > 网页.页面 标题="博客"* +*page = > page.头装配 表=`头资源`* +*page = > page.图片装配 表=`品牌图`* +*page = > page.元数据 元数据=`seo表`* + +*app = > 网页.应用 页面=`page` …* +*app = > app.静态 目录="public" 挂载="/static"* +*app = > app.图标 表=`站点图标`* +> app.监听 +``` + +英文对称:`web.page` / `head` / `images` / `meta`;`web.app` / `static` / `icons`;模块 `web.make_images`。 + +--- + +## 8. 实现清单(本切片必须全部完成) + +| # | 项 | 归属 | +|---|----|------| +| I1 | `assets.rs`:表解析、MIME、`web_images` HTML、`web_head` HTML、图标规范化 | `plugins/web` | +| I2 | `web_page_head` / `web_page_images` / `web_images` / `web_head` / `web_app_icons` FFI + 注册 | `plugins/web` | +| I3 | `head_html`:meta 图标键 + `page.head` + 合并 `site_head` | `render.rs` | +| I4 | `images_html` 插入主区;fragment main 同理 | `render.rs` | +| I5 | `listen`:图标文件路由 + static 约定 favicon + `AppState` 注入 | `http.rs` / `lib.rs` | +| I6 | `ext/web/web.mq.md` + `网页.mq.md` L1 方法与叙述 | `ext/web` | +| I7 | 金样:离线装配 + live `GET /favicon.ico` + HTML 含 link/img | `tests/ext/` | +| I8 | `examples/marqdo-blog`:真实 favicon + logo 装配 + README | `examples/` | +| I9 | 更新 [web-net-capabilities.md](web-net-capabilities.md)、[ext-web.md](ext-web.md)、[doc/README.md](../README.md)、CHANGELOG Unreleased;Skill 专节一句 | 文档 | + +**非目标(本切片不做)** + +- 服务端图片缩放 / WebP 转码 +- CDN 签名 URL +- 把上传相册(`gallery`)与品牌图混为一谈 +- 进程内 TLS(仍见反代文档) + +--- + +## 9. 验收标准 + +1. `marqdo run tests/ext/web-assets-smoke.mq.md` 离线:icons/head/images 字段与 HTML 片段断言通过。 +2. Live:`GET /favicon.ico` → 200 + 正确 Content-Type;首页 HTML 含 `rel="icon"` 与 `mq-images`。 +3. `examples/marqdo-blog`:`curl /favicon.ico` 与页面源码可见图标与 logo。 +4. 旧金样(`web-static-smoke`、`web-content-smoke` 等)不回归。 +5. `ext/**` 无 `host_*`。 + +--- + +## 10. 与能力矩阵的关系 + +在 [web-net-capabilities.md](web-net-capabilities.md) **类 D** 增补: + +| # | 能力 | 状态 | +|---|------|------| +| **D10** | 站点图标 / `/favicon.ico` / apple-touch-icon | ✅ 本设计 | +| **D11** | Head 资源表(link / script / preload / manifest) | ✅ 本设计 | +| **D12** | 图片装配(GFM → figure/img)+ 主区注入 | ✅ 本设计 | + +波次标签:**W8(站点资源与图片装配)** — 在 W7+P3 完结之上的内容站体验补齐,不推翻既有边界。 diff --git a/doc/design/web-net-capabilities.md b/doc/design/web-net-capabilities.md index 64f77a8..4a4f740 100644 --- a/doc/design/web-net-capabilities.md +++ b/doc/design/web-net-capabilities.md @@ -166,6 +166,9 @@ | D7 | **评论系统**(表单 + 审核 + 反垃圾) | ✅ 约定:表+表单+where(W6);反垃圾属应用层 | `ext/web` | P2 ✅ | | D8 | **草稿/发布/定时**(状态字段 + 过滤查询) | ✅ 约定:`status` + where(W6) | `ext/web` + db where | P2 ✅ | | D9 | **图片/附件库**(依赖 A5 上传 + 相册页) | ✅ **已实现(P3)**:`app.gallery` HTML 相册 + A5 上传/下载 | `ext/web` + `plugins/web` | P3 ✅ | +| **D10** | **站点图标 / favicon**(`/favicon.ico` + apple-touch-icon) | ✅ **已实现(W8)**:`app.icons` / `应用.图标`;`static` 约定 `favicon.*`;设计 [web-assets-and-images.md](web-assets-and-images.md) | `plugins/web` + `ext/web` | W8 ✅ | +| **D11** | **Head 资源表**(link / script / preload / manifest) | ✅ **已实现(W8)**:`page.head` / `页面.头装配`;`meta` 认 `icon`/`favicon` | `plugins/web` + `ext/web` | W8 ✅ | +| **D12** | **图片装配**(GFM → figure/img + 主区注入) | ✅ **已实现(W8)**:`make_images` / `网页.图片装配`;`page.images` | `plugins/web` + `ext/web` | W8 ✅ | --- @@ -184,6 +187,7 @@ | **W6** | 进阶 | 全文搜索(FTS5) + 迁移机制 + 评论系统 + 草稿/发布 + WS 广播 | B6 B9 ✅;WS 广播 + access_log ✅;D7/D8 用表+where ✅ | | **W7** | 完结打磨 | Cache-Control、自定义 404/500、301 重定向、sitemap/robots、init 唯一/索引、HTTPS 反代文档 | A6 A7 A9 A10 B7 D2 ✅ | | **P3** | 真·网络扩展补齐 | 审计时间戳、外键、RBAC 门禁、媒体相册、下载 ETag | B10 C8 D9 + ETag/FK ✅ | +| **W8** | 站点资源与图片装配 | favicon 根路由、Head 资源表、图片装配、meta 图标键 | D10 D11 D12 ✅ | ### 4.2 边界判定要点(严格遵守既有约束) diff --git a/examples/marqdo-blog/README.md b/examples/marqdo-blog/README.md index e0287c6..9d4939c 100644 --- a/examples/marqdo-blog/README.md +++ b/examples/marqdo-blog/README.md @@ -18,7 +18,8 @@ cargo run -- examples/marqdo-blog/index.mq.md - `/about` — 关于页 - `/admin` — 会话门禁后台,登录 `admin` / `marqdo`,可增删改文章与标签 - `/live` — WebSocket 回显端点 -- `/static/*` — 静态资源(`public/` 下的 `live.js`) +- `/static/*` — 静态资源(`public/` 下的 `live.js`、favicon、logo) +- `/favicon.ico` — 站点图标(`应用.图标` 表装配) ## 设计亮点(文档即代码) @@ -29,6 +30,9 @@ cargo run -- examples/marqdo-blog/index.mq.md 每个 `## 段`(基础/顶栏/侧栏/主体/卡片/页脚/表单/响应式)导出一张样式表, `## 全局` 用 `网页.样式装配` 函数把每张表装配成 CSS 文本,再 `text.str_join` 拼成完整样式表, 最后经 `页面.样式` 注入页面。样式保持可读的数据表格,不写胶水代码。 +- **图标 / 头资源 / 图片装配**(W8):`应用.图标` 表挂 `/favicon.ico` 与 SVG; + `页面.头装配` 写 apple-touch-icon;`页面.图片装配` 把 logo 表注入主区(`mq-images`)。 + 含 `/` 的路径与 MIME 单元格需加引号(如 `"/static/logo.svg"`、`"image/png"`)。 - **页面 = 组件装配 + 主体绑定**(`index.mq.md`): 导航/侧栏/页脚用 `|组件|样式|` 表装配,文章列表用 `|属性|值|` 绑定 SQLite 字段。 - **动态路由**:`/post/{slug}` 的 `slug` 注入查询条件,`页面.详情` 把首行渲染成文章。 diff --git a/examples/marqdo-blog/index.mq.md b/examples/marqdo-blog/index.mq.md index 3c465ab..234d1b7 100644 --- a/examples/marqdo-blog/index.mq.md +++ b/examples/marqdo-blog/index.mq.md @@ -64,6 +64,25 @@ import db:db/index.mq.md |----|--------|------| | 1 | admin | marqdo | +`站点图标` = + +| 路径 | 关系 | 类型 | 尺寸 | 地址 | +|------|------|------|------|------| +| "public/favicon.png" | icon | "image/png" | 32x32 | "/favicon.ico" | +| "public/favicon.svg" | icon | "image/svg+xml" | any | "/static/favicon.svg" | + +`头资源` = + +| 关系 | 地址 | 类型 | +|------|------|------| +| apple-touch-icon | "/static/favicon.png" | "image/png" | + +`品牌图` = + +| 源 | 替代 | 类 | 链接 | 宽度 | 加载 | +|----|------|----|------|------|------| +| "/static/logo.svg" | Marqdo | brand-logo | "/" | 40 | eager | + *store = > db.打开* *首页CSS = > theme.全局* @@ -73,6 +92,8 @@ import db:db/index.mq.md *page = > page.主体装配 主体=`列表`* *page = > page.排序 排序="-created_at"* *page = > page.样式 样式=`首页CSS`* +*page = > page.头装配 表=`头资源`* +*page = > page.图片装配 表=`品牌图`* *about = > 网页.页面 标题="关于" 引言="

关于本站

一个用 Marqdo 的 web 扩展库(ext/web)写成的博客系统。

它演示了:GFM 表格装配导航与侧栏、SQLite 驱动的主体绑定、动态路由 /post/{slug}、标签归档、以及受 session 保护的后台 CRUD。

"* *about = > about.组件装配 组件=`首页`* @@ -104,6 +125,7 @@ import db:db/index.mq.md *app = > app.路由 路径="/tags" 页面=tags* *app = > app.路由 路径="/tag/{slug}" 页面=tagged* *app = > app.静态 目录="public" 挂载="/static"* +*app = > app.图标 表=`站点图标`* *app = > app.路由实时 路径="/live" 回显=True* *app = > app.鉴权 用户表=`管理员` 会话时长=3600* > `app`.监听 \ No newline at end of file diff --git a/examples/marqdo-blog/public/favicon.png b/examples/marqdo-blog/public/favicon.png new file mode 100644 index 0000000..0dd1608 --- /dev/null +++ b/examples/marqdo-blog/public/favicon.png @@ -0,0 +1,2 @@ +‰PNG + diff --git a/examples/marqdo-blog/public/favicon.svg b/examples/marqdo-blog/public/favicon.svg new file mode 100644 index 0000000..b361312 --- /dev/null +++ b/examples/marqdo-blog/public/favicon.svg @@ -0,0 +1 @@ +M diff --git a/examples/marqdo-blog/public/logo.svg b/examples/marqdo-blog/public/logo.svg new file mode 100644 index 0000000..b361312 --- /dev/null +++ b/examples/marqdo-blog/public/logo.svg @@ -0,0 +1 @@ +M diff --git a/examples/marqdo-blog/smoke.sh b/examples/marqdo-blog/smoke.sh index fc20f54..2f19264 100755 --- a/examples/marqdo-blog/smoke.sh +++ b/examples/marqdo-blog/smoke.sh @@ -18,6 +18,10 @@ curl -s "$BASE/" | grep -q '@media (max-width: 860px)' && ok "响应式媒体查 echo "== 静态 ==" code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/static/live.js") [ "$code" = "200" ] && ok "GET /static/live.js -> $code" || bad "static -> $code" +code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/favicon.ico") +[ "$code" = "200" ] && ok "GET /favicon.ico -> $code" || bad "favicon -> $code" +curl -s "$BASE/" | grep -q 'rel="icon"' && ok "head icon link" || bad "head icon 缺失" +curl -s "$BASE/" | grep -q 'mq-images' && ok "图片装配 logo" || bad "mq-images 缺失" echo "== 动态路由 ==" code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/post/hello-marqdo") diff --git a/ext/web/web.mq.md b/ext/web/web.mq.md index 06ed42f..25a3724 100644 --- a/ext/web/web.mq.md +++ b/ext/web/web.mq.md @@ -30,6 +30,26 @@ merged, and a leading `|媒体|` column groups rows into `@media` blocks), or > ensure_plugin **> web_style name=`name` table=`table`** +## make_images + + `table` + +Assemble a GFM image table into an HTML fragment (`div.mq-images` of +`
` / ``). Columns: `src`/`alt`/`title`/`class`/ +`href`/`width`/`height`/`loading`/`caption` (ZH: `源`/`替代`/`标题`/`类`/ +`链接`/`宽度`/`高度`/`加载`/`图注`). Images stay as data — 图片即数据、装配即函数. + +> ensure_plugin +**> web_images table=`table`** + +## make_head + + `table` + +Assemble a Head resource table into HTML (`` / `", esc(&l.href))); + s.push_str(&tag); + continue; + } + let mut tag = format!(""); + s.push_str(&tag); + } + s +} + +/// Module-level preview: assemble head table → HTML string. +pub fn make_head_html(table: &Value) -> String { + render_head_links(&as_head_links(table)) +} + +/// Normalize icons table → (icons json array, site_head links, file routes). +pub fn normalize_icons(table: &Value) -> (Value, Vec, Vec) { + let mut icons = Vec::new(); + let mut head = Vec::new(); + let mut routes = Vec::new(); + let mut saw_favicon_url = false; + + for m in rows_of(table) { + let path = row_str(&m, &["路径", "path", "file", "Path"]); + let mut rel = row_str(&m, &["关系", "rel", "Rel"]); + if rel.is_empty() { + rel = "icon".into(); + } + let mut type_ = row_str(&m, &["类型", "type", "Type"]); + let sizes = row_str(&m, &["尺寸", "sizes", "Sizes"]); + let mut url = row_str(&m, &["地址", "url", "href", "Href", "URL"]); + + if type_.is_empty() && !path.is_empty() { + type_ = mime_for_path(&path).to_string(); + } + if url.is_empty() { + if !path.is_empty() { + let name = Path::new(&path) + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or("icon"); + let lower = path.to_ascii_lowercase(); + if rel.to_ascii_lowercase().contains("icon") && lower.ends_with(".ico") { + url = "/favicon.ico".into(); + } else { + url = format!("/icons/{name}"); + } + } else { + continue; + } + } + if url == "/favicon.ico" { + saw_favicon_url = true; + } + + icons.push(json!({ + "path": path, + "rel": rel, + "type": type_, + "sizes": sizes, + "url": url, + })); + + if !url.is_empty() { + head.push(HeadLink { + rel: rel.clone(), + href: url.clone(), + type_: type_.clone(), + sizes: sizes.clone(), + media: String::new(), + as_: String::new(), + crossorigin: String::new(), + }); + } + + if !path.is_empty() && !url.is_empty() { + routes.push(IconRoute { + url: url.clone(), + path: PathBuf::from(&path), + content_type: if type_.is_empty() { + mime_for_path(&path).to_string() + } else { + type_.clone() + }, + }); + } + } + + // Ensure browser default path if we have an icon file but no /favicon.ico. + if !saw_favicon_url { + if let Some(first) = icons.iter().find(|v| { + v.get("rel") + .and_then(|r| r.as_str()) + .map(|r| r.to_ascii_lowercase().contains("icon")) + .unwrap_or(false) + && v.get("path") + .and_then(|p| p.as_str()) + .map(|p| !p.is_empty()) + .unwrap_or(false) + }) { + let path = first.get("path").and_then(|v| v.as_str()).unwrap_or(""); + let type_ = first + .get("type") + .and_then(|v| v.as_str()) + .unwrap_or_else(|| mime_for_path(path)); + routes.push(IconRoute { + url: "/favicon.ico".into(), + path: PathBuf::from(path), + content_type: type_.to_string(), + }); + head.insert( + 0, + HeadLink { + rel: "icon".into(), + href: "/favicon.ico".into(), + type_: type_.to_string(), + sizes: first + .get("sizes") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(), + media: String::new(), + as_: String::new(), + crossorigin: String::new(), + }, + ); + } + } + + (Value::Array(icons), head, routes) +} + +/// Convention: if static_dir has favicon.ico|png|svg and icons empty, register defaults. +pub fn convention_favicon(static_dir: &Path) -> Option<(Vec, Vec)> { + for name in ["favicon.ico", "favicon.png", "favicon.svg"] { + let p = static_dir.join(name); + if p.is_file() { + let ct = mime_for_path(name).to_string(); + let head = vec![HeadLink { + rel: "icon".into(), + href: "/favicon.ico".into(), + type_: ct.clone(), + sizes: String::new(), + media: String::new(), + as_: String::new(), + crossorigin: String::new(), + }]; + let routes = vec![IconRoute { + url: "/favicon.ico".into(), + path: p, + content_type: ct, + }]; + return Some((head, routes)); + } + } + None +} + +/// Merge site_head into a page value (dedupe by href+rel). +pub fn merge_site_head(page: &mut Value, site_head: &[HeadLink]) { + if site_head.is_empty() { + return; + } + let obj = match page.as_object_mut() { + Some(o) => o, + None => return, + }; + let mut existing = obj + .get("head") + .map(head_links_from_json) + .unwrap_or_default(); + for link in site_head { + let dup = existing.iter().any(|e| { + e.href == link.href && e.rel.eq_ignore_ascii_case(&link.rel) + }); + if !dup { + existing.push(link.clone()); + } + } + obj.insert("head".into(), head_links_to_json(&existing)); +} + +/// GFM image table → HTML fragment. +pub fn make_images_html(table: &Value) -> String { + let mut figures = String::new(); + for m in rows_of(table) { + let src = row_str(&m, &["源", "src", "Src", "url", "URL"]); + if src.is_empty() { + continue; + } + let alt = row_str(&m, &["替代", "alt", "Alt"]); + let title = row_str(&m, &["标题", "title", "Title"]); + let class = row_str(&m, &["类", "class", "Class"]); + let href = row_str(&m, &["链接", "href", "link", "Href", "Link"]); + let width = row_str(&m, &["宽度", "width", "Width"]); + let height = row_str(&m, &["高度", "height", "Height"]); + let mut loading = row_str(&m, &["加载", "loading", "Loading"]); + if loading.is_empty() { + loading = "lazy".into(); + } + let caption = row_str(&m, &["图注", "caption", "Caption"]); + + let mut img = format!("\"{}\"",", esc(&loading))); + + let inner = if href.is_empty() { + img + } else { + format!("{}", esc(&href), img) + }; + + let fig_class = if class.is_empty() { + "mq-img".into() + } else { + format!("mq-img {}", class) + }; + figures.push_str(&format!("
{}", fig_class, inner)); + if !caption.is_empty() { + figures.push_str(&format!("
{}
", esc(&caption))); + } + figures.push_str("
"); + } + if figures.is_empty() { + return String::new(); + } + format!("
{figures}
") +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn images_basic() { + let t = json!([ + {"源": "/a.png", "替代": "A", "类": "logo", "加载": "eager"} + ]); + let h = make_images_html(&t); + assert!(h.contains("mq-images")); + assert!(h.contains("src=\"/a.png\"")); + assert!(h.contains("loading=\"eager\"")); + assert!(h.contains("class=\"mq-img logo\"")); + } + + #[test] + fn head_script_and_icon() { + let t = json!([ + {"关系": "icon", "地址": "/favicon.ico", "类型": "image/x-icon"}, + {"关系": "script", "地址": "/static/a.js"} + ]); + let h = make_head_html(&t); + assert!(h.contains("rel=\"icon\"")); + assert!(h.contains("")); + } +} diff --git a/plugins/web/src/http.rs b/plugins/web/src/http.rs index df7bfab..861846b 100644 --- a/plugins/web/src/http.rs +++ b/plugins/web/src/http.rs @@ -26,6 +26,34 @@ use crate::sitemap; use crate::storage; use crate::upload; +fn with_site_head(base: &Value, site_head: &[crate::assets::HeadLink]) -> Value { + let mut page = base.clone(); + crate::assets::merge_site_head(&mut page, site_head); + page +} + +fn serve_icon_file(path: PathBuf, content_type: String) -> Response { + match std::fs::read(&path) { + Ok(bytes) => { + let ct = HeaderValue::from_str(&content_type) + .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream")); + ( + StatusCode::OK, + [ + (header::CONTENT_TYPE, ct), + ( + header::CACHE_CONTROL, + HeaderValue::from_static("public, max-age=86400"), + ), + ], + bytes, + ) + .into_response() + } + Err(_) => StatusCode::NOT_FOUND.into_response(), + } +} + #[derive(Clone)] pub struct UploadRoute { pub field: String, @@ -58,6 +86,8 @@ pub struct AppState { /// Optional assembled pages for 404 / 500. page_404: Option, page_500: Option, + /// Default `` links from `app.icons` / static favicon convention. + site_head: Vec, } fn collect_page_forms( @@ -107,6 +137,8 @@ pub fn listen( gates: Vec<(String, Vec)>, gallery_routes: HashMap, middleware: &Middleware, + mut site_head: Vec, + mut icon_routes: Vec, ) -> Result { let mut form_owners = HashMap::new(); collect_page_forms(page, &mut forms, &mut form_owners); @@ -120,6 +152,20 @@ pub fn listen( }); session::reset(session_ttl); rate_limit::reset(); + + // Convention: static_dir/favicon.* → /favicon.ico when no explicit icons. + if icon_routes.is_empty() { + if let Some(dir) = static_dir.as_ref() { + if let Some((head, routes)) = crate::assets::convention_favicon(dir) { + site_head = head; + icon_routes = routes; + } + } + } + + // Resolve relative icon paths: try as-is absolute, else leave for entry_dir resolve in lib. + // (Absolute paths preferred; relative already joined in web_listen.) + let state = Arc::new(AppState { page: page.clone(), db_url: db_url.map(|s| s.to_string()), @@ -133,6 +179,7 @@ pub fn listen( download_routes: download_routes.clone(), page_404: page_404.clone(), page_500: page_500.clone(), + site_head: site_head.clone(), }); let mut app = Router::new() @@ -165,6 +212,7 @@ pub fn listen( get(async move |State(st): State>, headers: axum::http::HeaderMap, Path(params): Path>| { let mut p = page_for_render.clone(); inject_params(&mut p, ¶ms); + let p = with_site_head(&p, &st.site_head); let (_, csrf, set_cookie) = resolve_session(&headers); let mut resp = Html(render::render_page(&p, st.db_url.as_deref(), Some(&csrf))).into_response(); append_set_cookie(&mut resp, set_cookie); @@ -188,7 +236,8 @@ pub fn listen( &path, get(async move |State(st): State>, headers: axum::http::HeaderMap| { let (_, csrf, set_cookie) = resolve_session(&headers); - let mut resp = Html(render::render_page(&page_for_render, st.db_url.as_deref(), Some(&csrf))) + let p = with_site_head(&page_for_render, &st.site_head); + let mut resp = Html(render::render_page(&p, st.db_url.as_deref(), Some(&csrf))) .into_response(); append_set_cookie(&mut resp, set_cookie); resp @@ -293,6 +342,36 @@ pub fn listen( app = app.nest_service(&mount, svc); } + // Root / custom icon file routes (favicon.ico, /icons/…). + for ir in icon_routes { + let url = ir.url.clone(); + if !url.starts_with('/') { + return Err(format!("icon url `{url}` must start with /")); + } + if !ir.path.is_file() { + return Err(format!( + "icon file `{}` not found for `{url}`", + ir.path.display() + )); + } + eprintln!( + "marqdo web icon: {} → {} ({})", + url, + ir.path.display(), + ir.content_type + ); + let path = ir.path.clone(); + let ct = ir.content_type.clone(); + app = app.route( + &url, + get(move || { + let path = path.clone(); + let ct = ct.clone(); + async move { serve_icon_file(path, ct) } + }), + ); + } + let mut redir_paths: Vec = redirects.keys().cloned().collect(); redir_paths.sort(); for path in redir_paths { @@ -435,7 +514,8 @@ fn rss_feed(st: &AppState, _path: &str, cfg: &Value) -> Response { async fn home(State(st): State>, headers: axum::http::HeaderMap) -> Response { let (_, csrf, set_cookie) = resolve_session(&headers); - let html = render::render_page(&st.page, st.db_url.as_deref(), Some(&csrf)); + let page = with_site_head(&st.page, &st.site_head); + let html = render::render_page(&page, st.db_url.as_deref(), Some(&csrf)); let mut resp = Html(html).into_response(); append_set_cookie(&mut resp, set_cookie); resp @@ -1638,7 +1718,8 @@ fn sitemap_response(st: &AppState, cfg: &Value) -> Response { async fn fallback_404(State(st): State>, headers: axum::http::HeaderMap) -> Response { let (_, csrf, set_cookie) = resolve_session(&headers); let html = if let Some(ref page) = st.page_404 { - render::render_page(page, st.db_url.as_deref(), Some(&csrf)) + let page = with_site_head(page, &st.site_head); + render::render_page(&page, st.db_url.as_deref(), Some(&csrf)) } else { "404

404 Not Found

" .to_string() @@ -1652,7 +1733,8 @@ async fn fallback_404(State(st): State>, headers: axum::http::Head #[allow(dead_code)] fn error_500(st: &AppState, csrf: Option<&str>, msg: &str) -> Response { let html = if let Some(ref page) = st.page_500 { - render::render_page(page, st.db_url.as_deref(), csrf) + let page = with_site_head(page, &st.site_head); + render::render_page(&page, st.db_url.as_deref(), csrf) } else { format!( "500

500

{}

", diff --git a/plugins/web/src/lib.rs b/plugins/web/src/lib.rs index ee8f645..45a6846 100644 --- a/plugins/web/src/lib.rs +++ b/plugins/web/src/lib.rs @@ -1,5 +1,6 @@ //! Marqdo web plugin (C ABI v2): SQLite, page assemble, HTTP listen. +mod assets; mod compose; mod db; mod db_pg; @@ -373,6 +374,93 @@ web_ffi!(web_page_meta, |args: &Value| { Ok(Value::Object(obj)) }); +web_ffi!(web_page_head, |args: &Value| { + let page = args.get("page").cloned().unwrap_or(json!({})); + let table = args + .get("table") + .or_else(|| args.get("head")) + .cloned() + .unwrap_or(json!([])); + let links = crate::assets::as_head_links(&table); + let mut obj = page.as_object().cloned().unwrap_or_default(); + let mut existing = obj + .get("head") + .map(crate::assets::head_links_from_json) + .unwrap_or_default(); + for link in links { + let dup = existing + .iter() + .any(|e| e.href == link.href && e.rel.eq_ignore_ascii_case(&link.rel)); + if !dup { + existing.push(link); + } + } + obj.insert("head".into(), crate::assets::head_links_to_json(&existing)); + Ok(Value::Object(obj)) +}); + +web_ffi!(web_head, |args: &Value| { + let table = args + .get("table") + .or_else(|| args.get("head")) + .cloned() + .unwrap_or(json!([])); + Ok(Value::String(crate::assets::make_head_html(&table))) +}); + +web_ffi!(web_images, |args: &Value| { + let table = args + .get("table") + .or_else(|| args.get("images")) + .cloned() + .unwrap_or(json!([])); + Ok(Value::String(crate::assets::make_images_html(&table))) +}); + +web_ffi!(web_page_images, |args: &Value| { + let page = args.get("page").cloned().unwrap_or(json!({})); + let table = args + .get("table") + .or_else(|| args.get("images")) + .cloned() + .unwrap_or(json!([])); + let html = crate::assets::make_images_html(&table); + let mut obj = page.as_object().cloned().unwrap_or_default(); + let prev = obj + .get("images_html") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + let combined = if prev.is_empty() { + html + } else if html.is_empty() { + prev + } else { + format!("{prev}{html}") + }; + obj.insert("images_html".into(), json!(combined)); + Ok(Value::Object(obj)) +}); + +web_ffi!(web_app_icons, |args: &Value| { + let mut app = args.get("app").cloned().unwrap_or(json!({})); + let table = args + .get("table") + .or_else(|| args.get("icons")) + .cloned() + .unwrap_or(json!([])); + let (icons, site_head, _routes) = crate::assets::normalize_icons(&table); + let obj = app + .as_object_mut() + .ok_or_else(|| "app must be a map".to_string())?; + obj.insert("icons".into(), icons); + obj.insert( + "site_head".into(), + crate::assets::head_links_to_json(&site_head), + ); + Ok(app) +}); + web_ffi!(web_page_paginate, |args: &Value| { let page = args.get("page").cloned().unwrap_or(json!({})); let offset = args @@ -1424,6 +1512,8 @@ web_ffi!(web_listen, |args: &Value| { gallery_routes, middleware, cookie_secure, + site_head, + icon_routes, ) = if args.get("page").is_some() || args.get("host").is_some() { let page = args.get("page").cloned().unwrap_or(json!({})); let db_url = db_url_of(args).ok(); @@ -1478,6 +1568,8 @@ web_ffi!(web_listen, |args: &Value| { HashMap::new(), middleware::Middleware::default(), cookie_secure, + Vec::::new(), + Vec::::new(), ) } else { let app = args.get("app").cloned().unwrap_or_else(|| args.clone()); @@ -1684,6 +1776,20 @@ web_ffi!(web_listen, |args: &Value| { .get("cookie_secure") .and_then(|v| v.as_bool()) .unwrap_or(false); + let (site_head, icon_routes) = if let Some(icons) = app.get("icons") { + let (_icons_json, head, routes) = crate::assets::normalize_icons(icons); + // Prefer precomputed site_head if present (same content). + let head = app + .get("site_head") + .map(crate::assets::head_links_from_json) + .filter(|h| !h.is_empty()) + .unwrap_or(head); + (head, routes) + } else if let Some(sh) = app.get("site_head") { + (crate::assets::head_links_from_json(sh), Vec::new()) + } else { + (Vec::new(), Vec::new()) + }; ( page, db_url, @@ -1709,6 +1815,8 @@ web_ffi!(web_listen, |args: &Value| { gallery_routes, middleware, cookie_secure, + site_head, + icon_routes, ) }; let static_dir = static_dir.map(|p| { @@ -1718,6 +1826,32 @@ web_ffi!(web_listen, |args: &Value| { entry_dir().join(p) } }); + let icon_routes: Vec = icon_routes + .into_iter() + .map(|mut r| { + if !r.path.is_absolute() { + let joined = entry_dir().join(&r.path); + if joined.is_file() { + r.path = joined; + } else if let Some(ref sd) = static_dir { + let name = r + .path + .file_name() + .map(PathBuf::from) + .unwrap_or_else(|| r.path.clone()); + let in_static = sd.join(&name); + if in_static.is_file() { + r.path = in_static; + } else { + r.path = joined; + } + } else { + r.path = joined; + } + } + r + }) + .collect(); http::listen( &page, db_url.as_deref(), @@ -1743,6 +1877,8 @@ web_ffi!(web_listen, |args: &Value| { gates, gallery_routes, &middleware, + site_head, + icon_routes, ) }); @@ -1816,6 +1952,23 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int "page,meta", web_page_meta as PluginFn, ), + ( + "web_page_head", + "page,table", + web_page_head as PluginFn, + ), + ( + "web_page_images", + "page,table", + web_page_images as PluginFn, + ), + ("web_head", "table", web_head as PluginFn), + ("web_images", "table", web_images as PluginFn), + ( + "web_app_icons", + "app,table", + web_app_icons as PluginFn, + ), ( "web_page_paginate", "page,offset,limit,path", diff --git a/plugins/web/src/render.rs b/plugins/web/src/render.rs index 05166e8..7729234 100644 --- a/plugins/web/src/render.rs +++ b/plugins/web/src/render.rs @@ -376,6 +376,18 @@ fn head_html(args: &Value, default_title: &str) -> String { "canonical" => { s.push_str(&format!("", esc(&val))); } + "icon" | "favicon" => { + s.push_str(&format!( + "", + esc(&val) + )); + } + "apple-touch-icon" | "apple_touch_icon" => { + s.push_str(&format!( + "", + esc(&val) + )); + } k if k.starts_with("og:") => { s.push_str(&format!( "", @@ -393,6 +405,10 @@ fn head_html(args: &Value, default_title: &str) -> String { } } } + if let Some(head) = args.get("head") { + let links = crate::assets::head_links_from_json(head); + s.push_str(&crate::assets::render_head_links(&links)); + } s } @@ -476,6 +492,11 @@ pub fn render_page_ex( }; let mut main_html = String::new(); + if let Some(images) = args.get("images_html").and_then(|v| v.as_str()) { + if !images.is_empty() { + main_html.push_str(images); + } + } if !intro.is_empty() { main_html.push_str(&format!("
{intro}
")); } @@ -579,6 +600,11 @@ pub fn render_fragment(args: &Value, db_url: Option<&str>) -> String { _ => { let (intro, items, _total) = resolve_main(args, db_url); let mut body = String::new(); + if let Some(images) = args.get("images_html").and_then(|v| v.as_str()) { + if !images.is_empty() { + body.push_str(images); + } + } if !intro.is_empty() { body.push_str(&format!("
{intro}
")); } diff --git a/skills/marqdo/SKILL.md b/skills/marqdo/SKILL.md index 095fea9..6f03858 100644 --- a/skills/marqdo/SKILL.md +++ b/skills/marqdo/SKILL.md @@ -154,6 +154,7 @@ Import **one language file** — never mix EN/ZH API names in the same `.mq.md`: - Authors use **GFM tables + `#` classes** — no `json.parse` / `json.set` glue, no hand-built part JSON. - Table cells stay **literal strings**; path text like `` `posts`.`title` `` is resolved by web classes. +- **Quote path/MIME cells** that contain `/` (T5 cell expressions treat bare `/` as division): `"/static/logo.svg"`, `"image/png"`. - **`ext/**` never calls `host_*`** — hot path is native `plugins/web` ABI. - HTTPS: terminate at reverse proxy; set `cookie_secure=True` on auth (no in-process TLS). @@ -164,17 +165,18 @@ index.mq.md # entry + home page table + listen pages/ # sub-pages components/ # reusable |属性|值|样式| tables styles/ # CSS modules +public/ # static + favicon.ico|png|svg db/ # schema + open/init data/ # sqlite runtime (gitignore) ``` **Core objects (EN / ZH):** `# page`/`页面`, `# style`/`样式`, `# db`/`数据库`, `# form`/`表单`, `# app`/`应用`, `# auth`/`鉴权`, `# cache`/`缓存`, `# storage`/`存储`. -**Typical flow:** `db.init` → `page.compose_components` + `page.compose_main` → `page.render` → `app` with `route` / `static` / `configure` / `listen`. +**Typical flow:** `db.init` → `page.compose_components` + `page.compose_main` → `page.head` / `page.images` / `page.meta` → `app` with `route` / `static` / `icons` / `configure` / `listen`. -**Shipped surface (W0–W7 + P3):** middleware + JSON API (`app.configure`); transactions, pagination, FTS search (`db.migrate`, `db.fts`, `db.search`); security (argon2, CSRF, SQLite sessions, login rate limit); SEO / RSS / Markdown (`page.meta`, `route_rss`, `lib/net.markdown_parse`); upload / download / gallery; sitemap / robots / error pages / redirects; RBAC (`app.gate`, user `role`); audit timestamps + FK in `db.init`; ETag on downloads. +**Shipped surface (W0–W7 + P3 + W8):** middleware + JSON API (`app.configure`); transactions, pagination, FTS search (`db.migrate`, `db.fts`, `db.search`); security (argon2, CSRF, SQLite sessions, login rate limit); SEO / RSS / Markdown (`page.meta`, `route_rss`, `lib/net.markdown_parse`); upload / download / gallery; sitemap / robots / error pages / redirects; RBAC (`app.gate`, user `role`); audit timestamps + FK in `db.init`; ETag on downloads; **W8** site icons (`app.icons` → `/favicon.ico`), head resource tables (`page.head`), image assembly (`make_images` / `page.images`). -Design: [ext-web.md](../../doc/design/ext-web.md) · capability matrix: [web-net-capabilities.md](../../doc/design/web-net-capabilities.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/). +Design: [ext-web.md](../../doc/design/ext-web.md) · assets: [web-assets-and-images.md](../../doc/design/web-assets-and-images.md) · capability matrix: [web-net-capabilities.md](../../doc/design/web-net-capabilities.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/). Web patterns: [examples.md](examples.md) §13 · API index: [reference.md](reference.md). diff --git a/src/host/plugin.rs b/src/host/plugin.rs index db6832a..6c8688f 100644 --- a/src/host/plugin.rs +++ b/src/host/plugin.rs @@ -4,6 +4,7 @@ use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::ffi::{CStr, CString}; use std::os::raw::{c_char, c_int, c_void}; +use std::path::PathBuf; use libloading::{Library, Symbol}; @@ -273,8 +274,10 @@ unsafe extern "C" fn host_query( "cwd" => Ok(serde_json::Value::String( ctx.cwd.to_string_lossy().into_owned(), )), - "entry_dir" => Ok(serde_json::Value::String( - ctx.entry_path + "entry_dir" => { + // Script directory: parent of entry file (for_run also sets ctx.cwd to this). + let dir = ctx + .entry_path .as_ref() .map(|p| { if p.is_dir() { @@ -283,10 +286,21 @@ unsafe extern "C" fn host_query( p.parent().unwrap_or(p).to_path_buf() } }) - .unwrap_or_else(|| ctx.cwd.clone()) - .to_string_lossy() - .into_owned(), - )), + .unwrap_or_else(|| ctx.cwd.clone()); + // Absolutize against the *process* cwd — not ctx.cwd. For a relative + // entry like `tests/ext/foo.mq.md`, for_run sets ctx.cwd = `tests/ext`; + // joining that again would yield `tests/ext/tests/ext/...`. + let abs = if dir.is_absolute() { + dir + } else { + std::env::current_dir() + .unwrap_or_else(|_| PathBuf::from(".")) + .join(dir) + }; + Ok(serde_json::Value::String( + abs.to_string_lossy().into_owned(), + )) + } "call_lib_path" => (|| { let raw = args_owned.as_deref().unwrap_or("{}"); let args: serde_json::Value = serde_json::from_str(if raw.trim().is_empty() { diff --git a/tests/ext/web-assets-live-server.mq.md b/tests/ext/web-assets-live-server.mq.md new file mode 100644 index 0000000..8c33995 --- /dev/null +++ b/tests/ext/web-assets-live-server.mq.md @@ -0,0 +1,36 @@ +--- +title: web assets live server +description: Live favicon + head icon + images_html on home page. +import web:ext/web/web.mq.md +--- + +# main + +`icons_table` = + +|path|rel|type|url| +|---|---|---|---| +|"web-fixtures/public/favicon.png"|icon|"image/png"|"/favicon.ico"| + +`head_table` = + +|rel|href|type| +|---|---|---| +|apple-touch-icon|"/static/favicon.png"|"image/png"| + +`images_table` = + +|src|alt|class|loading| +|---|---|---|---| +|"/static/favicon.svg"|mark|brand|eager| + +*home = > web.page title="Live assets" intro="

assets live

"* +*home = > `home`.head table=`head_table`* +*home = > `home`.images table=`images_table`* + +*app = > web.app page=`home` host=127.0.0.1 port=18092* +*app = > `app`.static dir="web-fixtures/public" mount="/static"* +*app = > `app`.icons table=`icons_table`* + +> print text=marqdo web assets live starting +> `app`.listen diff --git a/tests/ext/web-assets-smoke.mq.md b/tests/ext/web-assets-smoke.mq.md new file mode 100644 index 0000000..11f84f9 --- /dev/null +++ b/tests/ext/web-assets-smoke.mq.md @@ -0,0 +1,92 @@ +--- +title: web assets smoke +description: Offline icons / head / images assembly (no listen). +import web:ext/web/web.mq.md +import json:lib/json.mq.md +--- + +# main + +`icons_table` = + +|path|rel|type|sizes|url| +|---|---|---|---|---| +|"web-fixtures/public/favicon.png"|icon|"image/png"|32x32|"/favicon.ico"| +|"web-fixtures/public/favicon.svg"|icon|"image/svg+xml"|any|"/static/favicon.svg"| + +`head_table` = + +|rel|href|type|media| +|---|---|---|---| +|icon|"/favicon.ico"|"image/png"| +|stylesheet|"/static/print.css"|"text/css"|print| +|script|"/static/live.js"|| + +`images_table` = + +|src|alt|class|href|width|loading|caption| +|---|---|---|---|---|---|---| +|"/static/logo.svg"|Marqdo|brand-logo|"/"|48|eager|Brand| + +`seo` = + +| 行 | key | value | +|----|-----|-------| +| 1 | description | asset smoke | +| 2 | icon | "/favicon.ico" | +| 3 | og:image | "/static/logo.svg" | + +*home = > web.page title="Assets"* +*home = > `home`.head table=`head_table`* +*home = > `home`.images table=`images_table`* +*home = > `home`.meta meta=`seo`* + +*ih = > json.get value=`home` key="images_html"* +1. `ih` != "" + > print text=images-ok +2. * + > print text=images-fail + +*hd = > json.get value=`home` key="head"* +*n = > len `hd`* +1. `n` >= 3 + > print text=head-ok +2. * + > print text=head-fail + +*meta = > json.get value=`home` key="meta"* +*icon = > json.get value=`meta` key="icon"* +1. `icon` == "/favicon.ico" + > print text=meta-icon-ok +2. * + > print text=meta-icon-fail + +*app = > web.app page=`home` host=127.0.0.1 port=18091* +*app = > `app`.static dir="web-fixtures/public" mount="/static"* +*app = > `app`.icons table=`icons_table`* + +*icons = > json.get value=`app` key="icons"* +*ni = > len `icons`* +1. `ni` == 2 + > print text=icons-ok +2. * + > print text=icons-fail + +*sh = > json.get value=`app` key="site_head"* +*ns = > len `sh`* +1. `ns` >= 1 + > print text=site-head-ok +2. * + > print text=site-head-fail + +*preview = > web.make_images table=`images_table`* +1. `preview` != "" + > print text=make-images-ok +2. * + > print text=make-images-fail + +*hprev = > web.make_head table=`head_table`* +1. `hprev` != "" + > print text=make-head-ok +2. * + > print text=make-head-fail diff --git a/tests/ext/web-fixtures/public/favicon.png b/tests/ext/web-fixtures/public/favicon.png new file mode 100644 index 0000000..0dd1608 --- /dev/null +++ b/tests/ext/web-fixtures/public/favicon.png @@ -0,0 +1,2 @@ +‰PNG + diff --git a/tests/ext/web-fixtures/public/favicon.svg b/tests/ext/web-fixtures/public/favicon.svg new file mode 100644 index 0000000..b361312 --- /dev/null +++ b/tests/ext/web-fixtures/public/favicon.svg @@ -0,0 +1 @@ +M diff --git a/tests/gold.rs b/tests/gold.rs index d40de40..7663378 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -1542,6 +1542,102 @@ custom-ok", ); } +#[test] +fn ext_web_assets_smoke() { + let status = Command::new("cargo") + .args(["build", "-p", "marqdo_plugin_web"]) + .current_dir(env!("CARGO_MANIFEST_DIR")) + .status() + .expect("build web plugin"); + assert!(status.success(), "failed to build marqdo_plugin_web"); + assert_out( + "tests/ext/web-assets-smoke.mq.md", + "images-ok +head-ok +meta-icon-ok +icons-ok +site-head-ok +make-images-ok +make-head-ok", + ); +} + +#[test] +fn ext_web_assets_live() { + let status = Command::new("cargo") + .args(["build", "-p", "marqdo_plugin_web"]) + .current_dir(env!("CARGO_MANIFEST_DIR")) + .status() + .expect("build web plugin"); + assert!(status.success(), "failed to build marqdo_plugin_web"); + + let script = "tests/ext/web-assets-live-server.mq.md"; + let bin = env!("CARGO_BIN_EXE_marqdo"); + let mut child = Command::new(bin) + .args(["run", script]) + .current_dir(env!("CARGO_MANIFEST_DIR")) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("spawn assets live server"); + + let base = "http://127.0.0.1:18092"; + let ready = std::time::Instant::now(); + loop { + if ready.elapsed().as_secs() > 10 { + let _ = child.kill(); + panic!("assets live server did not start in time"); + } + let out = Command::new("curl") + .args([ + "-s", + "-o", + "/dev/null", + "-w", + "%{http_code}", + &format!("{base}/"), + ]) + .output() + .expect("curl probe"); + if String::from_utf8_lossy(&out.stdout) == "200" { + break; + } + std::thread::sleep(std::time::Duration::from_millis(300)); + } + + let out = Command::new("curl") + .args([ + "-s", + "-D", + "-", + "-o", + "/tmp/marqdo-favicon.bin", + "-w", + "\n%{http_code}", + &format!("{base}/favicon.ico"), + ]) + .output() + .expect("curl favicon"); + let body = String::from_utf8_lossy(&out.stdout); + assert!( + body.contains("200") && body.to_ascii_lowercase().contains("image/"), + "favicon headers={body}" + ); + + let out = Command::new("curl") + .args(["-s", &format!("{base}/")]) + .output() + .expect("curl home"); + let html = String::from_utf8_lossy(&out.stdout); + assert!( + html.contains("rel=\"icon\"") && html.contains("mq-images") && html.contains("apple-touch-icon"), + "home html missing assets markers: {}", + &html[..html.len().min(500)] + ); + + let _ = child.kill(); +} + #[test] fn ext_web_middleware_smoke() { let status = Command::new("cargo")