feat(web): Go plugin W-G1 assemble/render + SQLite smoke path

Port table/compose/style/render/db/form/app bags, register ABI symbols,
prefer MARQDO_WEB_PLUGIN over ~/.marqdo, and pass web-smoke + web-zh-smoke.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-10 15:27:12 +08:00
1 parent fd3f1724e6
commit 7a0309284a
17 files changed
+4120 -18

No files matched your search

+3 -3
View File
@@ -2,7 +2,7 @@
| | |
|---|---|
| 状态 | **Accepted · 实现进行中(W-G0 完成)** |
| 状态 | **Accepted · 实现进行中(W-G0✅ · W-G1✅ · W-G2 部分)** |
| 日期 | 2026-09-10 |
| 相关 | [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`) |
@@ -386,8 +386,8 @@ scripts/build-web-plugin.sh # go build -buildmode=c-shared -o …/libweb.so
| 波次 | 内容 | 退出条件 |
|------|------|----------|
| **W-G0** | 文档(本文)+ ADR + 目录骨架 + ABI bridge 能 `plugin.load` + `demo` 注册探测 | ✅ `tests/ext/web-go-abi-smoke.mq.md`;`web_go_ready` + `web_page_new`;`scripts/build-web-plugin.sh` → `libweb.so` |
| **W-G1** | table 辅助 + `web_style` + page new/compose/render(无 listen) | `web-smoke` / `web-zh-smoke` |
| **W-G2** | SQLite db CRUD + where + txn + init | `web-select-smoke` / `web-db-w2-smoke` |
| **W-G1** | table 辅助 + `web_style` + page new/compose/render(无 listen) | ✅ `web-smoke` / `web-zh-smoke`(含 compose_form / app_new / app_route 袋) |
| **W-G2** | SQLite db CRUD + where + txn + init | 进行中:`new/init/insert/select/get/exec` 已通 smoke;缺 update/delete/txn/migrate/FTS |
| **W-G3** | form + mount_form + CSRF 基础 | `web-form-*` |
| **W-G4** | `web_listen` + route + static + part + middleware + JSON API | `web-route` / `web-middleware` / live |
| **W-G5** | session/auth/password/rate limit/gate/admin | `web-security` / `web-c0` / `web-c1` |
+15 -1
View File
@@ -1,3 +1,17 @@
module github.com/marqdo/marqdo/plugins/web
go 1.24.5
go 1.25.0
require modernc.org/sqlite v1.34.5
require (
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/sys v0.47.0 // indirect
modernc.org/libc v1.75.6 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.12.1 // indirect
)
+50
View File
@@ -0,0 +1,50 @@
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
modernc.org/cc/v4 v4.29.2 h1:h6+9ciCnPKutf4I03CvheAvDLX7+IHlqR6Iy6J+cgd8=
modernc.org/cc/v4 v4.29.2/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.35.0 h1:F+TUsmw09QxLzmi3aeYYGxjAXarmZaKgj3mKQHNaA8w=
modernc.org/ccgo/v4 v4.35.0/go.mod h1:qrVGs9S3Sr2Ztcg9ve+kTAYMp5a3YvWjo+SoN06kJ5I=
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.1.5 h1:21ldfPfRYE31Tb7B3mwAK8gy1AxP4+dKjrOQPfqakoc=
modernc.org/gc/v3 v3.1.5/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.75.6 h1:yKk8qo+Di4gkmvRboK8ocCqH22FiUCR6jRy2OwtCRus=
modernc.org/libc v1.75.6/go.mod h1:bO5o2ztHxBb2rjz0PgdHN0sSMw57CgxGFLZ3Qd/QpVQ=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.34.5 h1:Bb6SR13/fjp15jt70CL4f18JIN7p7dnMExd+UFnF15g=
modernc.org/sqlite v1.34.5/go.mod h1:YLuNmX9NKs8wRNK2ko1LW1NGYcc9FkBO69JOt1AR9JE=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
+136
View File
@@ -0,0 +1,136 @@
// Package app ports minimal app bag helpers (new + route) for offline smoke.
package app
import (
"fmt"
"strings"
)
// New builds an app bag matching Rust web_app_new defaults used by zh-smoke.
func New(args map[string]any) map[string]any {
page := args["page"]
if page == nil {
page = map[string]any{}
}
dbv := args["db"]
host := strOpt(args, "host", "127.0.0.1")
port := float64(18081)
if v, ok := args["port"]; ok {
switch t := v.(type) {
case float64:
port = t
case string:
// leave default if unparsable
_ = t
}
}
admin := boolish(args["admin"])
adminPrefix := strOpt(args, "admin_prefix", "/admin")
if s := strOpt(args, "后台前缀", ""); s != "" {
adminPrefix = s
}
out := map[string]any{
"page": page,
"db": dbv,
"host": host,
"port": port,
"admin": admin,
"admin_prefix": adminPrefix,
"forms": map[string]any{},
"routes": map[string]any{},
"ws_routes": map[string]any{},
"static_dir": nil,
"static_mount": "/static",
}
if s := strOpt(args, "shell_css", ""); s == "" {
s = strOpt(args, "壳样式", "")
if s != "" {
out["shell_css"] = s
}
} else {
out["shell_css"] = s
}
if s := strOpt(args, "layout", ""); s == "" {
s = strOpt(args, "布局", "")
if s != "" {
out["layout"] = s
}
} else {
out["layout"] = s
}
if s := strOpt(args, "asset_version", ""); s == "" {
s = strOpt(args, "资源版本", "")
if s != "" {
out["asset_version"] = s
}
} else {
out["asset_version"] = s
}
return out
}
// Route registers path → page on app.routes and stamps page._route.
func Route(appBag map[string]any, path string, page any) (map[string]any, error) {
path, err := normalizeRoutePath(path)
if err != nil {
return nil, err
}
out := clone(appBag)
pageMap := map[string]any{}
if m, ok := page.(map[string]any); ok {
pageMap = clone(m)
}
pageMap["_route"] = path
routes := map[string]any{}
if r, ok := out["routes"].(map[string]any); ok {
routes = clone(r)
}
routes[path] = pageMap
out["routes"] = routes
return out, nil
}
func normalizeRoutePath(raw string) (string, error) {
s := strings.TrimSpace(raw)
if s == "" {
return "", fmt.Errorf("empty route path")
}
if !strings.HasPrefix(s, "/") {
s = "/" + s
}
if s != "/" {
s = strings.TrimRight(s, "/")
}
return s, nil
}
func clone(m map[string]any) map[string]any {
out := make(map[string]any, len(m))
for k, v := range m {
out[k] = v
}
return out
}
func strOpt(args map[string]any, key, def string) string {
v, ok := args[key]
if !ok || v == nil {
return def
}
if s, ok := v.(string); ok {
return s
}
return def
}
func boolish(v any) bool {
switch t := v.(type) {
case bool:
return t
case string:
return t == "true" || t == "True" || t == "1" || t == "yes"
case float64:
return t != 0
}
return false
}
+300
View File
@@ -0,0 +1,300 @@
// Package compose ports page assemble helpers from the Rust web plugin.
package compose
import (
"fmt"
"strings"
"github.com/marqdo/marqdo/plugins/web/internal/table"
)
// CallLib loads a lib.member value (host callback).
type CallLib func(path string) (any, error)
func cloneMap(m map[string]any) map[string]any {
if m == nil {
return map[string]any{}
}
out := make(map[string]any, len(m))
for k, v := range m {
out[k] = v
}
return out
}
func asObject(v any) map[string]any {
if m, ok := v.(map[string]any); ok {
return cloneMap(m)
}
return map[string]any{}
}
func strField(m map[string]any, key string) string {
if m == nil {
return ""
}
s, _ := m[key].(string)
return s
}
// ComposeComponents merges layout component rows into a page bag.
func ComposeComponents(page any, layout any, callLib CallLib) (any, error) {
obj := asObject(page)
rows := table.AsCompose(layout)
arr, _ := rows.([]any)
css := strField(obj, "styles_css")
slotClass := map[string]any{}
if sc, ok := obj["slot_class"].(map[string]any); ok {
slotClass = cloneMap(sc)
}
parts := map[string]any{}
composeOut := make([]any, 0, len(arr))
for _, row := range arr {
rm, ok := row.(map[string]any)
if !ok {
continue
}
srcRaw := strField(rm, "src")
styleRaw := strField(rm, "style")
if srcRaw == "" {
continue
}
var name string
var bindTable any
switch sp := table.ParseSitePath(srcRaw); sp.Kind {
case table.SitePathLibMember:
t, err := callLib(sp.Lib + "." + sp.Member)
if err != nil {
return nil, err
}
name = sp.Member
bindTable = t
case table.SitePathPlain:
t, err := callLib(sp.Plain + "." + sp.Plain)
if err != nil {
return nil, err
}
name = sp.Plain
bindTable = t
case table.SitePathDbField:
return nil, fmt.Errorf("component cell cannot be a db field: %s", srcRaw)
}
slot := table.NormalizeSlot(name)
styleName := ""
if styleRaw != "" {
switch sp := table.ParseSitePath(styleRaw); sp.Kind {
case table.SitePathLibMember:
st, err := callLib(sp.Lib + "." + sp.Member)
if err != nil {
return nil, err
}
css += table.AsCSSNamed(sp.Member, st)
styleName = sp.Member
case table.SitePathPlain:
styleName = sp.Plain
case table.SitePathDbField:
styleName = table.NormalizeRef(styleRaw)
}
}
binds := table.AsBind(bindTable)
switch slot {
case "nav":
obj["nav"] = binds
case "sidebar":
obj["sidebar"] = binds
case "footer":
obj["footer"] = binds
default:
obj["main"] = binds
}
if styleName != "" {
slotClass[slot] = styleName
}
composeOut = append(composeOut, map[string]any{
"src": name,
"style": styleName,
"slot": slot,
})
part := map[string]any{
"_type": "page",
"slot": slot,
"fragment": slot,
}
switch slot {
case "nav":
part["nav"] = binds
case "sidebar":
part["sidebar"] = binds
case "footer":
part["footer"] = binds
default:
part["main"] = binds
}
parts[name] = part
}
obj["compose"] = composeOut
if css != "" {
obj["styles_css"] = css
}
if len(slotClass) > 0 {
obj["slot_class"] = slotClass
}
if len(parts) > 0 {
obj["parts"] = parts
}
return obj, nil
}
// ComposeMain merges a main bind table into a page bag.
func ComposeMain(page any, mainTable any, callLib CallLib) (any, error) {
obj := asObject(page)
raw := table.AsBind(mainTable)
arr, _ := raw.([]any)
binds := make([]any, 0, len(arr))
css := strField(obj, "styles_css")
for _, b := range arr {
bm, ok := b.(map[string]any)
if !ok {
continue
}
front := strField(bm, "front")
backRaw := strField(bm, "back")
cssRaw := strField(bm, "css")
var back string
switch sp := table.ParseSitePath(backRaw); sp.Kind {
case table.SitePathDbField:
back = sp.Table + "." + sp.Field
case table.SitePathPlain:
back = sp.Plain
case table.SitePathLibMember:
v, err := callLib(sp.Lib + "." + sp.Member)
if err != nil {
back = sp.Lib + "." + sp.Member
} else if s, ok := v.(string); ok {
back = s
} else {
back = fmt.Sprint(v)
}
}
cssName := ""
switch sp := table.ParseSitePath(cssRaw); sp.Kind {
case table.SitePathLibMember:
st, err := callLib(sp.Lib + "." + sp.Member)
if err != nil {
return nil, err
}
css += table.AsCSSNamed(sp.Member, st)
cssName = sp.Member
case table.SitePathPlain:
cssName = sp.Plain
case table.SitePathDbField:
cssName = table.NormalizeRef(cssRaw)
}
binds = append(binds, map[string]any{
"front": front,
"back": back,
"css": cssName,
})
}
if t, ok := table.BindTableName(binds); ok {
obj["table"] = t
}
obj["main"] = binds
if css != "" {
obj["styles_css"] = css
}
parts := map[string]any{}
if p, ok := obj["parts"].(map[string]any); ok {
parts = cloneMap(p)
}
part := map[string]any{
"_type": "page",
"slot": "main",
"fragment": "main",
"main": binds,
}
if intro, ok := obj["intro"]; ok {
part["intro"] = intro
}
parts["index"] = part
obj["parts"] = parts
return obj, nil
}
// ComposeForm embeds a form into the page main slot.
func ComposeForm(page any, form any, formID string, formTarget *string) (any, error) {
id := strings.TrimSpace(formID)
if id == "" {
return nil, fmt.Errorf("compose_form requires non-empty `id`")
}
obj := asObject(page)
frm := form
if m, ok := form.(map[string]any); ok {
fm := cloneMap(m)
if _, ok := fm["show_meta"]; !ok {
fm["show_meta"] = false
}
if _, ok := fm["title"]; !ok {
fm["title"] = id
}
frm = fm
}
obj["form_id"] = id
obj["form"] = frm
var target *string
if formTarget != nil {
t := strings.TrimSpace(*formTarget)
if t != "" {
target = &t
obj["form_target"] = t
} else {
delete(obj, "form_target")
}
} else {
delete(obj, "form_target")
}
forms := map[string]any{}
if f, ok := obj["forms"].(map[string]any); ok {
forms = cloneMap(f)
}
forms[id] = frm
obj["forms"] = forms
parts := map[string]any{}
if p, ok := obj["parts"].(map[string]any); ok {
parts = cloneMap(p)
}
part := map[string]any{
"_type": "page",
"slot": "main",
"fragment": "main",
"form_id": id,
"form": frm,
}
if target != nil {
part["form_target"] = *target
}
if intro, ok := obj["intro"]; ok {
part["intro"] = intro
}
parts["form_"+id] = part
obj["parts"] = parts
return obj, nil
}
@@ -0,0 +1,68 @@
package compose_test
import (
"testing"
"github.com/marqdo/marqdo/plugins/web/internal/compose"
)
func TestComposeComponentsFakeCallLib(t *testing.T) {
page := map[string]any{
"title": "Home",
}
layout := []any{
map[string]any{"组件": "site.nav", "样式": ""},
map[string]any{"组件": "site.footer", "样式": ""},
}
callLib := func(path string) (any, error) {
switch path {
case "site.nav":
return map[string]any{
"属性": []any{"Home", "About"},
"值": []any{"/", "/about"},
}, nil
case "site.footer":
return []any{
map[string]any{"属性": "©", "值": "/"},
}, nil
default:
t.Fatalf("unexpected callLib %q", path)
return nil, nil
}
}
out, err := compose.ComposeComponents(page, layout, callLib)
if err != nil {
t.Fatal(err)
}
obj := out.(map[string]any)
nav, ok := obj["nav"].([]any)
if !ok || len(nav) != 2 {
t.Fatalf("nav=%v", obj["nav"])
}
n0 := nav[0].(map[string]any)
if n0["front"] != "Home" || n0["back"] != "/" {
t.Fatalf("nav[0]=%v", n0)
}
foot, ok := obj["footer"].([]any)
if !ok || len(foot) != 1 {
t.Fatalf("footer=%v", obj["footer"])
}
comp, ok := obj["compose"].([]any)
if !ok || len(comp) != 2 {
t.Fatalf("compose=%v", obj["compose"])
}
c0 := comp[0].(map[string]any)
if c0["src"] != "nav" || c0["slot"] != "nav" {
t.Fatalf("compose[0]=%v", c0)
}
parts, ok := obj["parts"].(map[string]any)
if !ok {
t.Fatalf("parts missing: %v", obj)
}
if _, ok := parts["nav"]; !ok {
t.Fatalf("parts.nav missing: %v", parts)
}
if _, ok := parts["footer"]; !ok {
t.Fatalf("parts.footer missing: %v", parts)
}
}
+699
View File
@@ -0,0 +1,699 @@
// Package db ports minimal SQLite CRUD from the Rust web plugin (sqlite: URLs).
package db
import (
"database/sql"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/marqdo/marqdo/plugins/web/internal/table"
_ "modernc.org/sqlite"
)
var (
poolMu sync.Mutex
pool = map[string]*sql.DB{}
)
// ResolveURL normalizes sqlite: paths. Absolute paths stay; relative stay as given
// (caller / host resolve cwd). Always returns a sqlite:… URL when prefixed.
func ResolveURL(url string) string {
lower := strings.ToLower(url)
if strings.HasPrefix(lower, "postgres://") || strings.HasPrefix(lower, "postgresql://") {
return url
}
stripped := url
prefix := ""
if strings.HasPrefix(url, "sqlite:") {
stripped = strings.TrimPrefix(url, "sqlite:")
prefix = "sqlite:"
} else if strings.HasPrefix(url, "SQLITE:") {
stripped = strings.TrimPrefix(url, "SQLITE:")
prefix = "SQLITE:"
}
if prefix == "" {
return stripped
}
return prefix + stripped
}
func pathOf(url string) string {
u := ResolveURL(url)
if strings.HasPrefix(u, "sqlite:") {
return strings.TrimPrefix(u, "sqlite:")
}
if strings.HasPrefix(u, "SQLITE:") {
return strings.TrimPrefix(u, "SQLITE:")
}
return u
}
func open(url string) (*sql.DB, error) {
path := pathOf(url)
poolMu.Lock()
defer poolMu.Unlock()
key := ResolveURL(url)
if db, ok := pool[key]; ok {
return db, nil
}
if parent := filepath.Dir(path); parent != "" && parent != "." {
if err := os.MkdirAll(parent, 0o755); err != nil {
return nil, err
}
}
db, err := sql.Open("sqlite", path)
if err != nil {
return nil, err
}
if _, err := db.Exec(`PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;`); err != nil {
_ = db.Close()
return nil, err
}
pool[key] = db
return db, nil
}
// ResetPool closes pooled connections (tests).
func ResetPool() {
poolMu.Lock()
defer poolMu.Unlock()
for k, db := range pool {
_ = db.Close()
delete(pool, k)
}
}
func ident(s string) (string, error) {
s = strings.TrimSpace(s)
if s == "" {
return "", fmt.Errorf("bad identifier `%s`", s)
}
for _, c := range s {
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_') {
return "", fmt.Errorf("bad identifier `%s`", s)
}
}
return s, nil
}
func sqlType(t string) string {
switch strings.ToLower(strings.TrimSpace(t)) {
case "int", "integer":
return "INTEGER"
case "real", "float", "double":
return "REAL"
case "blob":
return "BLOB"
case "timestamp", "datetime", "timestamptz", "审计":
return "TEXT"
default:
return "TEXT"
}
}
func cellStr(v any) string {
switch t := v.(type) {
case nil:
return ""
case string:
return t
case bool:
return strconv.FormatBool(t)
case float64:
if t == float64(int64(t)) {
return strconv.FormatInt(int64(t), 10)
}
return strconv.FormatFloat(t, 'f', -1, 64)
case int:
return strconv.Itoa(t)
case int64:
return strconv.FormatInt(t, 10)
default:
return fmt.Sprint(t)
}
}
func boolField(m map[string]any, keys []string, def bool) bool {
for _, k := range keys {
v, ok := m[k]
if !ok {
continue
}
switch t := v.(type) {
case bool:
return t
case string:
switch t {
case "true", "True", "1", "yes", "是", "可", "唯一", "索引":
return true
case "false", "False", "0", "no", "否":
return false
}
case float64:
return int64(t) != 0
}
}
return def
}
func parseFK(raw string) (string, string, error) {
s := strings.TrimSpace(raw)
if s == "" {
return "", "", fmt.Errorf("empty foreign key")
}
if i := strings.IndexByte(s, '('); i >= 0 {
t, err := ident(s[:i])
if err != nil {
return "", "", err
}
col := strings.TrimSpace(strings.TrimSuffix(s[i+1:], ")"))
if col == "" {
return t, "id", nil
}
c, err := ident(col)
return t, c, err
}
if i := strings.IndexByte(s, '.'); i >= 0 {
t, err := ident(s[:i])
if err != nil {
return "", "", err
}
c, err := ident(s[i+1:])
return t, c, err
}
t, err := ident(s)
return t, "id", err
}
func utcNowISO() string {
return time.Now().UTC().Format("2006-01-02T15:04:05Z")
}
// Init creates a table from AsFields-shaped schema.
// Returns {"_type":"db_table","name":table,"url":url}.
func Init(url, name string, fields any) (map[string]any, error) {
tableName, err := ident(name)
if err != nil {
return nil, err
}
colsAny := table.AsFields(fields)
arr, ok := colsAny.([]any)
if !ok {
return nil, fmt.Errorf("fields must be a list")
}
if len(arr) == 0 {
return nil, fmt.Errorf("empty fields")
}
var parts []string
var indexSQL []string
hasPK := false
for _, c := range arr {
m, ok := c.(map[string]any)
if !ok {
continue
}
nm := cellStr(m["name"])
if nm == "" {
nm = cellStr(m["字段"])
}
colName, err := ident(nm)
if err != nil {
return nil, err
}
ty := cellStr(m["type"])
if ty == "" {
ty = cellStr(m["类型"])
}
if ty == "" {
ty = "text"
}
nullable := boolField(m, []string{"nullable", "可空"}, true)
unique := boolField(m, []string{"unique", "唯一"}, false)
index := boolField(m, []string{"index", "索引"}, false)
col := fmt.Sprintf(`"%s" %s`, colName, sqlType(ty))
if colName == "id" && !hasPK {
col += " PRIMARY KEY"
if sqlType(ty) == "INTEGER" {
col += " AUTOINCREMENT"
}
hasPK = true
} else if !nullable {
col += " NOT NULL"
}
if unique && colName != "id" {
col += " UNIQUE"
}
fkRaw := cellStr(m["fk"])
if fkRaw == "" {
fkRaw = cellStr(m["外键"])
}
if fkRaw != "" {
rt, rc, err := parseFK(fkRaw)
if err != nil {
return nil, err
}
col += fmt.Sprintf(` REFERENCES "%s"("%s")`, rt, rc)
}
parts = append(parts, col)
if (index || unique) && colName != "id" {
kind := ""
if unique {
kind = "UNIQUE "
}
indexSQL = append(indexSQL, fmt.Sprintf(
`CREATE %sINDEX IF NOT EXISTS "idx_%s_%s" ON "%s" ("%s")`,
kind, tableName, colName, tableName, colName,
))
}
}
sqlStmt := fmt.Sprintf(`CREATE TABLE IF NOT EXISTS "%s" (%s)`, tableName, strings.Join(parts, ", "))
db, err := open(url)
if err != nil {
return nil, err
}
if _, err := db.Exec(sqlStmt); err != nil {
return nil, err
}
for _, stmt := range indexSQL {
if _, err := db.Exec(stmt); err != nil {
return nil, err
}
}
return map[string]any{
"_type": "db_table",
"name": tableName,
"url": ResolveURL(url),
}, nil
}
func columnNames(db *sql.DB, tableName string) ([]string, error) {
rows, err := db.Query(fmt.Sprintf(`PRAGMA table_info("%s")`, tableName))
if err != nil {
return nil, err
}
defer rows.Close()
var out []string
for rows.Next() {
var cid int
var name, ctype string
var notnull, pk int
var dflt any
if err := rows.Scan(&cid, &name, &ctype, &notnull, &dflt, &pk); err != nil {
return nil, err
}
out = append(out, name)
}
return out, rows.Err()
}
func toSQLArg(v any) any {
switch t := v.(type) {
case nil:
return nil
case bool:
if t {
return int64(1)
}
return int64(0)
case float64:
if t == float64(int64(t)) {
return int64(t)
}
return t
case string:
s := strings.TrimSpace(t)
if i, err := strconv.ParseInt(s, 10, 64); err == nil {
return i
}
if f, err := strconv.ParseFloat(s, 64); err == nil && strings.Contains(s, ".") && !strings.ContainsAny(s, "eE") {
return f
}
return t
case int:
return int64(t)
case int64:
return t
default:
return fmt.Sprint(t)
}
}
func fromSQL(v any) any {
switch t := v.(type) {
case nil:
return nil
case int64:
return float64(t) // JSON numbers are float64
case float64:
return t
case bool:
return t
case []byte:
return string(t)
case string:
return t
default:
return fmt.Sprint(t)
}
}
// Insert inserts row maps. Returns {"ok":true,"inserted":n}.
func Insert(url, tableName string, rows any) (map[string]any, error) {
tn, err := ident(tableName)
if err != nil {
return nil, err
}
db, err := open(url)
if err != nil {
return nil, err
}
colsPresent, err := columnNames(db, tn)
if err != nil {
return nil, err
}
hasCreated, hasUpdated := false, false
for _, c := range colsPresent {
if c == "created_at" {
hasCreated = true
}
if c == "updated_at" {
hasUpdated = true
}
}
normalized := table.AsRows(rows)
arr, ok := normalized.([]any)
if !ok {
return nil, fmt.Errorf("rows must be a list")
}
now := utcNowISO()
var n int64
for _, row := range arr {
obj, ok := row.(map[string]any)
if !ok {
return nil, fmt.Errorf("row must be a map")
}
var cols, placeholders []string
var vals []any
seenCreated, seenUpdated := false, false
for k, v := range obj {
if k == "@" || k == "行" || k == "row" {
continue
}
if _, err := ident(k); err != nil {
return nil, err
}
if k == "created_at" {
seenCreated = true
}
if k == "updated_at" {
seenUpdated = true
}
cols = append(cols, `"`+k+`"`)
placeholders = append(placeholders, "?")
vals = append(vals, toSQLArg(v))
}
if hasCreated && !seenCreated {
cols = append(cols, `"created_at"`)
placeholders = append(placeholders, "?")
vals = append(vals, now)
}
if hasUpdated && !seenUpdated {
cols = append(cols, `"updated_at"`)
placeholders = append(placeholders, "?")
vals = append(vals, now)
}
if len(cols) == 0 {
continue
}
sqlStmt := fmt.Sprintf(
`INSERT INTO "%s" (%s) VALUES (%s)`,
tn, strings.Join(cols, ", "), strings.Join(placeholders, ", "),
)
if _, err := db.Exec(sqlStmt, vals...); err != nil {
return nil, err
}
n++
}
return map[string]any{"ok": true, "inserted": float64(n)}, nil
}
func skipWhereKey(k string) bool {
return k == "@" || k == "行" || k == "row" || strings.HasPrefix(k, "_")
}
func whereOp(raw string) (string, error) {
switch strings.ToLower(strings.TrimSpace(raw)) {
case "", "=", "eq", "==", "等于":
return "=", nil
case "!=", "<>", "ne", "不等于":
return "!=", nil
case ">", "gt", "大于":
return ">", nil
case ">=", "gte", "大于等于":
return ">=", nil
case "<", "lt", "小于":
return "<", nil
case "<=", "lte", "小于等于":
return "<=", nil
case "like", "contains", "包含", "匹配":
return "LIKE", nil
default:
return "", fmt.Errorf("unsupported where op `%s`", raw)
}
}
func parseWhere(where any) (exprs []string, vals []any, err error) {
if where == nil {
return nil, nil, nil
}
if s, ok := where.(string); ok {
if s == "" || strings.EqualFold(s, "none") || strings.EqualFold(s, "null") {
return nil, nil, nil
}
}
w := table.AsRows(where)
arr, ok := w.([]any)
if !ok {
return nil, nil, fmt.Errorf("where must be a map or filter table")
}
for _, item := range arr {
m, ok := item.(map[string]any)
if !ok {
return nil, nil, fmt.Errorf("where must be a map or filter table")
}
field := ""
for _, k := range []string{"field", "字段", "列"} {
if v, ok := m[k]; ok {
field = cellStr(v)
break
}
}
_, hasVal := m["value"]
if !hasVal {
_, hasVal = m["值"]
}
_, hasOp := m["op"]
if !hasOp {
_, hasOp = m["操作"]
}
if field != "" && (hasVal || hasOp) {
col, err := ident(field)
if err != nil {
return nil, nil, err
}
opRaw := ""
if v, ok := m["op"]; ok {
opRaw = cellStr(v)
} else if v, ok := m["操作"]; ok {
opRaw = cellStr(v)
}
op, err := whereOp(opRaw)
if err != nil {
return nil, nil, err
}
var val any
if v, ok := m["value"]; ok {
val = v
} else if v, ok := m["值"]; ok {
val = v
}
exprs = append(exprs, fmt.Sprintf(`"%s" %s ?`, col, op))
vals = append(vals, toSQLArg(val))
continue
}
for k, v := range m {
if skipWhereKey(k) {
continue
}
col, err := ident(k)
if err != nil {
return nil, nil, err
}
exprs = append(exprs, fmt.Sprintf(`"%s" = ?`, col))
vals = append(vals, toSQLArg(v))
}
}
return exprs, vals, nil
}
func scanRows(rows *sql.Rows) ([]any, error) {
cols, err := rows.Columns()
if err != nil {
return nil, err
}
var out []any
for rows.Next() {
raw := make([]any, len(cols))
ptrs := make([]any, len(cols))
for i := range raw {
ptrs[i] = &raw[i]
}
if err := rows.Scan(ptrs...); err != nil {
return nil, err
}
m := map[string]any{}
for i, name := range cols {
m[name] = fromSQL(raw[i])
}
out = append(out, m)
}
return out, rows.Err()
}
// SelectOpts controls select_order behavior.
type SelectOpts struct {
Where any
Order string
Offset *int64
}
// Select runs SELECT * FROM table with optional where/order/offset.
// Without offset: {"rows":[…]}; with offset: {"rows":[…],"total":N}.
func Select(url, tableName string, limit int64, opts SelectOpts) (map[string]any, error) {
tn, err := ident(tableName)
if err != nil {
return nil, err
}
exprs, vals, err := parseWhere(opts.Where)
if err != nil {
return nil, err
}
db, err := open(url)
if err != nil {
return nil, err
}
sqlStmt := fmt.Sprintf(`SELECT * FROM "%s"`, tn)
whereSQL := ""
if len(exprs) > 0 {
whereSQL = " WHERE " + strings.Join(exprs, " AND ")
sqlStmt += whereSQL
}
if order := strings.TrimSpace(opts.Order); order != "" {
parts := strings.Split(order, ",")
var orderExprs []string
for _, part := range parts {
part = strings.TrimSpace(part)
if part == "" {
continue
}
dir := ""
col := part
if strings.HasPrefix(part, "-") {
col = part[1:]
dir = " DESC"
}
c, err := ident(col)
if err != nil {
return nil, err
}
orderExprs = append(orderExprs, fmt.Sprintf(`"%s"%s`, c, dir))
}
if len(orderExprs) > 0 {
sqlStmt += " ORDER BY " + strings.Join(orderExprs, ", ")
}
}
sqlStmt += " LIMIT ?"
vals = append(vals, limit)
if opts.Offset != nil && *opts.Offset > 0 {
sqlStmt += " OFFSET ?"
vals = append(vals, *opts.Offset)
}
rows, err := db.Query(sqlStmt, vals...)
if err != nil {
return nil, err
}
defer rows.Close()
list, err := scanRows(rows)
if err != nil {
return nil, err
}
if list == nil {
list = []any{}
}
if opts.Offset != nil {
countSQL := fmt.Sprintf(`SELECT COUNT(*) FROM "%s"%s`, tn, whereSQL)
_, whereOnly, _ := parseWhere(opts.Where)
var total int64
if err := db.QueryRow(countSQL, whereOnly...).Scan(&total); err != nil {
total = int64(len(list))
}
return map[string]any{"rows": list, "total": float64(total)}, nil
}
return map[string]any{"rows": list}, nil
}
// Get returns one row by id, or nil (JSON null).
func Get(url, tableName, id string) (any, error) {
tn, err := ident(tableName)
if err != nil {
return nil, err
}
db, err := open(url)
if err != nil {
return nil, err
}
sqlStmt := fmt.Sprintf(`SELECT * FROM "%s" WHERE "id" = ? LIMIT 1`, tn)
rows, err := db.Query(sqlStmt, toSQLArg(id))
if err != nil {
return nil, err
}
defer rows.Close()
list, err := scanRows(rows)
if err != nil {
return nil, err
}
if len(list) == 0 {
return nil, nil
}
return list[0], nil
}
// Exec runs a non-SELECT statement. Returns {"ok":true,"changes":N}.
func Exec(url, sqlStmt string, args any) (map[string]any, error) {
db, err := open(url)
if err != nil {
return nil, err
}
var vals []any
switch t := args.(type) {
case []any:
for _, v := range t {
vals = append(vals, toSQLArg(v))
}
case nil:
// none
default:
vals = append(vals, toSQLArg(t))
}
res, err := db.Exec(sqlStmt, vals...)
if err != nil {
return nil, err
}
n, _ := res.RowsAffected()
return map[string]any{"ok": true, "changes": float64(n)}, nil
}
+75
View File
@@ -0,0 +1,75 @@
package db_test
import (
"os"
"path/filepath"
"testing"
"github.com/marqdo/marqdo/plugins/web/internal/db"
)
func TestInitInsertSelectGet(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "t.db")
url := "sqlite:" + path
defer db.ResetPool()
fields := []any{
map[string]any{"name": "id", "type": "integer", "nullable": false},
map[string]any{"name": "title", "type": "text", "nullable": false},
map[string]any{"name": "body", "type": "text", "nullable": true},
}
initOut, err := db.Init(url, "articles", fields)
if err != nil {
t.Fatal(err)
}
if initOut["_type"] != "db_table" || initOut["name"] != "articles" {
t.Fatalf("init=%v", initOut)
}
if _, err := os.Stat(path); err != nil {
t.Fatal(err)
}
ins, err := db.Insert(url, "articles", []any{
map[string]any{"id": float64(1), "title": "Hello Marqdo", "body": "First"},
map[string]any{"id": float64(2), "title": "Two", "body": "Second"},
})
if err != nil {
t.Fatal(err)
}
if ins["ok"] != true || ins["inserted"] != float64(2) {
t.Fatalf("insert=%v", ins)
}
sel, err := db.Select(url, "articles", 10, db.SelectOpts{})
if err != nil {
t.Fatal(err)
}
rows, ok := sel["rows"].([]any)
if !ok || len(rows) != 2 {
t.Fatalf("select=%v", sel)
}
if _, hasTotal := sel["total"]; hasTotal {
t.Fatalf("unexpected total without offset: %v", sel)
}
got, err := db.Get(url, "articles", "1")
if err != nil {
t.Fatal(err)
}
m, ok := got.(map[string]any)
if !ok {
t.Fatalf("get=%v", got)
}
if m["title"] != "Hello Marqdo" {
t.Fatalf("title=%v", m["title"])
}
miss, err := db.Get(url, "articles", "999")
if err != nil {
t.Fatal(err)
}
if miss != nil {
t.Fatalf("expected null, got %v", miss)
}
}
+110
View File
@@ -0,0 +1,110 @@
// Package form ports minimal form bag helpers for assemble smoke (W-G1/W-G3 start).
package form
import "github.com/marqdo/marqdo/plugins/web/internal/table"
// New matches Rust form_new.
func New(tableName, action, id string) map[string]any {
out := map[string]any{
"_type": "form",
"action": action,
"fields": []any{},
"rules": []any{},
}
if action == "" {
out["action"] = "insert"
}
if tableName != "" {
out["table"] = tableName
}
if id != "" {
out["id"] = id
}
return out
}
// SetFields attaches normalized field rows to the form bag.
func SetFields(formBag map[string]any, fields any) map[string]any {
out := map[string]any{}
for k, v := range formBag {
out[k] = v
}
out["fields"] = normalizeFormFields(fields)
return out
}
func normalizeFormFields(fields any) []any {
// Prefer list-of-maps shape from GFM @ tables; fall back to AsFields-like maps.
switch t := fields.(type) {
case []any:
var out []any
for _, row := range t {
m, ok := row.(map[string]any)
if !ok {
continue
}
name := pickStr(m, "字段", "name", "列", "column")
if name == "" {
continue
}
item := map[string]any{
"name": name,
"label": pickStr(m, "标签", "label", "title"),
"type": pickStrDef(m, "text", "类型", "type"),
}
if v, ok := m["必填"]; ok {
item["required"] = boolish(v)
} else if v, ok := m["required"]; ok {
item["required"] = boolish(v)
}
if v, ok := m["默认"]; ok {
item["default"] = v
} else if v, ok := m["default"]; ok {
item["default"] = v
}
out = append(out, item)
}
if len(out) > 0 {
return out
}
}
// Columnar / schema fallback
af := table.AsFields(fields)
if arr, ok := af.([]any); ok {
return arr
}
return []any{}
}
func pickStr(m map[string]any, keys ...string) string {
for _, k := range keys {
if v, ok := m[k]; ok && v != nil {
if s, ok := v.(string); ok {
return s
}
}
}
return ""
}
func pickStrDef(m map[string]any, def string, keys ...string) string {
if s := pickStr(m, keys...); s != "" {
return s
}
return def
}
func boolish(v any) bool {
switch t := v.(type) {
case bool:
return t
case string:
switch t {
case "1", "true", "True", "yes", "是", "可":
return true
}
case float64:
return t != 0
}
return false
}
+881
View File
@@ -0,0 +1,881 @@
// Package render ports HTML shell rendering from the Rust web plugin.
package render
import (
"fmt"
"strings"
"github.com/marqdo/marqdo/plugins/web/internal/db"
"github.com/marqdo/marqdo/plugins/web/internal/table"
)
func esc(s string) string {
r := strings.NewReplacer(
"&", "&amp;",
"<", "&lt;",
">", "&gt;",
`"`, "&quot;",
)
return r.Replace(s)
}
func text(v any) string {
switch t := v.(type) {
case nil:
return ""
case string:
return t
case bool:
if t {
return "true"
}
return "false"
case float64:
if t == float64(int64(t)) {
return fmt.Sprintf("%d", int64(t))
}
return fmt.Sprint(t)
default:
return fmt.Sprint(t)
}
}
func classAttr(css string) string {
if css == "" {
return ""
}
return fmt.Sprintf(` class="%s"`, esc(css))
}
func isSimpleIdent(s string) bool {
if s == "" {
return false
}
for _, c := range s {
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' {
continue
}
if c > 127 {
continue
}
return false
}
return true
}
func isDBBindBack(back string) bool {
s := table.NormalizeRef(back)
if s == "" || strings.Contains(s, "://") || strings.HasPrefix(s, "/") ||
strings.HasPrefix(s, "#") || strings.HasPrefix(s, "?") {
return false
}
sp := table.ParseSitePath(s)
switch sp.Kind {
case table.SitePathDbField:
return true
case table.SitePathLibMember:
return isSimpleIdent(sp.Lib) && isSimpleIdent(sp.Member)
case table.SitePathPlain:
parts := strings.Split(sp.Plain, ".")
n := 0
for _, p := range parts {
if p != "" {
n++
if !isSimpleIdent(p) {
return false
}
}
}
return n == 2
}
return false
}
type navLink struct {
label string
href string
class string
media string
}
type navWhen int
const (
navAlways navWhen = iota
navHide
navAuth
navGuest
)
func parseNavWhen(raw string) navWhen {
t := strings.TrimSpace(raw)
switch t {
case "", "*", "always", "Always", "真", "yes", "on", "show", "all":
return navAlways
case "hide", "never", "off", "no", "假", "否", "0", "false", "False":
return navHide
case "auth", "user", "登录", "已登录", "logged_in", "logged-in":
return navAuth
case "guest", "anon", "anonymous", "访客", "匿名", "未登录":
return navGuest
default:
return navAlways
}
}
func pageAuthState(page map[string]any) *bool {
if page == nil {
return nil
}
for _, k := range []string{"_nav_user", "user", "username", "_user"} {
if v, ok := page[k]; ok {
b := false
switch t := v.(type) {
case nil:
b = false
case bool:
b = t
case string:
b = strings.TrimSpace(t) != ""
case float64:
b = int64(t) != 0
default:
b = true
}
return &b
}
}
for _, k := range []string{"_logged_in", "logged_in"} {
if v, ok := page[k]; ok {
switch t := v.(type) {
case bool:
return &t
case string:
b := false
switch strings.TrimSpace(t) {
case "1", "true", "True", "yes", "on", "真", "是":
b = true
}
return &b
case float64:
b := int64(t) != 0
return &b
}
}
}
return nil
}
func navWhenVisible(when navWhen, auth *bool) bool {
switch when {
case navAlways:
return true
case navHide:
return false
case navAuth:
if auth == nil {
return true
}
return *auth
case navGuest:
if auth == nil {
return true
}
return !*auth
}
return true
}
func selectPageData(url, tableName string, page map[string]any, limit, offset int64) map[string]any {
var where any
if q, ok := page["query"]; ok {
where = q
}
order, _ := page["order"].(string)
opts := db.SelectOpts{Where: where, Order: order}
if _, ok := page["paginate"]; ok || offset > 0 {
opts.Offset = &offset
}
out, err := db.Select(url, tableName, limit, opts)
if err != nil {
return map[string]any{"rows": []any{}}
}
return out
}
func resolveLinks(raw any, dbURL string, page map[string]any) []navLink {
if raw == nil {
return nil
}
auth := pageAuthState(page)
bindsAny := table.AsBind(raw)
arr, _ := bindsAny.([]any)
var rows []map[string]any
if len(arr) > 0 {
hasDB := false
for _, b := range arr {
m, _ := b.(map[string]any)
back, _ := m["back"].(string)
if isDBBindBack(back) {
hasDB = true
break
}
}
if hasDB {
if dbURL == "" {
return nil
}
tn, ok := table.BindTableName(arr)
if !ok {
return nil
}
data := selectPageData(dbURL, tn, map[string]any{}, 200, 0)
rawRows, _ := data["rows"].([]any)
projected := table.ProjectRows(arr, rawRows)
parr, _ := projected.([]any)
for _, it := range parr {
if m, ok := it.(map[string]any); ok {
rows = append(rows, m)
}
}
} else {
for _, b := range arr {
if m, ok := b.(map[string]any); ok {
rows = append(rows, m)
}
}
}
} else {
rows = table.AsNavRows(raw)
}
var out []navLink
for _, m := range rows {
label, href := table.NavLabelHref(m)
if label == "" {
continue
}
media, whenRaw, class := table.NavMediaWhenClass(m)
if whenRaw == "" {
if v, ok := m["when"]; ok {
whenRaw = text(v)
} else if v, ok := m["当"]; ok {
whenRaw = text(v)
}
}
if media == "" {
if v, ok := m["media"]; ok {
media = text(v)
} else if v, ok := m["媒体"]; ok {
media = text(v)
}
}
when := parseNavWhen(whenRaw)
if !navWhenVisible(when, auth) {
continue
}
out = append(out, navLink{label: label, href: href, class: class, media: media})
}
return out
}
func navMediaClassMapMany(groups ...[]navLink) (string, [][2]string) {
var pairs [][2]string
var css strings.Builder
for _, links := range groups {
for _, link := range links {
media := strings.TrimSpace(link.media)
if media == "" {
continue
}
dup := false
for _, p := range pairs {
if p[0] == media {
dup = true
break
}
}
if dup {
continue
}
class := fmt.Sprintf("nav-mq-%d", len(pairs))
css.WriteString(fmt.Sprintf(
"@media not %s { li.%s { display:none !important; } }\n",
media, class,
))
pairs = append(pairs, [2]string{media, class})
}
}
return css.String(), pairs
}
func renderULWithMQ(links []navLink, class string, mqPairs [][2]string) string {
var s strings.Builder
s.WriteString(fmt.Sprintf(`<ul class="%s">`, esc(class)))
for _, link := range links {
mq := strings.TrimSpace(link.media)
mqClass := ""
if mq != "" {
for _, p := range mqPairs {
if p[0] == mq {
mqClass = p[1]
break
}
}
}
liClass := link.class
if mqClass != "" {
if liClass != "" {
liClass += " "
}
liClass += mqClass
}
if liClass == "" {
s.WriteString(fmt.Sprintf(`<li><a href="%s">%s</a></li>`, esc(link.href), esc(link.label)))
} else {
s.WriteString(fmt.Sprintf(
`<li class="%s"><a href="%s">%s</a></li>`,
esc(liClass), esc(link.href), esc(link.label),
))
}
}
s.WriteString("</ul>")
return s.String()
}
func resolveMain(page map[string]any, dbURL string) (intro string, items []map[string]any, total *int64) {
intro, _ = page["intro"].(string)
main, ok := page["main"]
if !ok {
return intro, nil, nil
}
bindsAny := table.AsBind(main)
arr, _ := bindsAny.([]any)
if len(arr) == 0 {
return intro, nil, nil
}
if dbURL == "" {
return intro, nil, nil
}
tn, ok := table.BindTableName(arr)
if !ok {
return intro, nil, nil
}
limit := int64(200)
offset := int64(0)
if p, ok := page["paginate"].(map[string]any); ok {
if v, ok := p["limit"].(float64); ok {
limit = int64(v)
}
if v, ok := p["offset"].(float64); ok {
offset = int64(v)
}
}
data := selectPageData(dbURL, tn, page, limit, offset)
if t, ok := data["total"].(float64); ok {
ti := int64(t)
total = &ti
}
rawRows, _ := data["rows"].([]any)
projected := table.ProjectRows(arr, rawRows)
parr, _ := projected.([]any)
for _, v := range parr {
if m, ok := v.(map[string]any); ok {
items = append(items, m)
}
}
return intro, items, total
}
func fieldCSS(obj map[string]any, field string) string {
css, _ := obj["_css"].(map[string]any)
if css == nil {
return ""
}
s, _ := css[field].(string)
return s
}
func partSrcPrefix(page map[string]any) string {
r, _ := page["_route"].(string)
if r == "" || r == "/" {
return ""
}
for len(r) > 1 && strings.HasSuffix(r, "/") {
r = r[:len(r)-1]
}
if strings.HasPrefix(r, "/") {
return r
}
return "/" + r
}
func slotAttrs(slot string, parts map[string]any, page map[string]any) string {
prefix := partSrcPrefix(page)
a := fmt.Sprintf(` data-slot="%s"`, esc(slot))
for id, cfg := range parts {
cm, ok := cfg.(map[string]any)
if !ok {
continue
}
s, _ := cm["slot"].(string)
if s == "" {
s, _ = cm["fragment"].(string)
}
if s == slot || (slot == "sidebar" && id == "side") || (slot == "main" && id == "index") {
a += fmt.Sprintf(` data-slot-src="%s/_part/%s"`, esc(prefix), esc(id))
break
}
}
return a
}
func slotClass(page map[string]any, slot, base string) string {
extra := ""
if sc, ok := page["slot_class"].(map[string]any); ok {
extra, _ = sc[slot].(string)
}
if extra == "" {
return base
}
return base + " " + extra
}
const shellVars = `
:root { --ink:#1c1917; --muted:#57534e; --paper:#fafaf9; --line:#e7e5e4; --accent:#0f766e; }
body { margin:0; font-family: "IBM Plex Sans", "Noto Sans SC", sans-serif; background:var(--paper); color:var(--ink); }
a { color:var(--ink); text-decoration:none; }
a:hover { color:var(--accent); }
`
const shellLayout = `
body { display:grid; min-height:100vh; grid-template-rows:auto 1fr auto; }
body.has-sidebar { grid-template-columns:14rem 1fr; grid-template-areas:"top top" "side main" "foot foot"; }
body.no-sidebar { grid-template-areas:"top" "main" "foot"; }
@media (max-width:720px) {
body.has-sidebar { grid-template-columns:1fr; grid-template-areas:"top" "main" "foot" "side"; }
body.has-sidebar aside.side { border-right:0; border-top:1px solid var(--line); }
}
body.layout-stacked { display:flex; flex-direction:column; min-height:100vh; }
body.layout-stacked header.topnav, body.layout-stacked aside.side, body.layout-stacked main.main, body.layout-stacked footer.foot { width:100%; }
body.layout-stacked aside.side { border-right:0; border-bottom:1px solid var(--line); }
body.layout-bare { display:block; min-height:100vh; }
body.layout-bare main.main { padding:1.5rem 1.25rem 2rem; }
header.topnav { grid-area:top; border-bottom:1px solid var(--line); padding:.85rem 1.25rem; background:#fff; }
aside.side { grid-area:side; border-right:1px solid var(--line); padding:1.25rem 1rem; background:#f5f5f4; }
main.main { grid-area:main; padding:1.5rem 1.25rem 2rem; }
footer.foot { grid-area:foot; border-top:1px solid var(--line); padding:.85rem 1.25rem; color:var(--muted); background:#fff; }
ul.nav, ul.side-nav, ul.foot-nav { list-style:none; margin:0; padding:0; display:flex; flex-wrap:wrap; gap:.35rem 1rem; }
ul.side-nav { flex-direction:column; }
`
const shellWidgets = `
.content.cards { display:grid; gap:1rem; margin-top:1.25rem; grid-template-columns:repeat(auto-fill,minmax(16rem,1fr)); }
.content.cards article { background:#fff; border:1px solid var(--line); border-radius:6px; padding:1rem; }
.main-intro h1 { margin:0 0 .75rem; font-size:2rem; }
.main-intro p { color:var(--muted); }
.site-form { margin-top:1.25rem; max-width:28rem; }
.article { background:#fff; border:1px solid var(--line); border-radius:8px; padding:2rem; margin-top:1.5rem; }
.article-title { margin:0 0 .75rem; font-size:2rem; }
.pagination { display:flex; gap:1rem; align-items:center; margin:1.5rem 0; font-size:.95rem; }
`
func shellCSSFor(mode string) string {
switch strings.ToLower(strings.TrimSpace(mode)) {
case "off", "none", "false", "0":
return ""
case "minimal", "min", "vars":
return shellVars
default:
return shellVars + shellLayout + shellWidgets
}
}
func resolveShellCSS(page map[string]any) string {
raw := "full"
if s, ok := page["shell_css"].(string); ok {
raw = s
} else if s, ok := page["壳样式"].(string); ok {
raw = s
}
return shellCSSFor(raw)
}
func normalizeLayout(raw string) string {
switch strings.ToLower(strings.TrimSpace(raw)) {
case "", "auto", "default":
return ""
case "sidebar", "side":
return "sidebar"
case "stacked", "stack", "column":
return "stacked"
case "bare", "main", "none":
return "bare"
case "rail":
return "rail"
default:
return raw
}
}
func resolveLayout(page map[string]any) string {
raw := ""
if s, ok := page["layout"].(string); ok {
raw = s
} else if s, ok := page["布局"].(string); ok {
raw = s
}
return normalizeLayout(raw)
}
func headHTML(page map[string]any, defaultTitle string) string {
pageTitle := defaultTitle
if meta, ok := page["meta"].(map[string]any); ok {
if t := text(meta["title"]); t != "" {
pageTitle = t
}
}
var s strings.Builder
s.WriteString(fmt.Sprintf("<title>%s</title>", esc(pageTitle)))
if meta, ok := page["meta"].(map[string]any); ok {
for k, v := range meta {
if k == "title" {
continue
}
val := text(v)
if val == "" {
continue
}
switch {
case k == "description":
s.WriteString(fmt.Sprintf(`<meta name="description" content="%s"/>`, esc(val)))
case k == "canonical":
s.WriteString(fmt.Sprintf(`<link rel="canonical" href="%s"/>`, esc(val)))
case k == "icon" || k == "favicon":
s.WriteString(fmt.Sprintf(`<link rel="icon" href="%s"/>`, esc(val)))
case strings.HasPrefix(k, "og:"):
s.WriteString(fmt.Sprintf(`<meta property="%s" content="%s"/>`, esc(k), esc(val)))
default:
s.WriteString(fmt.Sprintf(`<meta name="%s" content="%s"/>`, esc(k), esc(val)))
}
}
}
return s.String()
}
func renderCard(page map[string]any, it map[string]any) string {
title := text(it["title"])
body := text(it["body"])
href := text(it["href"])
meta := text(it["meta"])
tag := text(it["tag"])
tc := classAttr(fieldCSS(it, "title"))
bc := classAttr(fieldCSS(it, "body"))
var card strings.Builder
card.WriteString(`<article class="card">`)
if href != "" {
prefix := "/post/"
if p, ok := page["link_prefix"].(string); ok {
prefix = p
}
card.WriteString(fmt.Sprintf(`<a class="card-link" href="%s">`, esc(prefix+href)))
}
if meta != "" {
card.WriteString(fmt.Sprintf(`<div class="card-meta">%s</div>`, esc(meta)))
}
card.WriteString(fmt.Sprintf("<h2%s>%s</h2>", tc, esc(title)))
if tag != "" {
card.WriteString(fmt.Sprintf(`<div class="card-tag">%s</div>`, esc(tag)))
}
if body != "" {
card.WriteString(fmt.Sprintf("<p%s>%s</p>", bc, esc(body)))
}
if href != "" {
card.WriteString("</a>")
}
card.WriteString("</article>")
return card.String()
}
func renderArticle(it map[string]any) string {
title := text(it["title"])
body := text(it["body"])
meta := text(it["meta"])
tag := text(it["tag"])
var s strings.Builder
s.WriteString(`<article class="article">`)
if meta != "" {
s.WriteString(fmt.Sprintf(`<div class="article-meta">%s</div>`, esc(meta)))
}
s.WriteString(fmt.Sprintf(`<h1 class="article-title">%s</h1>`, esc(title)))
if tag != "" {
s.WriteString(fmt.Sprintf(`<div class="article-tags">%s</div>`, esc(tag)))
}
if body != "" {
// Minimal: escape as paragraphs (full markdown deferred).
s.WriteString(fmt.Sprintf(`<div class="article-body"><p class="article-p">%s</p></div>`, esc(body)))
}
s.WriteString("</article>")
return s.String()
}
func renderPagination(page map[string]any, total int64, itemCount int) string {
p, ok := page["paginate"].(map[string]any)
if !ok {
return ""
}
offset := int64(0)
limit := int64(10)
if v, ok := p["offset"].(float64); ok {
offset = int64(v)
}
if v, ok := p["limit"].(float64); ok {
limit = int64(v)
}
if limit <= 0 {
return ""
}
path := "/"
if s, ok := p["path"].(string); ok {
path = s
}
var s strings.Builder
s.WriteString(`<nav class="pagination" aria-label="Pagination">`)
if offset > 0 {
prev := offset - limit
if prev < 0 {
prev = 0
}
s.WriteString(fmt.Sprintf(
`<a class="page-prev" href="%s?offset=%d">← Previous</a> `,
esc(path), prev,
))
}
end := offset + int64(itemCount)
statusEnd := end
if statusEnd > total {
statusEnd = total
}
s.WriteString(fmt.Sprintf(
`<span class="page-status">%d–%d of %d</span> `,
offset+1, statusEnd, total,
))
if end < total {
s.WriteString(fmt.Sprintf(
`<a class="page-next" href="%s?offset=%d">Next →</a>`,
esc(path), end,
))
}
s.WriteString("</nav>")
return s.String()
}
func pushIntro(buf *strings.Builder, intro string) {
if intro != "" {
buf.WriteString(fmt.Sprintf(`<div class="main-intro">%s</div>`, intro))
}
}
func renderFragment(page map[string]any, dbURL, slot string) string {
slot = table.NormalizeSlot(slot)
switch slot {
case "nav":
links := resolveLinks(page["nav"], dbURL, page)
return fmt.Sprintf(
`<header class="topnav" data-slot="nav">%s</header>`,
renderULWithMQ(links, "nav", nil),
)
case "sidebar":
links := resolveLinks(page["sidebar"], dbURL, page)
return fmt.Sprintf(
`<aside class="side" data-slot="sidebar"><span class="side-label">侧栏</span>%s</aside>`,
renderULWithMQ(links, "side-nav", nil),
)
case "footer":
links := resolveLinks(page["footer"], dbURL, page)
return fmt.Sprintf(
`<footer class="foot" data-slot="footer">%s</footer>`,
renderULWithMQ(links, "foot-nav", nil),
)
default:
intro, items, _ := resolveMain(page, dbURL)
var body strings.Builder
pushIntro(&body, intro)
if len(items) > 0 {
isDetail, _ := page["detail"].(bool)
if isDetail {
body.WriteString(renderArticle(items[0]))
} else {
body.WriteString(`<section class="content cards">`)
for _, it := range items {
body.WriteString(renderCard(page, it))
}
body.WriteString(`</section>`)
}
}
return fmt.Sprintf(`<main class="main" data-slot="main">%s</main>`, 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 {
if page == nil {
page = map[string]any{}
}
if partID != "" {
parts, _ := page["parts"].(map[string]any)
if parts != nil {
if cfg, ok := parts[partID].(map[string]any); ok {
merged := map[string]any{}
for k, v := range page {
merged[k] = v
}
for k, v := range cfg {
merged[k] = v
}
slot, _ := cfg["slot"].(string)
if slot == "" {
slot, _ = cfg["fragment"].(string)
}
if slot == "" {
slot = "main"
}
return renderFragment(merged, dbURL, slot)
}
}
return renderFragment(page, dbURL, partID)
}
title := "Marqdo Web"
if t, ok := page["title"].(string); ok && t != "" {
title = t
}
shell := resolveShellCSS(page)
layout := resolveLayout(page)
parts, _ := page["parts"].(map[string]any)
if parts == nil {
parts = map[string]any{}
}
nav := resolveLinks(page["nav"], dbURL, page)
side := resolveLinks(page["sidebar"], dbURL, page)
foot := resolveLinks(page["footer"], dbURL, page)
intro, items, total := resolveMain(page, dbURL)
navCSS, mqPairs := navMediaClassMapMany(nav, side, foot)
extra, _ := page["styles_css"].(string)
if navCSS != "" {
if extra != "" {
extra += "\n"
}
extra += navCSS
}
_, hasSideKey := page["sidebar"]
hasSide := hasSideKey || len(side) > 0
bare := layout == "bare"
var bodyClass string
switch layout {
case "bare":
bodyClass = "layout-bare"
case "stacked":
bodyClass = "layout-stacked"
case "rail":
if hasSide {
bodyClass = "has-rail has-sidebar"
} else {
bodyClass = "has-rail no-sidebar"
}
case "sidebar":
if hasSide {
bodyClass = "has-sidebar"
} else {
bodyClass = "no-sidebar"
}
case "":
if hasSide {
bodyClass = "has-sidebar"
} else {
bodyClass = "no-sidebar"
}
default:
bodyClass = layout
}
var mainHTML strings.Builder
if images, ok := page["images_html"].(string); ok && images != "" {
mainHTML.WriteString(images)
}
pushIntro(&mainHTML, intro)
if len(items) > 0 {
isDetail, _ := page["detail"].(bool)
if isDetail {
mainHTML.WriteString(renderArticle(items[0]))
} else {
mainHTML.WriteString(`<section class="content cards">`)
for _, it := range items {
mainHTML.WriteString(renderCard(page, it))
}
mainHTML.WriteString(`</section>`)
}
if total != nil {
mainHTML.WriteString(renderPagination(page, *total, len(items)))
}
}
styleBlock := ""
if shell != "" || extra != "" {
styleBlock = fmt.Sprintf("<style>%s%s</style>", shell, extra)
}
showChrome := !bare
sideHTML := ""
if showChrome && hasSide {
sideHTML = fmt.Sprintf(
`<aside class="%s"%s><span class="side-label">侧栏</span>%s</aside>`,
slotClass(page, "sidebar", "side"),
slotAttrs("sidebar", parts, page),
renderULWithMQ(side, "side-nav", mqPairs),
)
}
headerHTML := ""
if showChrome {
headerHTML = fmt.Sprintf(
`<header class="%s"%s>%s</header>`,
slotClass(page, "nav", "topnav"),
slotAttrs("nav", parts, page),
renderULWithMQ(nav, "nav", mqPairs),
)
}
footerHTML := ""
if showChrome {
footerHTML = fmt.Sprintf(
`<footer class="%s"%s>%s</footer>`,
slotClass(page, "footer", "foot"),
slotAttrs("footer", parts, page),
renderULWithMQ(foot, "foot-nav", mqPairs),
)
}
return fmt.Sprintf(`<!DOCTYPE html>
<html lang="zh-CN"><head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
%s
%s
</head>
<body class="%s">
%s
%s
<main class="%s"%s>%s</main>
%s
</body></html>`,
headHTML(page, title),
styleBlock,
bodyClass,
headerHTML,
sideHTML,
slotClass(page, "main", "main"),
slotAttrs("main", parts, page),
mainHTML.String(),
footerHTML,
)
}
@@ -0,0 +1,52 @@
package render_test
import (
"strings"
"testing"
"github.com/marqdo/marqdo/plugins/web/internal/render"
)
func TestRenderPageIntroNoDB(t *testing.T) {
page := map[string]any{
"title": "smoke",
"intro": "<h1>smoke</h1>",
"styles_css": ".x { color: red; }",
"shell_css": "minimal",
}
html := render.RenderPage(page, "", "")
if html == "" {
t.Fatal("empty html")
}
if !strings.Contains(html, "<h1>smoke</h1>") {
t.Fatalf("missing intro: %s", html)
}
if !strings.Contains(html, ".x { color: red; }") {
t.Fatalf("missing styles: %s", html)
}
if !strings.Contains(html, "<!DOCTYPE html>") {
t.Fatalf("not a document: %s", html[:80])
}
}
func TestRenderPageNavChrome(t *testing.T) {
page := map[string]any{
"title": "t",
"nav": []any{
map[string]any{"front": "Home", "back": "/", "css": "", "media": "", "when": ""},
},
"sidebar": []any{
map[string]any{"front": "A", "back": "/a", "css": "", "media": "", "when": ""},
},
"footer": []any{
map[string]any{"front": "©", "back": "/", "css": "", "media": "", "when": ""},
},
"intro": "hi",
}
html := render.RenderPage(page, "", "")
for _, needle := range []string{"<header", "<aside", "<footer", "Home", "侧栏", "has-sidebar"} {
if !strings.Contains(html, needle) {
t.Fatalf("missing %q in html", needle)
}
}
}
+63
View File
@@ -0,0 +1,63 @@
// Package style implements web_style (CSS from GFM style tables).
package style
import (
"strconv"
"strings"
"github.com/marqdo/marqdo/plugins/web/internal/table"
)
// Style matches Rust web_style: args name + table + optional strict → CSS string.
func Style(args map[string]any) (string, error) {
name := ""
if v, ok := args["name"]; ok && v != nil {
name = cellStr(v)
}
var tbl any = []any{}
if v, ok := args["table"]; ok && v != nil {
tbl = v
}
strict := false
for _, k := range []string{"strict", "strict_css_cells", "严格"} {
if v, ok := args[k]; ok {
strict = boolishStrict(v)
break
}
}
return table.AsCSSNamedChecked(name, tbl, strict)
}
func cellStr(v any) string {
switch t := v.(type) {
case string:
return t
case float64:
if t == float64(int64(t)) {
return strconv.FormatInt(int64(t), 10)
}
return strconv.FormatFloat(t, 'f', -1, 64)
case bool:
return strconv.FormatBool(t)
default:
return ""
}
}
func boolishStrict(v any) bool {
switch t := v.(type) {
case bool:
return t
case float64:
return int64(t) != 0
case string:
s := strings.TrimSpace(t)
switch s {
case "1", "true", "True", "yes", "on", "真", "是":
return true
}
return false
default:
return false
}
}
+36
View File
@@ -0,0 +1,36 @@
package style_test
import (
"strings"
"testing"
"github.com/marqdo/marqdo/plugins/web/internal/style"
)
func TestStyleSimple(t *testing.T) {
css, err := style.Style(map[string]any{
"name": "card",
"table": []any{
map[string]any{"选择器": ".card", "属性": "color", "值": "navy"},
},
})
if err != nil {
t.Fatal(err)
}
if !strings.Contains(css, ".card {") || !strings.Contains(css, "color: navy;") {
t.Fatalf("%q", css)
}
}
func TestStyleStrictRejectsNumeric(t *testing.T) {
_, err := style.Style(map[string]any{
"name": "x",
"strict": true,
"table": []any{
map[string]any{"选择器": ".x", "属性": "grid-column", "值": float64(0)},
},
})
if err == nil || !strings.Contains(err.Error(), "suspicious") {
t.Fatalf("err=%v", err)
}
}
File diff suppressed because it is too large. Load diff
+62
View File
@@ -0,0 +1,62 @@
package table_test
import (
"strings"
"testing"
"github.com/marqdo/marqdo/plugins/web/internal/table"
)
func TestNormalizeRefBackticks(t *testing.T) {
cases := []struct {
in, want string
}{
{"`foo`", "foo"},
{" `a.b` ", "a.b"},
{"plain", "plain"},
{"`a` and `b`", "a and b"},
{"`unclosed", "`unclosed"},
{"", ""},
}
for _, c := range cases {
got := table.NormalizeRef(c.in)
if got != c.want {
t.Errorf("NormalizeRef(%q)=%q want %q", c.in, got, c.want)
}
}
}
func TestAsBindChineseHeaders(t *testing.T) {
tbl := map[string]any{
"属性": []any{"title", "body"},
"值": []any{"posts.title", "posts.body"},
"样式": []any{"`hero`", ""},
}
got := table.AsBind(tbl)
arr, ok := got.([]any)
if !ok || len(arr) != 2 {
t.Fatalf("AsBind=%v", got)
}
r0 := arr[0].(map[string]any)
if r0["front"] != "title" || r0["back"] != "posts.title" || r0["css"] != "hero" {
t.Fatalf("row0=%v", r0)
}
r1 := arr[1].(map[string]any)
if r1["front"] != "body" || r1["back"] != "posts.body" || r1["css"] != "" {
t.Fatalf("row1=%v", r1)
}
}
func TestAsCSSNamedSimpleSelector(t *testing.T) {
tbl := []any{
map[string]any{"选择器": ".card", "属性": "color", "值": "red"},
map[string]any{"选择器": ".card", "属性": "padding", "值": "1rem"},
}
css := table.AsCSSNamed("card", tbl)
if !strings.Contains(css, ".card {") {
t.Fatalf("missing selector: %q", css)
}
if !strings.Contains(css, "color: red;") || !strings.Contains(css, "padding: 1rem;") {
t.Fatalf("missing decls: %q", css)
}
}
+430 -8
View File
@@ -51,10 +51,40 @@ static int host_query(char *name, char *args_json, char **out_json, char **err_m
extern int web_go_ready(char *args_json, char **out_json, char **err_msg);
extern int web_page_new(char *args_json, char **out_json, char **err_msg);
extern int web_style(char *args_json, char **out_json, char **err_msg);
extern int web_compose_components(char *args_json, char **out_json, char **err_msg);
extern int web_compose_main(char *args_json, char **out_json, char **err_msg);
extern int web_render(char *args_json, char **out_json, char **err_msg);
extern int web_db_new(char *args_json, char **out_json, char **err_msg);
extern int web_db_init(char *args_json, char **out_json, char **err_msg);
extern int web_db_insert(char *args_json, char **out_json, char **err_msg);
extern int web_db_select(char *args_json, char **out_json, char **err_msg);
extern int web_db_get(char *args_json, char **out_json, char **err_msg);
extern int web_db_exec(char *args_json, char **out_json, char **err_msg);
extern int web_form_new(char *args_json, char **out_json, char **err_msg);
extern int web_form_fields(char *args_json, char **out_json, char **err_msg);
extern int web_compose_form(char *args_json, char **out_json, char **err_msg);
extern int web_app_new(char *args_json, char **out_json, char **err_msg);
extern int web_app_route(char *args_json, char **out_json, char **err_msg);
static int register_core(void) {
if (host_register((char *)"web_go_ready", (char *)"", web_go_ready) != 0) return 1;
if (host_register((char *)"web_page_new", (char *)"title,intro,shell_css,layout,asset_version", web_page_new) != 0) return 1;
if (host_register((char *)"web_style", (char *)"name,table,strict", web_style) != 0) return 1;
if (host_register((char *)"web_compose_components", (char *)"page,components", web_compose_components) != 0) return 1;
if (host_register((char *)"web_compose_main", (char *)"page,main", web_compose_main) != 0) return 1;
if (host_register((char *)"web_compose_form", (char *)"page,form,id,target", web_compose_form) != 0) return 1;
if (host_register((char *)"web_render", (char *)"page", web_render) != 0) return 1;
if (host_register((char *)"web_db_new", (char *)"url", web_db_new) != 0) return 1;
if (host_register((char *)"web_db_init", (char *)"url,name,fields", web_db_init) != 0) return 1;
if (host_register((char *)"web_db_insert", (char *)"url,table,rows,txn", web_db_insert) != 0) return 1;
if (host_register((char *)"web_db_select", (char *)"url,table,where,limit,order,offset,txn", web_db_select) != 0) return 1;
if (host_register((char *)"web_db_get", (char *)"url,table,id,txn", web_db_get) != 0) return 1;
if (host_register((char *)"web_db_exec", (char *)"url,sql,args,txn", web_db_exec) != 0) return 1;
if (host_register((char *)"web_form_new", (char *)"table,action,id", web_form_new) != 0) return 1;
if (host_register((char *)"web_form_fields", (char *)"form,fields", web_form_fields) != 0) return 1;
if (host_register((char *)"web_app_new", (char *)"page,db,admin,host,port,admin_prefix,login_redirect,logout_redirect,shell_css,layout,asset_version", web_app_new) != 0) return 1;
if (host_register((char *)"web_app_route", (char *)"app,path,page", web_app_route) != 0) return 1;
return 0;
}
*/
@@ -63,18 +93,25 @@ import "C"
import (
"encoding/json"
"fmt"
"path/filepath"
"strconv"
"strings"
"unsafe"
"github.com/marqdo/marqdo/plugins/web/internal/app"
"github.com/marqdo/marqdo/plugins/web/internal/compose"
"github.com/marqdo/marqdo/plugins/web/internal/db"
"github.com/marqdo/marqdo/plugins/web/internal/form"
"github.com/marqdo/marqdo/plugins/web/internal/page"
"github.com/marqdo/marqdo/plugins/web/internal/plugin"
"github.com/marqdo/marqdo/plugins/web/internal/render"
"github.com/marqdo/marqdo/plugins/web/internal/style"
)
func main() {}
//export marqdo_plugin_abi_version
func marqdo_plugin_abi_version() C.uint32_t {
return 2
}
func marqdo_plugin_abi_version() C.uint32_t { return 2 }
//export marqdo_plugin_init
func marqdo_plugin_init(host *C.MarqdoHostApi) C.int {
@@ -88,6 +125,7 @@ func marqdo_plugin_init(host *C.MarqdoHostApi) C.int {
//export marqdo_plugin_shutdown
func marqdo_plugin_shutdown() {
db.ResetPool()
plugin.Shutdown()
}
@@ -165,14 +203,108 @@ func parseArgs(argsJSON *C.char) (map[string]any, error) {
return m, nil
}
func argStr(args map[string]any, keys ...string) (string, bool) {
for _, k := range keys {
v, ok := args[k]
if !ok || v == nil {
continue
}
switch t := v.(type) {
case string:
return t, true
case float64:
if t == float64(int64(t)) {
return strconv.FormatInt(int64(t), 10), true
}
return strconv.FormatFloat(t, 'f', -1, 64), true
case bool:
return strconv.FormatBool(t), true
case json.Number:
return t.String(), true
}
}
return "", false
}
func argStrReq(args map[string]any, keys ...string) (string, error) {
s, ok := argStr(args, keys...)
if !ok || s == "" {
return "", fmt.Errorf("missing `%s`", keys[0])
}
return s, nil
}
func entryDir() string {
raw, err := plugin.Query("entry_dir", "{}")
if err != nil {
return "."
}
var s string
if json.Unmarshal([]byte(raw), &s) == nil && s != "" {
return s
}
return "."
}
func resolveDbURL(url string) string {
lower := strings.ToLower(url)
if strings.HasPrefix(lower, "postgres://") || strings.HasPrefix(lower, "postgresql://") {
return url
}
stripped := url
prefix := "sqlite:"
switch {
case strings.HasPrefix(url, "sqlite:"):
stripped = strings.TrimPrefix(url, "sqlite:")
case strings.HasPrefix(url, "SQLITE:"):
stripped = strings.TrimPrefix(url, "SQLITE:")
prefix = "SQLITE:"
default:
prefix = "sqlite:"
}
if filepath.IsAbs(stripped) {
return prefix + stripped
}
abs := filepath.Join(entryDir(), stripped)
return prefix + abs
}
func dbURLOf(args map[string]any) (string, error) {
if s, ok := argStr(args, "url", "db_url"); ok && s != "" {
return resolveDbURL(s), nil
}
if dbObj, ok := args["db"].(map[string]any); ok {
if s, ok := argStr(dbObj, "url"); ok && s != "" {
return resolveDbURL(s), nil
}
}
return "", fmt.Errorf("missing db url")
}
func callLib(path string) (any, error) {
payload, _ := json.Marshal(map[string]any{"path": path})
raw, err := plugin.Query("call_lib_path", string(payload))
if err != nil {
return nil, err
}
var v any
if err := json.Unmarshal([]byte(raw), &v); err != nil {
return nil, err
}
return v, nil
}
func asPageMap(v any) map[string]any {
if m, ok := v.(map[string]any); ok {
return m
}
return map[string]any{}
}
//export web_go_ready
func web_go_ready(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
_ = argsJSON
return replyJSON(outJSON, errMsg, map[string]any{
"ok": true,
"impl": "go",
"abi": 2,
}, nil)
return replyJSON(outJSON, errMsg, map[string]any{"ok": true, "impl": "go", "abi": 2}, nil)
}
//export web_page_new
@@ -183,3 +315,293 @@ func web_page_new(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
}
return replyJSON(outJSON, errMsg, page.New(args), nil)
}
//export web_style
func web_style(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
css, err := style.Style(args)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
return replyJSON(outJSON, errMsg, css, nil)
}
//export web_compose_components
func web_compose_components(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
pageBag := asPageMap(args["page"])
components := args["components"]
if components == nil {
return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing `components`"))
}
out, err := compose.ComposeComponents(pageBag, components, callLib)
return replyJSON(outJSON, errMsg, out, err)
}
//export web_compose_main
func web_compose_main(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
pageBag := asPageMap(args["page"])
main := args["main"]
if main == nil {
return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing `main`"))
}
out, err := compose.ComposeMain(pageBag, main, callLib)
return replyJSON(outJSON, errMsg, out, err)
}
//export web_render
func web_render(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
pageBag := asPageMap(args["page"])
if len(pageBag) == 0 {
pageBag = args
}
dbURL, _ := dbURLOf(args)
html := render.RenderPage(pageBag, dbURL, "")
return replyJSON(outJSON, errMsg, html, nil)
}
//export web_db_new
func web_db_new(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
url, _ := argStr(args, "url")
if url == "" {
url = "sqlite:site.db"
}
return replyJSON(outJSON, errMsg, map[string]any{
"url": resolveDbURL(url),
"_type": "db",
}, nil)
}
//export web_db_init
func web_db_init(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
url, err := dbURLOf(args)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
name, err := argStrReq(args, "name", "table")
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
fields := args["fields"]
if fields == nil {
fields = []any{}
}
out, err := db.Init(url, name, fields)
return replyJSON(outJSON, errMsg, out, err)
}
//export web_db_insert
func web_db_insert(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
url, err := dbURLOf(args)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
tableName, err := argStrReq(args, "table")
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
rows := args["rows"]
if rows == nil {
rows = args["row"]
}
if rows == nil {
rows = []any{}
}
out, err := db.Insert(url, tableName, rows)
return replyJSON(outJSON, errMsg, out, err)
}
//export web_db_select
func web_db_select(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
url, err := dbURLOf(args)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
tableName, err := argStrReq(args, "table")
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
limit := int64(200)
if v, ok := args["limit"]; ok {
switch t := v.(type) {
case float64:
limit = int64(t)
case string:
if n, e := strconv.ParseInt(t, 10, 64); e == nil {
limit = n
}
}
}
opts := db.SelectOpts{}
if w, ok := args["where"]; ok && w != nil {
if s, ok := w.(string); ok {
if s != "" && !strings.EqualFold(s, "none") && !strings.EqualFold(s, "null") {
opts.Where = w
}
} else {
opts.Where = w
}
}
if o, ok := argStr(args, "order"); ok {
opts.Order = o
}
if v, ok := args["offset"]; ok && v != nil {
switch t := v.(type) {
case float64:
n := int64(t)
opts.Offset = &n
case string:
if n, e := strconv.ParseInt(t, 10, 64); e == nil {
opts.Offset = &n
}
}
} else if v, ok := args["跳过"]; ok && v != nil {
if t, ok := v.(float64); ok {
n := int64(t)
opts.Offset = &n
}
}
out, err := db.Select(url, tableName, limit, opts)
return replyJSON(outJSON, errMsg, out, err)
}
//export web_db_get
func web_db_get(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
url, err := dbURLOf(args)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
tableName, err := argStrReq(args, "table")
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
id, err := argStrReq(args, "id")
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
out, err := db.Get(url, tableName, id)
return replyJSON(outJSON, errMsg, out, err)
}
//export web_db_exec
func web_db_exec(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
url, err := dbURLOf(args)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
sqlStmt, err := argStrReq(args, "sql")
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
out, err := db.Exec(url, sqlStmt, args["args"])
return replyJSON(outJSON, errMsg, out, err)
}
//export web_form_new
func web_form_new(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
tableName, _ := argStr(args, "table")
action, _ := argStr(args, "action")
id, _ := argStr(args, "id")
return replyJSON(outJSON, errMsg, form.New(tableName, action, id), nil)
}
//export web_form_fields
func web_form_fields(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
formBag := asPageMap(args["form"])
fields := args["fields"]
if fields == nil {
return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing `fields`"))
}
return replyJSON(outJSON, errMsg, form.SetFields(formBag, fields), nil)
}
//export web_compose_form
func web_compose_form(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
pageBag := args["page"]
formV := args["form"]
id, _ := argStr(args, "id")
var target *string
if t, ok := argStr(args, "target"); ok && t != "" {
target = &t
}
out, err := compose.ComposeForm(pageBag, formV, id, target)
return replyJSON(outJSON, errMsg, out, err)
}
//export web_app_new
func web_app_new(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
return replyJSON(outJSON, errMsg, app.New(args), nil)
}
//export web_app_route
func web_app_route(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
appBag := asPageMap(args["app"])
path, err := argStrReq(args, "path")
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
pageV := args["page"]
if pageV == nil {
return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing `page` for route"))
}
out, err := app.Route(appBag, path, pageV)
return replyJSON(outJSON, errMsg, out, err)
}
+9 -6
View File
@@ -435,12 +435,21 @@ pub fn remove_ext(id: &str) -> Result<()> {
/// Resolve installed native plugin path for `name` (`agent`, `web`, …).
/// Also falls back to cargo `target/{debug,release}` artifacts for local runs.
///
/// `MARQDO_*_PLUGIN` env overrides installed `~/.marqdo/ext` so developers can
/// point at a freshly built Go `libweb.so` during the web rewrite.
pub fn installed_native_path(name: &str) -> Option<PathBuf> {
let short = native_short_name(name);
if !matches!(short, "agent" | "web" | "quantum" | "linalg") {
return None;
}
let lib_name = native_lib_filename(short);
if let Ok(p) = env::var(native_env_var(short)) {
let p = PathBuf::from(p);
if p.is_file() {
return Some(p);
}
}
for root in trusted_plugin_roots() {
let hint = root.join(format!("{short}.plugin"));
if let Ok(s) = fs::read_to_string(&hint) {
@@ -454,12 +463,6 @@ pub fn installed_native_path(name: &str) -> Option<PathBuf> {
return Some(p);
}
}
if let Ok(p) = env::var(native_env_var(short)) {
let p = PathBuf::from(p);
if p.is_file() {
return Some(p);
}
}
find_native_plugin(short).ok()
}