feat(web): C3 style cell strict checks and head defer/version

Warn or reject numeric CSS values from bare `/` division; support script defer/async/version and page/app asset_version for cache busting.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-04 13:43:35 +08:00
1 parent 824b9bf607
commit 7670673a39
11 files changed
+426 -52

No files matched your search

+1
View File
@@ -11,6 +11,7 @@
- **`ext/web` C0**:`admin=False` 不再挂载/保留 `/admin*`;可配 `admin_prefix` / `login_redirect` / `logout_redirect`;金样 `web-c0-admin-prefix`。
- **`ext/web` C1**:门禁段边界匹配(不再误伤 `/admin-publish`);`gate` 支持 `match` / `on_deny` / `exclude`;`auth` 默认 `on_deny=redirect` + `login_path`;金样 `web-c1-gates`。
- **`ext/web` C2**:`shell_css=full|minimal|off`;`layout=sidebar|stacked|bare|rail`;full 壳含小屏单列 media;金样 `web-c2-shell-layout`。
- **`ext/web` C3**:样式装配对数字/布尔值单元格告警,`strict`/`strict_css_cells` 硬错误;`page.css` 作 raw CSS;head 表支持 `defer`/`async`/`version`,`asset_version` 统一 `?v=`;金样 `web-c3-style-head`。
### Changed
- `build_step_context`:call site 提前到 task 之后;开场白强调 code-as-documentation。
+2 -2
View File
@@ -2,7 +2,7 @@
| | |
|---|---|
| 状态 | **C0–C2 done · C3–C4 planned** |
| 状态 | **C0–C3 done · C4 planned** |
| 日期 | 2026-09-04 |
| 问题盘点 | [../../research/ext-web-customization-limits.md](../../research/ext-web-customization-limits.md) |
| 相关 | [../ext-web.md](../ext-web.md) · [../ext-web-net.md](../ext-web-net.md) · [../../roadmap/ext-web.md](../../roadmap/ext-web.md) |
@@ -35,7 +35,7 @@
| **C0** | 可配置 `admin_prefix`;`admin=False` 时不挂内置路由;`login_redirect` / `logout_redirect` | — |
| **C1** | gate:统一未登录策略;精确/前缀匹配;登录页自动放行;默认 gate 不再误伤 `/admin-*` | C0 |
| **C2** | `shell_css=off\|minimal\|full`;主题在壳前或隔离层;可选 `layout=bare` | — |
| **C3** | 样式:文档 + 校验警告;可选 raw CSS 块;脚本 `defer`/`type=module` 默认 | — |
| **C3** | 样式:校验警告 / `strict`;`page.css` raw;脚本 `defer`/`async`/`version` + `asset_version` | **done** |
| **C4** | 壳:`layout` 预设(sidebar / stacked / bare);条件导航钩子(后续) | C2 |
路线图入口可在 [ext-web.md](../../roadmap/ext-web.md) 增补「定制波次 C0–C4」行,落地后再改状态。
+5 -2
View File
@@ -121,13 +121,16 @@ url = /favicon.ico
| `媒体` | `media` | CSS media |
| `作为` | `as` | preload `as` |
| `跨域` | `crossorigin` | 空 / `anonymous` / `use-credentials` |
| `推迟` | `defer` | 经典 `script` 为真时输出 `defer`(缺省同步,兼容旧站) |
| `异步` | `async` | 为真时输出 `async` |
| `版本` | `version` / `v` | 非空则自动追加 `?v=`;否则用页面/应用 `asset_version` |
**渲染规则**
| `rel` | 输出 |
|-------|------|
| `script` | `<script src="…"></script>`(`type` 非空则写出) |
| `module` | `<script type="module" src="…"></script>` |
| `script` | `<script … src="…"></script>`(可选 `defer`/`async`;`type` 非空则写出) |
| `module` | `<script type="module" src="…"></script>`(浏览器默认 defer 语义) |
| 其他 | `<link rel="…" href="…" …>`(按列附加 `type`/`sizes`/`media`/`as`/`crossorigin`) |
空 `地址` 的行跳过。
+1 -1
View File
@@ -44,7 +44,7 @@
| **C0** | `admin` 关则不占路径;`admin_prefix` / 登录回跳可配 | **done** |
| **C1** | gate 匹配与未登录策略一致;段边界默认 admin gate | **done** |
| **C2** | `shell_css` + `layout` 松绑 | **done** |
| **C3** | 样式 strict / 脚本 defer·version | **planned** |
| **C3** | 样式 strict / 脚本 defer·version | **done** |
| **C4** | 壳预设收口与条件导航(后续) | **planned** |
验收金样:`tests/ext/web-smoke.mq.md`、`tests/ext/web-security-smoke.mq.md`、`tests/ext/web-drivers-smoke.mq.md`、`tests/ext/web-upload-smoke.mq.md`、`tests/ext/web-db-w6-smoke.mq.md`、`tests/ext/web-w7-finish-smoke.mq.md`、`tests/ext/web-p3-smoke.mq.md`、`ext_cli_add_web`。
+24 -9
View File
@@ -21,6 +21,7 @@ Load the ABI v2 `web` plugin once.
## make_style
+ `name`=""
+ `table`
+ `strict`=False
Assemble a GFM style table into a CSS string. Two shapes are accepted:
`|选择器|属性|值|` rule rows (arbitrary selectors; rows sharing a selector are
@@ -28,11 +29,14 @@ merged, and a leading `|媒体|` column groups rows into `@media` blocks), or
`|属性|值|` property rows wrapped as `.name { … }`. Selectors starting with
`@keyframes name` emit keyframe blocks (`属性` = stop `from`/`to`/`N%`,
`值` = `prop: val` or use `@keyframes name from` + normal 属性/值). Quote CSS
values that contain `/` (e.g. `"16/9"`, `"1/5"`); bare `1/5` is integer division.
Styles stay as data tables, `make_style` turns them into CSS — 样式即数据、装配即函数.
values that contain `/` (e.g. `"16/9"`, `"1 / 5"`); bare `1 / 5` is integer
division and becomes a numeric cell — default mode warns, `strict=True` errors.
For complex themes prefer `page.css` (raw string, no table eval) or an external
`static/*.css` via `page.head`. Styles stay as data tables, `make_style` turns
them into CSS — 样式即数据、装配即函数.
> ensure_plugin
**> web_style name=`name` table=`table`**
**> web_style name=`name` table=`table` strict=`strict`**
## make_images
+ `table`
@@ -181,9 +185,10 @@ Build a `render_list` effect: `{ render_list: { sel: { tag, items } } }`.
+ `intro`=""
+ `shell_css`=None
+ `layout`=None
+ `asset_version`=None
> ensure_plugin
**> web_page_new title=`title` intro=`intro` shell_css=`shell_css` layout=`layout`**
**> web_page_new title=`title` intro=`intro` shell_css=`shell_css` layout=`layout` asset_version=`asset_version`**
## shell_css
+ `mode`=full
@@ -201,6 +206,14 @@ Page chrome layout: `sidebar` (default when a side slot exists), `stacked` (sing
*`out` = > table.put in=`self` at="layout" value=layout*
**out**
## asset_version
+ `version`=""
Default `?v=` bump for head scripts/styles that omit a per-row `version` column.
*`out` = > table.put in=`self` at="asset_version" value=version*
**out**
## compose_components
+ `components`
@@ -241,8 +254,9 @@ an `href`/`链接` field become `<a href="{prefix}{href}">`.
## css
+ `css`
Append a raw CSS string to the page's stylesheet (`styles_css`). Use it to ship
a hand-written theme alongside the assembled shell.
Append a **raw** CSS string to the page's stylesheet (`styles_css`). Skips table-cell
expression evaluation — use for themes with `/`, `@keyframes`, or long media queries.
Hand-written theme alongside the assembled shell; or link `static/theme.css` via `head`.
**> web_page_css page=`self` css=`css`**
@@ -264,7 +278,7 @@ SEO / OpenGraph metadata as a data table (`|key|value|`). Keys such as `title`,
## head
+ `table`
Assemble `<head>` resources from a GFM table (`|rel|href|type|sizes|media|as|crossorigin|` or ZH `|关系|地址|类型|…|`). `rel=script` / `module` become `<script>`; other rows become `<link>`. Merges with any existing `head` on the page.
Assemble `<head>` resources from a GFM table (`|rel|href|type|sizes|media|as|crossorigin|defer|async|version|` or ZH `|关系|地址|…|推迟|异步|版本|`). `rel=script` / `module` become `<script>`; other rows become `<link>`. Classic scripts emit `defer` / `async` only when those columns are true (compat: missing `defer` stays synchronous). Non-empty `version` appends `?v=`; else page/app `asset_version` is used. Merges with any existing `head` on the page.
**> web_page_head page=`self` table=`table`**
@@ -588,11 +602,12 @@ Field table + rules table; submit writes through `# db`.
+ `logout_redirect`=None
+ `shell_css`=None
+ `layout`=None
+ `asset_version`=None
Construct an app. `admin=True` mounts the built-in CRUD UI under `admin_prefix` (default `/admin`). When `admin=False`, that prefix is **not** reserved — you may `route` your own pages there. Optional `login_redirect` / `logout_redirect` override post-auth landing. Optional `shell_css` / `layout` become defaults for pages that do not set their own (see `page.shell_css` / `page.layout`).
Construct an app. `admin=True` mounts the built-in CRUD UI under `admin_prefix` (default `/admin`). When `admin=False`, that prefix is **not** reserved — you may `route` your own pages there. Optional `login_redirect` / `logout_redirect` override post-auth landing. Optional `shell_css` / `layout` / `asset_version` become defaults for pages that do not set their own (see `page.shell_css` / `page.layout` / `page.asset_version`).
> ensure_plugin
**> web_app_new page=`page` db=`db` admin=`admin` host=`host` port=`port` admin_prefix=`admin_prefix` login_redirect=`login_redirect` logout_redirect=`logout_redirect` shell_css=`shell_css` layout=`layout`**
**> web_app_new page=`page` db=`db` admin=`admin` host=`host` port=`port` admin_prefix=`admin_prefix` login_redirect=`login_redirect` logout_redirect=`logout_redirect` shell_css=`shell_css` layout=`layout` asset_version=`asset_version`**
## route
+ `path`
+19 -7
View File
@@ -21,17 +21,19 @@ import table:lib/table.mq.md
## 样式装配
+ `名`=""
+ `表`
+ `严格`=False
把 GFM 样式表装配成一段 CSS 文本。支持两种表形:
`|选择器|属性|值|` 规则行(选择器任意,同一选择器多行合并成一条规则;
加 `|媒体|` 列即可分组进 `@media` 块),或 `|属性|值|` 属性行(按 `.名 { … }` 包裹)。
选择器以 `@keyframes 名` 开头时输出关键帧块(`属性` 为停点 `from`/`to`/`N%`,
`值` 写 `opacity: 0` 等声明;也可用 `@keyframes 名 from` + 普通属性/值)。
含 `/` 的 CSS 值请加引号(如 `"16/9"`、`"1/5"`),否则按表达式除法求值。
含 `/` 的 CSS 值请加引号(如 `"16/9"`、`"1 / 5"`);裸 `1 / 5` 会按表达式除法变成数字单元格——默认告警,`严格=真` 时报错。
复杂主题优先 `页面.样式`(原始 CSS 字符串,不经表求值)或外链 `static/*.css` + `页面.头装配`。
样式即数据、装配即函数 —— 主题模块据此把样式表拼成完整样式表。
> 确保插件
**> web_style name=`名` table=`表`**
**> web_style name=`名` table=`表` strict=`严格`**
## 图片装配
+ `表`
@@ -176,9 +178,10 @@ import table:lib/table.mq.md
+ `引言`=""
+ `壳样式`=None
+ `布局`=None
+ `资源版本`=None
> 确保插件
**> web_page_new title=`标题` intro=`引言` shell_css=`壳样式` layout=`布局`**
**> web_page_new title=`标题` intro=`引言` shell_css=`壳样式` layout=`布局` asset_version=`资源版本`**
## 壳样式
+ `模式`=full
@@ -196,6 +199,14 @@ import table:lib/table.mq.md
*`out` = > table.put in=`自` at="layout" value=布局*
**out**
## 资源版本
+ `版本`=""
为未写 `版本` 列的 head 脚本/样式统一追加 `?v=`。
*`out` = > table.put in=`自` at="asset_version" value=版本*
**out**
## 组件装配
+ `组件`
@@ -230,7 +241,7 @@ import table:lib/table.mq.md
## 样式
+ `样式`
把一段手写 CSS 字符串追加到页面样式表(`styles_css`),用于在装配好的外壳上叠加自定义主题。
把一段**原始** CSS 字符串追加到页面样式表(`styles_css`),不经表单元格表达式求值——适合含 `/`、`@keyframes` 或长 media 的主题。也可外链 `static/theme.css` 再经 `头装配`。
**> web_page_css page=`self` css=`样式`**
@@ -251,7 +262,7 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c
## 头装配
+ `表`
把 Head 资源表(`|关系|地址|类型|尺寸|媒体|作为|跨域|`)挂到页面的 `head`。`关系=script` / `module` 生成 `<script>`,其余生成 `<link>`。与已有 `head` 合并。
把 Head 资源表(`|关系|地址|类型|尺寸|媒体|作为|跨域|推迟|异步|版本|`)挂到页面的 `head`。`关系=script` / `module` 生成 `<script>`,其余生成 `<link>`。经典脚本仅在 `推迟`/`异步` 为真时输出对应属性(缺省仍同步,兼容旧站)。非空 `版本` 追加 `?v=`,否则用页面/应用的 `资源版本`。与已有 `head` 合并。
**> web_page_head page=`self` table=`表`**
@@ -568,11 +579,12 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c
+ `登出回跳`=None
+ `壳样式`=None
+ `布局`=None
+ `资源版本`=None
构造应用。`后台=真` 时在 `后台前缀`(默认 `/admin`)挂载内置 CRUD。`后台=假` 时该前缀**不再保留**,可自行 `路由` 到 `/admin…`。可选 `登录回跳` / `登出回跳`。可选 `壳样式` / `布局` 作为未自设页面的默认(见 `页面.壳样式` / `页面.布局`)。
构造应用。`后台=真` 时在 `后台前缀`(默认 `/admin`)挂载内置 CRUD。`后台=假` 时该前缀**不再保留**,可自行 `路由` 到 `/admin…`。可选 `登录回跳` / `登出回跳`。可选 `壳样式` / `布局` / `资源版本` 作为未自设页面的默认(见 `页面.壳样式` / `页面.布局` / `页面.资源版本`)。
> 确保插件
**> web_app_new page=`页面` db=`数据库` admin=`后台` host=`主机` port=`端口` admin_prefix=`后台前缀` login_redirect=`登录回跳` logout_redirect=`登出回跳` shell_css=`壳样式` layout=`布局`**
**> web_app_new page=`页面` db=`数据库` admin=`后台` host=`主机` port=`端口` admin_prefix=`后台前缀` login_redirect=`登录回跳` logout_redirect=`登出回跳` shell_css=`壳样式` layout=`布局` asset_version=`资源版本`**
## 路由
+ `路径`
+122 -5
View File
@@ -15,6 +15,11 @@ pub struct HeadLink {
pub media: String,
pub as_: String,
pub crossorigin: String,
/// When `Some(true)`, emit `defer` on classic scripts (not modules).
pub defer: Option<bool>,
pub async_: bool,
/// Query `?v=` bump for cache busting.
pub version: String,
}
#[derive(Clone, Debug)]
@@ -38,6 +43,37 @@ fn pick<'a>(m: &'a Map<String, Value>, keys: &[&str]) -> Option<&'a Value> {
keys.iter().find_map(|k| m.get(*k))
}
fn cell_boolish(v: &Value) -> Option<bool> {
match v {
Value::Bool(b) => Some(*b),
Value::Number(n) => Some(n.as_i64().unwrap_or(0) != 0),
Value::String(s) => {
let s = s.trim();
if s.is_empty() {
return None;
}
if matches!(
s,
"1" | "true" | "True" | "yes" | "on" | "真" | "是"
) {
Some(true)
} else if matches!(
s,
"0" | "false" | "False" | "no" | "off" | "假" | "否"
) {
Some(false)
} else {
None
}
}
_ => None,
}
}
fn row_bool(m: &Map<String, Value>, keys: &[&str]) -> Option<bool> {
pick(m, keys).and_then(cell_boolish)
}
fn row_str(m: &Map<String, Value>, keys: &[&str]) -> String {
pick(m, keys)
.map(|v| normalize_ref(&cell_str(v)))
@@ -46,6 +82,19 @@ fn row_str(m: &Map<String, Value>, keys: &[&str]) -> String {
.to_string()
}
/// Append `?v=` / `&v=` for cache busting.
pub fn href_with_version(href: &str, version: &str) -> String {
let version = version.trim();
if version.is_empty() {
return href.to_string();
}
if href.contains('?') {
format!("{href}&v={version}")
} else {
format!("{href}?v={version}")
}
}
fn esc(s: &str) -> String {
s.replace('&', "&amp;")
.replace('<', "&lt;")
@@ -142,6 +191,9 @@ pub fn as_head_links(table: &Value) -> Vec<HeadLink> {
media: row_str(&m, &["媒体", "media", "Media"]),
as_: row_str(&m, &["作为", "as", "As"]),
crossorigin: row_str(&m, &["跨域", "crossorigin", "crossOrigin"]),
defer: row_bool(&m, &["推迟", "defer", "Defer"]),
async_: row_bool(&m, &["异步", "async", "Async"]).unwrap_or(false),
version: row_str(&m, &["版本", "version", "Version", "v"]),
});
}
out
@@ -152,7 +204,7 @@ pub fn head_links_to_json(links: &[HeadLink]) -> Value {
links
.iter()
.map(|l| {
json!({
let mut o = json!({
"rel": l.rel,
"href": l.href,
"type": l.type_,
@@ -160,7 +212,15 @@ pub fn head_links_to_json(links: &[HeadLink]) -> Value {
"media": l.media,
"as": l.as_,
"crossorigin": l.crossorigin,
})
"async": l.async_,
"version": l.version,
});
if let Some(d) = l.defer {
o.as_object_mut()
.unwrap()
.insert("defer".into(), json!(d));
}
o
})
.collect(),
)
@@ -187,6 +247,9 @@ pub fn head_links_from_json(v: &Value) -> Vec<HeadLink> {
media: row_str(m, &["media", "媒体"]),
as_: row_str(m, &["as", "作为"]),
crossorigin: row_str(m, &["crossorigin", "跨域"]),
defer: row_bool(m, &["defer", "推迟"]),
async_: row_bool(m, &["async", "异步"]).unwrap_or(false),
version: row_str(m, &["version", "版本", "v"]),
});
}
out
@@ -194,24 +257,42 @@ pub fn head_links_from_json(v: &Value) -> Vec<HeadLink> {
/// Render HeadLink list to HTML (link / script tags).
pub fn render_head_links(links: &[HeadLink]) -> String {
render_head_links_with_version(links, "")
}
pub fn render_head_links_with_version(links: &[HeadLink], asset_version: &str) -> String {
let mut s = String::new();
for l in links {
let rel = l.rel.trim().to_ascii_lowercase();
let ver = if !l.version.trim().is_empty() {
l.version.as_str()
} else {
asset_version
};
let href = href_with_version(&l.href, ver);
if rel == "script" || rel == "module" {
let mut tag = String::from("<script");
if rel == "module" || l.type_ == "module" {
let is_module = rel == "module" || l.type_ == "module";
if is_module {
tag.push_str(" type=\"module\"");
} else if !l.type_.is_empty() {
tag.push_str(&format!(" type=\"{}\"", esc(&l.type_)));
}
// Modules are deferred by browsers; classic scripts honor explicit defer.
if !is_module && l.defer == Some(true) {
tag.push_str(" defer");
}
if l.async_ {
tag.push_str(" async");
}
if !l.crossorigin.is_empty() {
tag.push_str(&format!(" crossorigin=\"{}\"", esc(&l.crossorigin)));
}
tag.push_str(&format!(" src=\"{}\"></script>", esc(&l.href)));
tag.push_str(&format!(" src=\"{}\"></script>", esc(&href)));
s.push_str(&tag);
continue;
}
let mut tag = format!("<link rel=\"{}\" href=\"{}\"", esc(&l.rel), esc(&l.href));
let mut tag = format!("<link rel=\"{}\" href=\"{}\"", esc(&l.rel), esc(&href));
if !l.type_.is_empty() {
tag.push_str(&format!(" type=\"{}\"", esc(&l.type_)));
}
@@ -295,6 +376,9 @@ pub fn normalize_icons(table: &Value) -> (Value, Vec<HeadLink>, Vec<IconRoute>)
media: String::new(),
as_: String::new(),
crossorigin: String::new(),
defer: None,
async_: false,
version: String::new(),
});
}
@@ -347,6 +431,9 @@ pub fn normalize_icons(table: &Value) -> (Value, Vec<HeadLink>, Vec<IconRoute>)
media: String::new(),
as_: String::new(),
crossorigin: String::new(),
defer: None,
async_: false,
version: String::new(),
},
);
}
@@ -369,6 +456,9 @@ pub fn convention_favicon(static_dir: &Path) -> Option<(Vec<HeadLink>, Vec<IconR
media: String::new(),
as_: String::new(),
crossorigin: String::new(),
defer: None,
async_: false,
version: String::new(),
}];
let routes = vec![IconRoute {
url: "/favicon.ico".into(),
@@ -486,5 +576,32 @@ mod tests {
let h = make_head_html(&t);
assert!(h.contains("rel=\"icon\""));
assert!(h.contains("<script src=\"/static/a.js\"></script>"));
assert!(!h.contains(" defer"), "{h}");
}
#[test]
fn head_script_defer_async_version() {
let t = json!([
{"关系": "script", "地址": "/static/a.js", "推迟": true, "版本": "3"},
{"关系": "module", "地址": "/static/b.js", "版本": "9"},
{"关系": "stylesheet", "地址": "/static/t.css", "版本": "1"},
]);
let h = make_head_html(&t);
assert!(h.contains("<script defer src=\"/static/a.js?v=3\"></script>"), "{h}");
assert!(h.contains("type=\"module\""), "{h}");
assert!(h.contains("src=\"/static/b.js?v=9\""), "{h}");
assert!(h.contains("href=\"/static/t.css?v=1\""), "{h}");
}
#[test]
fn head_asset_version_fallback() {
let links = as_head_links(&json!([
{"关系": "script", "地址": "/static/a.js", "推迟": "真"},
]));
let h = render_head_links_with_version(&links, "2026-09-04");
assert!(
h.contains("<script defer src=\"/static/a.js?v=2026-09-04\"></script>"),
"{h}"
);
}
}
+59 -8
View File
@@ -22,7 +22,7 @@ mod upload;
mod ws;
mod ws_hub;
use crate::table::as_css_named;
use crate::table::as_css_named_checked;
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_void};
@@ -283,6 +283,13 @@ web_ffi!(web_page_new, |args: &Value| {
if let Some(s) = arg_str_opt(args, "layout").or_else(|| arg_str_opt(args, "布局")) {
out.as_object_mut().unwrap().insert("layout".into(), json!(s));
}
if let Some(s) = arg_str_opt(args, "asset_version")
.or_else(|| arg_str_opt(args, "资源版本"))
{
out.as_object_mut()
.unwrap()
.insert("asset_version".into(), json!(s));
}
Ok(out)
});
@@ -355,7 +362,21 @@ web_ffi!(web_page_css, |args: &Value| {
web_ffi!(web_style, |args: &Value| {
let name = arg_str_opt(args, "name").unwrap_or("").to_string();
let table = args.get("table").cloned().unwrap_or(json!([]));
Ok(Value::String(as_css_named(&name, &table)))
let strict = args
.get("strict")
.or_else(|| args.get("strict_css_cells"))
.or_else(|| args.get("严格"))
.map(|v| match v {
Value::Bool(b) => *b,
Value::Number(n) => n.as_i64().unwrap_or(0) != 0,
Value::String(s) => matches!(
s.trim(),
"1" | "true" | "True" | "yes" | "on" | "真" | "是"
),
_ => false,
})
.unwrap_or(false);
as_css_named_checked(&name, &table, strict).map(Value::String)
});
web_ffi!(web_page_detail, |args: &Value| {
@@ -1066,6 +1087,13 @@ web_ffi!(web_app_new, |args: &Value| {
if let Some(s) = arg_str_opt(args, "layout").or_else(|| arg_str_opt(args, "布局")) {
out.as_object_mut().unwrap().insert("layout".into(), json!(s));
}
if let Some(s) = arg_str_opt(args, "asset_version")
.or_else(|| arg_str_opt(args, "资源版本"))
{
out.as_object_mut()
.unwrap()
.insert("asset_version".into(), json!(s));
}
Ok(out)
});
@@ -1642,7 +1670,12 @@ web_ffi!(web_db_table_info, |args: &Value| {
});
fn stamp_page_shell(page: &mut Value, shell_css: Option<&str>, layout: Option<&str>) {
fn stamp_page_shell(
page: &mut Value,
shell_css: Option<&str>,
layout: Option<&str>,
asset_version: Option<&str>,
) {
let Some(obj) = page.as_object_mut() else {
return;
};
@@ -1666,6 +1699,16 @@ fn stamp_page_shell(page: &mut Value, shell_css: Option<&str>, layout: Option<&s
obj.insert("layout".into(), json!(s));
}
}
if let Some(s) = asset_version {
let empty = obj
.get("asset_version")
.and_then(|v| v.as_str())
.unwrap_or("")
.is_empty();
if empty {
obj.insert("asset_version".into(), json!(s));
}
}
}
web_ffi!(web_listen, |args: &Value| {
@@ -2057,11 +2100,15 @@ web_ffi!(web_listen, |args: &Value| {
.get("layout")
.or_else(|| admin_cfg_app.get("布局"))
.and_then(|v| v.as_str());
let app_asset_version = admin_cfg_app
.get("asset_version")
.or_else(|| admin_cfg_app.get("资源版本"))
.and_then(|v| v.as_str());
let mut page = page;
let mut routes = routes;
stamp_page_shell(&mut page, app_shell, app_layout);
stamp_page_shell(&mut page, app_shell, app_layout, app_asset_version);
for (_k, p) in routes.iter_mut() {
stamp_page_shell(p, app_shell, app_layout);
stamp_page_shell(p, app_shell, app_layout, app_asset_version);
}
http::listen(
&page,
@@ -2130,7 +2177,11 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
}
let regs = [
("web_page_new", "title,intro,shell_css,layout", web_page_new as PluginFn),
(
"web_page_new",
"title,intro,shell_css,layout,asset_version",
web_page_new as PluginFn,
),
(
"web_compose_components",
"page,components",
@@ -2239,7 +2290,7 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
("web_media_new", "storage", web_media_new as PluginFn),
(
"web_style",
"name,table",
"name,table,strict",
web_style as PluginFn,
),
(
@@ -2302,7 +2353,7 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
("web_db_list_tables", "url", web_db_list_tables as PluginFn),
(
"web_app_new",
"page,db,admin,host,port,admin_prefix,login_redirect,logout_redirect,shell_css,layout",
"page,db,admin,host,port,admin_prefix,login_redirect,logout_redirect,shell_css,layout,asset_version",
web_app_new as PluginFn,
),
("web_app_route", "app,path,page", web_app_route as PluginFn),
+9 -1
View File
@@ -469,7 +469,15 @@ fn head_html(args: &Value, default_title: &str) -> String {
}
if let Some(head) = args.get("head") {
let links = crate::assets::head_links_from_json(head);
s.push_str(&crate::assets::render_head_links(&links));
let asset_version = args
.get("asset_version")
.or_else(|| args.get("资源版本"))
.and_then(|v| v.as_str())
.unwrap_or("");
s.push_str(&crate::assets::render_head_links_with_version(
&links,
asset_version,
));
}
s
}
+93 -17
View File
@@ -335,20 +335,30 @@ pub fn normalize_slot(name: &str) -> String {
/// | @keyframes pulse from | opacity | 0 |
/// ```
pub fn as_css_named(name: &str, table: &Value) -> String {
as_css_named_checked(name, table, false).unwrap_or_default()
}
/// Like [`as_css_named`], but when `strict` is true, reject cells that look like
/// T5 evaluated a bare `/` (numeric/bool CSS values). Default mode warns on stderr.
pub fn as_css_named_checked(name: &str, table: &Value, strict: bool) -> Result<String, String> {
let name = normalize_ref(name);
if name.is_empty() {
return String::new();
return Ok(String::new());
}
let mut out = String::new();
match table {
Value::Object(m) => {
let sels = pick(m, SEL_KEYS).map(as_str_list).unwrap_or_default();
let props = pick(m, PROP_KEYS).map(as_str_list).unwrap_or_default();
let vals = pick(m, VAL_KEYS).map(as_str_list).unwrap_or_default();
let vals_raw = pick(m, VAL_KEYS);
let vals = vals_raw.map(as_str_list).unwrap_or_default();
let medias = pick(m, MEDIA_KEYS).map(as_str_list).unwrap_or_default();
let n = props.len().max(sels.len()).max(vals.len());
if n == 0 {
return String::new();
return Ok(String::new());
}
if let Some(raw) = vals_raw {
check_css_value_cells(raw, &props, strict)?;
}
let rows: Vec<(String, String, String, String)> = (0..n)
.map(|i| {
@@ -363,23 +373,68 @@ pub fn as_css_named(name: &str, table: &Value) -> String {
emit_css_rows(&rows, &name, &mut out);
}
Value::Array(rows) => {
let rows: Vec<(String, String, String, String)> = rows
.iter()
.filter_map(|row| {
let m = row.as_object()?;
Some((
pick(m, MEDIA_KEYS).map(cell_str).unwrap_or_default(),
pick(m, SEL_KEYS).map(cell_str).unwrap_or_default(),
pick(m, PROP_KEYS).map(cell_str).unwrap_or_default(),
pick(m, VAL_KEYS).map(cell_str).unwrap_or_default(),
))
})
.collect();
emit_css_rows(&rows, &name, &mut out);
let mut collected = Vec::new();
for row in rows {
let Some(m) = row.as_object() else {
continue;
};
let prop = pick(m, PROP_KEYS).map(cell_str).unwrap_or_default();
if let Some(v) = pick(m, VAL_KEYS) {
note_css_value_cell(&prop, v, strict)?;
}
collected.push((
pick(m, MEDIA_KEYS).map(cell_str).unwrap_or_default(),
pick(m, SEL_KEYS).map(cell_str).unwrap_or_default(),
prop,
pick(m, VAL_KEYS).map(cell_str).unwrap_or_default(),
));
}
emit_css_rows(&collected, &name, &mut out);
}
_ => {}
}
out
Ok(out)
}
fn css_value_suspicious(v: &Value) -> Option<&'static str> {
match v {
Value::Number(_) => Some(
"numeric CSS value (likely bare `/` division such as `1 / 5`; quote the cell, e.g. `\"1 / 5\"`)",
),
Value::Bool(_) => Some("boolean CSS value (quote the cell if intentional)"),
_ => None,
}
}
fn note_css_value_cell(prop: &str, val: &Value, strict: bool) -> Result<(), String> {
let Some(why) = css_value_suspicious(val) else {
return Ok(());
};
let prop = if prop.trim().is_empty() {
"(value)"
} else {
prop.trim()
};
let msg = format!("ext/web style: suspicious cell for `{prop}`: {why}");
if strict {
Err(msg)
} else {
eprintln!("warning: {msg}");
Ok(())
}
}
fn check_css_value_cells(vals: &Value, props: &[String], strict: bool) -> Result<(), String> {
match vals {
Value::Array(a) => {
for (i, v) in a.iter().enumerate() {
let prop = props.get(i).map(|s| s.as_str()).unwrap_or("");
note_css_value_cell(prop, v, strict)?;
}
}
other => note_css_value_cell(props.first().map(|s| s.as_str()).unwrap_or(""), other, strict)?,
}
Ok(())
}
/// Parse `@keyframes name` or `@keyframes name stop` from a selector cell.
@@ -742,4 +797,25 @@ mod css_tests {
assert!(css.contains(".x {"), "{css}");
assert!(css.contains("color: red;"), "{css}");
}
#[test]
fn strict_rejects_numeric_css_value() {
let t = json!([
{"选择器": ".x", "属性": "grid-column", "值": 0},
]);
let err = as_css_named_checked("x", &t, true).unwrap_err();
assert!(err.contains("suspicious"), "{err}");
// Non-strict still emits (with warning on stderr).
let css = as_css_named_checked("x", &t, false).unwrap();
assert!(css.contains("grid-column: 0;"), "{css}");
}
#[test]
fn quoted_string_ok_in_strict() {
let t = json!([
{"选择器": ".x", "属性": "grid-column", "值": "1 / 5"},
]);
let css = as_css_named_checked("x", &t, true).unwrap();
assert!(css.contains("grid-column: 1 / 5;"), "{css}");
}
}
+91
View File
@@ -0,0 +1,91 @@
---
title: web C3 style strict + head defer/version
description: Offline markers for quoted CSS cells and head script lifecycle.
import web:ext/web/web.mq.md
import sys:lib/sys.mq.md
---
# main
`好` =
| 选择器 | 属性 | 值 |
|--------|------|-----|
| .box | grid-column | "1 / 5" |
*css = > web.make_style name="t" table=`好` strict=True*
*a = > split value=`css` sep="1 / 5"*
*na = > len value=`a`*
1. `na` > 1
> print text=quoted-css-ok
2. *
> print text=quoted-css-missing
> sys.exit code=1
`头` =
| 关系 | 地址 | 推迟 | 版本 |
|------|------|------|------|
| script | /static/a.js | 真 | 3 |
| stylesheet | /static/t.css | | 1 |
*页 = > web.page title="c3" asset_version="appv"*
*页 = > `页`.head table=`头`*
*html = > `页`.render*
*b = > split value=`html` sep="a.js?v=3"*
*nb = > len value=`b`*
*c = > split value=`html` sep="t.css?v=1"*
*nc = > len value=`c`*
*d0 = > split value=`html` sep="script defer"*
*nd0 = > len value=`d0`*
1. `nb` > 1
1. `nc` > 1
1. `nd0` > 1
> print text=defer-version-ok
2. *
> print text=defer-attr-missing
> sys.exit code=1
2. *
> print text=css-version-missing
> sys.exit code=1
2. *
> print text=defer-script-missing
> sys.exit code=1
`头2` =
| 关系 | 地址 | 推迟 |
|------|------|------|
| script | /static/b.js | 真 |
*页2 = > web.page title="c3b" asset_version="2026-09-04"*
*页2 = > `页2`.head table=`头2`*
*h2 = > `页2`.render*
*d = > split value=`h2` sep="b.js?v=2026-09-04"*
*nd = > len value=`d`*
1. `nd` > 1
> print text=asset-version-ok
2. *
> print text=asset-version-missing
> sys.exit code=1
`头3` =
| 关系 | 地址 |
|------|------|
| script | /static/sync.js |
*页3 = > web.page title="c3c"*
*页3 = > `页3`.head table=`头3`*
*h3 = > `页3`.render*
*e = > split value=`h3` sep="sync.js"*
*ne = > len value=`e`*
*f = > split value=`h3` sep="script defer"*
*nf = > len value=`f`*
1. `ne` > 1
1. `nf` == 1
> print text=sync-compat-ok
2. *
> print text=unexpected-defer
> sys.exit code=1
2. *
> print text=sync-script-missing
> sys.exit code=1
> print text=c3-style-head-ok