feat(web): land Artifact serve/endpoint path and retire compose golds

Wire data_source into Document render, register Endpoint handlers via
run_artifact, restore marqdo-blog as an Artifact site, and replace old
compose_* web golds with ADR 0007 fixtures and docs.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-28 11:36:45 +08:00
1 parent 67bac1bf02
commit ff252fd469
86 files changed
+952 -4499

No files matched your search

+114 -12
View File
@@ -19,6 +19,7 @@ import (
"os"
"path/filepath"
"strconv"
"strings"
"github.com/marqdo/marqdo/plugins/web/internal/app"
"github.com/marqdo/marqdo/plugins/web/internal/artifact"
@@ -123,6 +124,7 @@ func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
}
}
homeArgs := map[string]any{"title": "Marqdo"}
var homeMeta map[string]string
for _, f := range files {
if f.Kind == "web" && (f.Route == "/" || f.Rel == "index.mq.md") {
title := f.Meta["title"]
@@ -136,33 +138,72 @@ func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
"title": title,
"intro": artifact.MarkdownHTML(f.Body),
}
homeMeta = f.Meta
break
}
}
home := page.New(homeArgs)
stampArtifactData(home, homeMeta)
a := app.New(map[string]any{
"page": home,
"db": args["db"],
"host": host,
"port": port,
})
artifactRoutes := map[string]any{}
for _, f := range files {
if f.Kind != "web" || f.Route == "/" {
if f.Kind == "web" {
if f.Route == "/" {
continue
}
title := f.Meta["title"]
if title == "" {
title = f.Meta["标题"]
}
pg := page.New(map[string]any{
"title": title,
"intro": artifact.MarkdownHTML(f.Body),
})
stampArtifactData(pg, f.Meta)
out, err := app.Route(a, f.Route, pg)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
a = out
continue
}
title := f.Meta["title"]
if title == "" {
title = f.Meta["标题"]
// endpoint
req := f.Meta["request"]
if req == "" {
req = f.Meta["请求"]
}
pg := page.New(map[string]any{
"title": title,
"intro": artifact.MarkdownHTML(f.Body),
})
out, err := app.Route(a, f.Route, pg)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
if req == "" {
req = "json"
}
a = out
resp := f.Meta["response"]
if resp == "" {
resp = f.Meta["响应"]
}
if resp == "" {
resp = "json"
}
auth := f.Meta["auth"]
if auth == "" {
auth = f.Meta["鉴权"]
}
key := f.Method + " " + f.Route
artifactRoutes[key] = map[string]any{
"method": f.Method,
"path": f.Route,
"file": f.Path,
"request": req,
"response": resp,
"auth": auth,
"kind": "endpoint",
}
}
if len(artifactRoutes) > 0 {
a["artifact_routes"] = artifactRoutes
}
if mw := args["middleware"]; mw != nil {
out, err := middleware.Configure(a, map[string]any{"security": mw})
@@ -222,3 +263,64 @@ func web_route_use(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
rt["middleware"] = args["middleware"]
return replyJSON(outJSON, errMsg, rt, nil)
}
// stampArtifactData applies flat Document metadata (ADR 0007) onto a page bag.
func stampArtifactData(pg map[string]any, meta map[string]string) {
if pg == nil || meta == nil {
return
}
src := meta["data_source"]
if src == "" {
src = meta["数据源"]
}
if src != "" {
pg["data_source"] = src
}
order := meta["data_order"]
if order == "" {
order = meta["排序"]
}
if order != "" {
pg["order"] = order
}
where := meta["data_where"]
if where == "" {
where = meta["条件"]
}
if where != "" {
// col=val,col2=val2 → query map (values may contain {param})
q := map[string]any{}
for _, part := range strings.Split(where, ",") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
k, v, ok := strings.Cut(part, "=")
if !ok {
continue
}
q[strings.TrimSpace(k)] = strings.TrimSpace(v)
}
if len(q) > 0 {
pg["query"] = q
// Filtered Document routes render as article detail (007 /post/{slug}).
pg["detail"] = true
}
}
if d := meta["detail"]; d != "" {
pg["detail"] = d == "true" || d == "True" || d == "1"
}
if d := meta["详情"]; d != "" {
pg["detail"] = d == "true" || d == "True" || d == "1" || d == "是"
}
prefix := meta["link_prefix"]
if prefix == "" {
prefix = meta["链接前缀"]
}
if prefix != "" {
pg["link_prefix"] = prefix
} else if src != "" && where == "" {
// List pages default card links to /post/{slug}.
pg["link_prefix"] = "/post/"
}
}
+11
View File
@@ -279,6 +279,17 @@ func InspectBag(app map[string]any, declared []ArtifactFile) map[string]any {
dec = append(dec, map[string]any{"path": key, "kind": "endpoint"})
}
}
if art, ok := app["artifact_routes"].(map[string]any); ok {
for key, v := range art {
m, _ := v.(map[string]any)
dec = append(dec, map[string]any{
"path": key,
"kind": "endpoint",
"method": fmt.Sprint(m["method"]),
"file": fmt.Sprint(m["file"]),
})
}
}
}
return map[string]any{
"declared": dec,
+3
View File
@@ -122,6 +122,7 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
galleryRoutes: routeMapOf(appBag, "gallery_routes"),
proxyRoutes: routeMapOf(appBag, "proxy_routes"),
invokeRoutes: routeMapOf(appBag, "invoke_routes"),
artifactRoutes: routeMapOf(appBag, "artifact_routes"),
auth: authCfg,
oidc: oidc.ParseConfig(appBag),
tenant: tenant.FromBag(appBag),
@@ -238,6 +239,7 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
st.mountGalleryRoutes(mux)
st.mountProxyRoutes(mux)
st.mountInvokeRoutes(mux)
st.mountArtifactRoutes(mux)
st.mountAuthRoutes(mux)
mux.HandleFunc("/{path...}", st.handleNotFound)
@@ -307,6 +309,7 @@ type state struct {
galleryRoutes map[string]any
proxyRoutes map[string]any
invokeRoutes map[string]any
artifactRoutes map[string]any
auth authConfig
oidc oidc.Config
tenant tenant.Config
@@ -0,0 +1,142 @@
package httpx
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"github.com/marqdo/marqdo/plugins/web/internal/plugin"
"github.com/marqdo/marqdo/plugins/web/internal/session"
)
// artifactRoute is one Endpoint file registered by web.serve (ADR 0007).
type artifactRoute struct {
Method string
Path string
File string
Request string // json | form | none | query
Response string // json | text | html
Auth string // role name or "" / "none"
}
func parseArtifactRoute(v any) artifactRoute {
m, _ := v.(map[string]any)
return artifactRoute{
Method: strings.ToUpper(strOpt(m, "method", "GET")),
Path: strOpt(m, "path", ""),
File: strOpt(m, "file", ""),
Request: strings.ToLower(strOpt(m, "request", "json")),
Response: strings.ToLower(strOpt(m, "response", "json")),
Auth: strOpt(m, "auth", ""),
}
}
func (st *state) mountArtifactRoutes(mux *http.ServeMux) {
for _, key := range sortedKeys(st.artifactRoutes) {
cfg := parseArtifactRoute(st.artifactRoutes[key])
if cfg.File == "" || cfg.Path == "" {
continue
}
method := cfg.Method
if method == "" {
method = http.MethodGet
}
pattern := method + " " + goMuxPattern(cfg.Path)
routeCfg := cfg
mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
if r.Method != method {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
st.handleArtifact(w, r, routeCfg)
})
}
}
func (st *state) handleArtifact(w http.ResponseWriter, r *http.Request, route artifactRoute) {
if route.Auth != "" && !strings.EqualFold(route.Auth, "none") {
cookie := r.Header.Get("Cookie")
user := session.UsernameFromCookie(cookie)
if user == "" {
jsonErr(w, http.StatusUnauthorized, "auth required")
return
}
role := session.RoleFromCookie(cookie)
if role != "" && role != route.Auth && role != "admin" && role != "superadmin" {
jsonErr(w, http.StatusForbidden, "forbidden")
return
}
}
payload := map[string]any{}
switch route.Request {
case "none":
payload = queryToMap(r.URL.RawQuery)
case "query":
payload = queryToMap(r.URL.RawQuery)
case "form":
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 8<<20))
if err != nil {
jsonErr(w, http.StatusBadRequest, fmt.Sprintf("body: %v", err))
return
}
payload = formToMap(body)
default: // json
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 8<<20))
if err != nil {
jsonErr(w, http.StatusBadRequest, fmt.Sprintf("body: %v", err))
return
}
q := queryToMap(r.URL.RawQuery)
if len(body) == 0 {
payload = q
} else {
var raw map[string]any
if err := json.Unmarshal(body, &raw); err != nil {
jsonErr(w, http.StatusBadRequest, fmt.Sprintf("json: %v", err))
return
}
if raw == nil {
payload = q
} else {
for k, v := range q {
if _, exists := raw[k]; !exists {
raw[k] = v
}
}
payload = raw
}
}
}
for _, name := range pathParamNames(route.Path) {
if v := r.PathValue(name); v != "" {
payload[name] = v
}
}
value, err := plugin.RunArtifact(route.File, payload)
if err != nil {
jsonErr(w, http.StatusInternalServerError, err.Error())
return
}
switch route.Response {
case "text":
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
_, _ = io.WriteString(w, fmt.Sprint(value))
case "html", "text/html":
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
_, _ = io.WriteString(w, fmt.Sprint(value))
default:
code, body, err := jsonWrapInvokeValue(value)
if err != nil {
jsonErr(w, code, err.Error())
return
}
writeJSON(w, code, body)
}
}
+22
View File
@@ -49,3 +49,25 @@ func CallLibPath(path string, args map[string]any) (any, error) {
}
return v, nil
}
// RunArtifact loads and runs a Document/Endpoint `.mq.md` (ADR 0007).
// Request fields are passed as Metadata Binding overlays (`arg` / `--bind`).
func RunArtifact(path string, args map[string]any) (any, error) {
payload := map[string]any{"path": path}
if len(args) > 0 {
payload["args"] = args
}
raw, err := json.Marshal(payload)
if err != nil {
return nil, err
}
out, err := Query("run_artifact", string(raw))
if err != nil {
return nil, err
}
var v any
if err := json.Unmarshal([]byte(out), &v); err != nil {
return nil, err
}
return v, nil
}
@@ -0,0 +1,88 @@
package render
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/marqdo/marqdo/plugins/web/internal/db"
)
func TestResolveMainDataSource(t *testing.T) {
dir := t.TempDir()
url := "sqlite:" + filepath.Join(dir, "t.db")
fields := []any{
map[string]any{"字段": "title", "类型": "text", "可空": false},
map[string]any{"字段": "slug", "类型": "text", "可空": false},
map[string]any{"字段": "summary", "类型": "text", "可空": true},
map[string]any{"字段": "content", "类型": "text", "可空": true},
}
if _, err := db.Init(url, "posts", fields); err != nil {
t.Fatal(err)
}
rows := []any{
map[string]any{
"title": "Hello", "slug": "hello",
"summary": "sum", "content": "# Body",
},
}
if _, err := db.Insert(url, "posts", rows); err != nil {
t.Fatal(err)
}
page := map[string]any{
"intro": "<p>hi</p>",
"data_source": "posts",
"order": "-id",
"link_prefix": "/post/",
}
intro, items, _ := resolveMain(page, url)
if intro != "<p>hi</p>" {
t.Fatalf("intro=%q", intro)
}
if len(items) != 1 {
t.Fatalf("items=%d", len(items))
}
if items[0]["title"] != "Hello" || items[0]["href"] != "hello" {
t.Fatalf("item=%v", items[0])
}
html := RenderPage(page, url, "")
if !strings.Contains(html, `class="card"`) || !strings.Contains(html, "Hello") {
t.Fatalf("html missing card: %s", html[:min(400, len(html))])
}
_ = os.RemoveAll(dir)
}
func TestResolveMainDataWhereDetail(t *testing.T) {
dir := t.TempDir()
url := "sqlite:" + filepath.Join(dir, "t.db")
fields := []any{
map[string]any{"字段": "title", "类型": "text", "可空": false},
map[string]any{"字段": "slug", "类型": "text", "可空": false},
map[string]any{"字段": "content", "类型": "text", "可空": true},
}
if _, err := db.Init(url, "posts", fields); err != nil {
t.Fatal(err)
}
rows := []any{
map[string]any{"title": "A", "slug": "a", "content": "alpha"},
map[string]any{"title": "B", "slug": "b", "content": "beta"},
}
if _, err := db.Insert(url, "posts", rows); err != nil {
t.Fatal(err)
}
page := map[string]any{
"data_source": "posts",
"query": map[string]any{"slug": "{slug}"},
"params": map[string]any{"slug": "b"},
"detail": true,
}
_, items, _ := resolveMain(page, url)
if len(items) != 1 || items[0]["title"] != "B" {
t.Fatalf("items=%v", items)
}
html := RenderPage(page, url, "")
if !strings.Contains(html, "article-title") || !strings.Contains(html, "B") {
t.Fatalf("detail html: %s", html[:min(500, len(html))])
}
}
+73 -21
View File
@@ -420,22 +420,6 @@ func renderULWithMQ(links []navLink, class string, mqPairs [][2]string) 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 {
@@ -446,22 +430,90 @@ func resolveMain(page map[string]any, dbURL string) (intro string, items []map[s
offset = int64(v)
}
}
data := selectPageData(dbURL, tn, page, limit, offset)
// Legacy compose_main bind table (internal); prefer when present.
if main, ok := page["main"]; ok {
bindsAny := table.AsBind(main)
arr, _ := bindsAny.([]any)
if len(arr) > 0 && dbURL != "" {
if tn, ok := table.BindTableName(arr); ok {
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
}
}
}
// Artifact Document: flat data_source / data_order / data_where (ADR 0007).
src, _ := page["data_source"].(string)
if src == "" || dbURL == "" {
return intro, nil, nil
}
data := selectPageData(dbURL, src, 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 {
for _, v := range rawRows {
if m := projectArtifactRow(v); m != nil {
items = append(items, m)
}
}
return intro, items, total
}
// projectArtifactRow maps a DB row to card/article fields without compose binds.
func projectArtifactRow(row any) map[string]any {
obj, ok := row.(map[string]any)
if !ok || obj == nil {
return nil
}
m := map[string]any{}
if id, ok := obj["id"]; ok {
m["id"] = id
}
if t := text(obj["title"]); t != "" {
m["title"] = t
}
if s := text(obj["slug"]); s != "" {
m["href"] = s
} else if h := text(obj["href"]); h != "" {
m["href"] = h
}
// Detail pages prefer full content; list cards prefer summary.
if c := text(obj["content"]); c != "" {
m["body"] = c
} else if s := text(obj["summary"]); s != "" {
m["body"] = s
} else if b := text(obj["body"]); b != "" {
m["body"] = b
}
if tag := text(obj["tag"]); tag != "" {
m["tag"] = tag
}
if meta := text(obj["created_at"]); meta != "" {
m["meta"] = meta
} else if meta := text(obj["meta"]); meta != "" {
m["meta"] = meta
}
if len(m) == 0 {
return nil
}
return m
}
// listBind is one secondary page list (compose_list / 列表装配).
type listBind struct {
Items []map[string]any
-10
View File
@@ -176,16 +176,6 @@ static int register_core(void) {
if (host_register((char *)"web_page_detail", (char *)"page,detail", web_page_detail) != 0) return 1;
if (host_register((char *)"web_page_chrome", (char *)"page,nav_html,footer_html,body_class", web_page_chrome) != 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_list", (char *)"page,main,query,order,target", web_compose_list) != 0) return 1;
if (host_register((char *)"web_compose_intro", (char *)"page,intro", web_compose_intro) != 0) return 1;
if (host_register((char *)"web_intro", (char *)"table", web_intro) != 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_compose_auth_form", (char *)"page,action,submit,form_id,err_id,target,next,kind", web_compose_auth_form) != 0) return 1;
if (host_register((char *)"web_compose_nav_brand", (char *)"page,title,href,logo,logo_light,theme_key", web_compose_nav_brand) != 0) return 1;
if (host_register((char *)"web_compose_client", (char *)"page,source,bridge,wasm", web_compose_client) != 0) return 1;
if (host_register((char *)"web_compose_form_load", (char *)"page,table,id_param", web_compose_form_load) != 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;