Compare commits

...
125 changed files with 8734 additions and 84 deletions

No files matched your search

+4
View File
@@ -29,3 +29,7 @@ CLAUDE.md
AGENTS.md
codex-workflow.md
CODING_STANDARDS.md
# Generated LLM docs
internal/infrastructure/llmdocs/generated/*
!internal/infrastructure/llmdocs/generated/.gitkeep
+5
View File
@@ -4,6 +4,10 @@ COPY web/package.json web/bun.lock ./
RUN bun install --frozen-lockfile
COPY web/ ./
RUN bun run build-only
WORKDIR /src
COPY docs/ ./docs/
COPY scripts/generate-llms.ts ./scripts/generate-llms.ts
RUN bun scripts/generate-llms.ts
FROM golang:1.27.3-alpine AS server
ARG VERSION=dev
@@ -13,6 +17,7 @@ COPY go.mod go.sum ./
RUN go mod download
COPY . .
COPY --from=web /src/internal/infrastructure/assets/dist ./internal/infrastructure/assets/dist
COPY --from=web /src/internal/infrastructure/llmdocs/generated ./internal/infrastructure/llmdocs/generated
RUN go build -trimpath -ldflags "-s -w -X main.version=${VERSION}" -o /out/renewcms ./cmd/server
FROM alpine:3.22
+18 -2
View File
@@ -3,6 +3,7 @@ version: '3'
vars:
BINARY: renewcms
DIST_DIR: internal/infrastructure/assets/dist
LLMS_DIR: internal/infrastructure/llmdocs/generated
VERSION:
sh: git describe --tags --always --dirty
LDFLAGS: -s -w -X main.version={{.VERSION}}
@@ -32,6 +33,7 @@ tasks:
dev:api:
desc: Run the API with hot reload on :8080 (SPA not embedded)
deps: [build:llms]
cmds:
- air
@@ -231,22 +233,36 @@ tasks:
desc: Type-check and build the SPA into {{.DIST_DIR}}
dir: web
deps: [web:install]
sources: [src/**/*, public/**/*, index.html, vite.config.ts, tsconfig*.json, package.json, bun.lock]
sources: [src/**/*, public/**/*, vite/**/*, index.html, vite.config.ts, tsconfig*.json, package.json, bun.lock]
generates: ['../{{.DIST_DIR}}/index.html']
cmds:
- bun run build
build:llms:
desc: Generate llms.txt, llms-full.txt and openapi.json from the route catalogue and docs/ → {{.LLMS_DIR}}
deps: [web:install]
sources: [scripts/generate-llms.ts, web/src/data/apiCatalogue.ts, docs/api.md, docs/api/*.md, docs/llm/*.md, docs/configuration.md]
generates: ['{{.LLMS_DIR}}/llms-full.txt']
cmds:
- bun scripts/generate-llms.ts
build:
desc: Production binary for this machine → bin/{{.BINARY}}
deps: [build:web]
deps: [build:web, build:llms]
cmds:
- go build -trimpath -ldflags "{{.LDFLAGS}}" -o bin/{{.BINARY}}{{exeExt}} ./cmd/server
build:mcp:
desc: MCP server (stdio) for this machine → bin/{{.BINARY}}-mcp
cmds:
- go build -trimpath -ldflags "{{.LDFLAGS}}" -o bin/{{.BINARY}}-mcp{{exeExt}} ./cmd/mcp
release:
desc: Cross-compile and sign production binaries for all release targets → bin/ (needs RELEASE_SIGNING_KEY)
cmds:
- task: release:check
- task: build:web
- task: build:llms
- for: { var: RELEASE_TARGETS }
task: build:target
vars:
@@ -92,6 +92,8 @@ func writeContentTypeError(w http.ResponseWriter, err error) {
http.Error(w, apperr.ContentTypeKeyTakenErrorMessage, http.StatusConflict)
case errors.Is(err, domain.ErrHasEntries):
http.Error(w, apperr.ContentTypeHasEntriesErrorMessage, http.StatusConflict)
case errors.Is(err, domain.ErrReferenced):
http.Error(w, apperr.ContentTypeReferencedErrorMessage, http.StatusConflict)
case errors.Is(err, domain.ErrSchemaIncompatible):
http.Error(w, apperr.SchemaIncompatibleErrorMessage, http.StatusConflict)
case errors.Is(err, domain.ErrInvalidName):
+45 -1
View File
@@ -43,6 +43,49 @@ type entryResponse struct {
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Media map[string]any `json:"media"`
Relations map[string]any `json:"relations"`
}
type firstFieldBody struct {
Key string `json:"key"`
Type contenttype.FieldType `json:"type"`
Value any `json:"value"`
}
type relationBody struct {
ID uint32 `json:"id"`
ContentType string `json:"content_type"`
FirstField firstFieldBody `json:"first_field"`
}
type missingRelationBody struct {
ID uint32 `json:"id"`
Missing bool `json:"missing"`
}
func toRelationItem(item useCases.EntryRelation) any {
if item.Missing {
return missingRelationBody{ID: item.ID, Missing: true}
}
return relationBody{ID: item.ID, ContentType: item.ContentType, FirstField: firstFieldBody{Key: item.FirstField.Key, Type: item.FirstField.Type, Value: item.FirstField.Value}}
}
func toRelationsResponse(relations map[string]useCases.EntryRelations) map[string]any {
body := make(map[string]any, len(relations))
for key, held := range relations {
if !held.Many {
if len(held.Items) > 0 {
body[key] = toRelationItem(held.Items[0])
}
continue
}
items := make([]any, 0, len(held.Items))
for _, item := range held.Items {
items = append(items, toRelationItem(item))
}
body[key] = items
}
return body
}
type mediaBody struct {
@@ -81,6 +124,7 @@ func toResponse(typed useCases.TypedEntry) entryResponse {
CreatedAt: typed.CreatedAt,
UpdatedAt: typed.UpdatedAt,
Media: toMediaResponse(typed.Media),
Relations: toRelationsResponse(typed.Relations),
}
}
@@ -181,7 +225,7 @@ func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
page, err := h.ListUseCase.ListPage(useCases.ListEntriesCommand{ContentTypeKey: chi.URLParam(r, "key"), Page: query.Page, Size: query.Size, Sort: query.Sort})
page, err := h.ListUseCase.ListPage(useCases.ListEntriesCommand{ContentTypeKey: chi.URLParam(r, "key"), Page: query.Page, Size: query.Size, Sort: query.Sort, Query: r.URL.Query().Get("q")})
if err != nil {
writeEntryError(w, err)
return
+76
View File
@@ -0,0 +1,76 @@
package llms
import (
"io/fs"
"net/http"
"path"
"strings"
"github.com/go-chi/chi/v5"
)
const (
versionPlaceholder = "{{VERSION}}"
baseURLPlaceholder = "{{BASE_URL}}"
pageSuffix = ".md"
cacheControl = "public, max-age=300"
notBuiltNotice = "The LLM documentation was not generated for this build. Run `task build:llms`."
)
type Handler struct {
docs fs.FS
version string
baseURL string
}
func NewHandler(docs fs.FS, version string, publicURL string) *Handler {
return &Handler{
docs: docs,
version: version,
baseURL: strings.TrimRight(publicURL, "/"),
}
}
func (h *Handler) Register(r chi.Router) {
r.Get("/llms.txt", h.serve("llms.txt", "text/plain; charset=utf-8"))
r.Get("/llms-full.txt", h.serve("llms-full.txt", "text/plain; charset=utf-8"))
r.Get("/openapi.json", h.serve("openapi.json", "application/json"))
r.Get("/llms/{page}", h.page)
}
func (h *Handler) page(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "page")
if !strings.HasSuffix(name, pageSuffix) || strings.ContainsAny(name, "/\\") {
h.notFound(w)
return
}
h.write(w, path.Join("llms", name), "text/markdown; charset=utf-8")
}
func (h *Handler) serve(name string, contentType string) http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
h.write(w, name, contentType)
}
}
func (h *Handler) write(w http.ResponseWriter, name string, contentType string) {
if h.docs == nil {
h.notFound(w)
return
}
raw, err := fs.ReadFile(h.docs, name)
if err != nil {
h.notFound(w)
return
}
text := strings.NewReplacer(versionPlaceholder, h.version, baseURLPlaceholder, h.baseURL).Replace(string(raw))
w.Header().Set("Content-Type", contentType)
w.Header().Set("Cache-Control", cacheControl)
_, _ = w.Write([]byte(text))
}
func (h *Handler) notFound(w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(notBuiltNotice))
}
+1
View File
@@ -92,6 +92,7 @@ const SlugSuggestionHeader = "X-Slug-Suggestion"
const ContentTypeNotFoundErrorMessage = "content_type_not_found"
const ContentTypeKeyTakenErrorMessage = "content_type_key_taken"
const ContentTypeHasEntriesErrorMessage = "content_type_has_entries"
const ContentTypeReferencedErrorMessage = "content_type_referenced"
const InvalidContentTypeKeyErrorMessage = "invalid_content_type_key"
const InvalidIconErrorMessage = "invalid_icon"
const BuiltinTypeNotFoundErrorMessage = "builtin_type_not_found"
+3
View File
@@ -11,6 +11,7 @@ import (
"RenewCMS/api/handlers/entry"
"RenewCMS/api/handlers/frontend"
"RenewCMS/api/handlers/imagevariant"
"RenewCMS/api/handlers/llms"
"RenewCMS/api/handlers/media"
"RenewCMS/api/handlers/settings"
"RenewCMS/api/handlers/site"
@@ -20,6 +21,7 @@ import (
"RenewCMS/api/middleware"
"RenewCMS/api/pkg/authtoken"
"RenewCMS/internal/infrastructure/config"
"RenewCMS/internal/infrastructure/llmdocs"
"encoding/json"
"log"
"net/http"
@@ -493,6 +495,7 @@ func InitRoutes(container *UseCases, settings config.Settings) *chi.Mux {
apiRouter.Use(middleware.CrossOriginProtection(settings.PublicURL))
apiRouter.Use(chimiddleware.GetHead)
apiRouter.Get("/healthz", GetHealth)
llms.NewHandler(llmdocs.Docs, settings.Version, settings.PublicURL).Register(apiRouter)
apiRouter.Mount("/v1", backend)
apiRouter.Mount("/static/uploadedImages", staticimages.NewHandler(container.OpenMediaUseCase, container.ServeVariantUseCase))
apiRouter.Mount("/", frontend)
+43
View File
@@ -0,0 +1,43 @@
package main
import (
"RenewCMS/internal/infrastructure/mcpserver"
"context"
"flag"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
var version = "dev"
func main() {
allowDestructive := flag.Bool("allow-destructive", false, "also expose delete_article and delete_media")
showVersion := flag.Bool("version", false, "print the version and exit")
flag.Parse()
if *showVersion {
fmt.Println(version)
return
}
baseURL := os.Getenv("RENEWCMS_URL")
apiKey := os.Getenv("RENEWCMS_API_KEY")
if baseURL == "" || apiKey == "" {
log.Fatal("RENEWCMS_URL and RENEWCMS_API_KEY must be set")
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
server := mcpserver.New(mcpserver.NewClient(baseURL, apiKey, nil), mcpserver.Options{
Version: version,
AllowDestructive: *allowDestructive,
})
if err := server.Run(ctx, &mcp.StdioTransport{}); err != nil {
log.Fatal(err)
}
}
+67
View File
@@ -0,0 +1,67 @@
# Gotchas
> What trips up API clients: session-only routes, error texts, rate limits and draft visibility.
## Session-only routes
An API key cannot call these routes. They answer `403` with a plain-text body and no JSON:
```
HTTP/1.1 403 Forbidden
This action needs a real session.
```
- `/v1/api-key/*`, `/v1/system/*`, `POST /v1/auth/verify`, `DELETE /v1/auth/register`.
- Every activity route under `/v1/activity`.
- Writes on sites (`POST`, `PATCH`, `DELETE` under `/v1/site`, so a key cannot create a site) and on authors (`POST`, `PATCH`, `DELETE` under `/v1/author`).
- `PATCH /v1/settings`.
Variant routes under `/v1/media/{id}/variants` answer `401` to a key instead. The sign-in routes (login, logout, register, password reset) ignore a key and give no `403`.
When a task needs one of these routes, stop and tell the user to do it in the app. Do not try to log in with a password.
## Error texts are plain text
Errors are not JSON. The body is one sentence; branch on the status code, and show the sentence to the user.
| Status | Typical text |
| --- | --- |
| `400` | `The request cannot be processed due to a mismatch in the format of the body.` |
| `401` | `You must be logged in to access this resource.` |
| `403` | `This action needs a real session.`, `Only the owner can do this.`, `Only owners and admins can do this.`, `You must verify your account to access this resource.` |
| `404` | `Article not found`, `Image not found` |
| `429` | `Too many requests. Please try again later.` |
An invalid, unknown, expired or revoked key answers `401`, even on public routes. It is never treated as anonymous.
## Rate limit: 429
Each key may make 120 requests per minute. The `429` response carries a `Retry-After` header holding the seconds to wait:
```
HTTP/1.1 429 Too Many Requests
Retry-After: 46
Too many requests. Please try again later.
```
Sleep for `Retry-After` seconds, then retry once. Do not retry in a tight loop. Prefer one list call with `size=100` over many single reads.
## Draft versus online
- Anonymous callers and unverified users only see online articles. A draft answers `404` with `Article not found`, the same as an id that does not exist.
- A verified session or a key sees drafts as well. In lists, `counts.draft` is `0` for anonymous callers and `status=draft` answers an empty page.
- `POST /v1/article/` always creates a draft. Publishing is a separate call, `PATCH /v1/article/{id}/publish`.
- Sitemaps list online articles only.
## Writes
- A title cannot be changed after creation. Create a new article instead.
- `PATCH /v1/article/{id}` accepts `body`, `site_id`, `author_ids` and the SEO fields only. `{}` and `null` values answer `400`, except `cover_image_id` and `social_image_id`, where `null` removes the image.
- Request bodies are HTML even though responses default to markdown. Send `<p>` and `<h2>`, not markdown syntax, or it is stored literally.
- Ids in paths are unsigned integers. Anything else answers `400`.
## Permissions follow the key's creator
A key acts as the user who made it. A key made by a user who is neither owner nor admin cannot do what only owners and admins can, and it answers `403 Only owners and admins can do this.` Check `GET /v1/auth/me` to read the role of the key.
+81
View File
@@ -0,0 +1,81 @@
# Recipe: create, edit and publish an article
> Create a draft, replace its body, check its SEO, publish it and read it back, with an API key.
Set the key once. Every request below is real output from a running instance; ids and timestamps differ on yours.
```sh
export RENEWCMS_API_KEY=rcms_...
```
## 1. Create a draft
Titles are 3 to 200 characters and cannot be changed later. The request body is HTML; the response body is markdown unless you pass `?format=html` or `?format=json`.
```sh
curl -X POST "{{BASE_URL}}/v1/article/" \
-H "Authorization: Bearer $RENEWCMS_API_KEY" \
-H "Content-Type: application/json" \
-d '{"title":"How we price a bathroom renovation","body":"<p>A bathroom renovation is priced by room size, plumbing changes and finish level.</p>"}'
```
Status `201`:
```json
{"id":1,"title":"How we price a bathroom renovation","body":"A bathroom renovation is priced by room size, plumbing changes and finish level.","body_format":"markdown","is_online":false,"site_id":1,"authors":[],"created_at":"2026-10-23T01:11:16.767761797+02:00","updated_at":"2026-10-23T01:11:16.767761797+02:00","slug":"how-we-price-a-bathroom-renovation","excerpt":"","seo_title":"","seo_description":"","cover_image_id":null,"cover_image_alt":"","social_title":"","social_description":"","social_image_id":null,"canonical_url":"","noindex":false,"seo_dismissed":[]}
```
The article starts offline (`is_online: false`) on the default site.
## 2. Replace the body, move it to a site, set the excerpt
`PATCH` takes only `body`, `site_id`, `author_ids` and the SEO fields. At least one is required; `{}` answers `400`. Send `{"body": ""}` to empty a body.
```sh
curl -X PATCH "{{BASE_URL}}/v1/article/1" \
-H "Authorization: Bearer $RENEWCMS_API_KEY" \
-H "Content-Type: application/json" \
-d '{"body":"<h2>What drives the price</h2><p>Room size, plumbing changes and finish level.</p>","site_id":2,"excerpt":"What drives the price of a bathroom renovation."}'
```
Status `200`:
```json
{"id":1,"title":"How we price a bathroom renovation","body":"## What drives the price\n\nRoom size, plumbing changes and finish level.","body_format":"markdown","is_online":false,"site_id":2,"authors":[],"created_at":"2026-10-23T01:11:16.767761797+02:00","updated_at":"2026-10-23T01:11:16.771008847+02:00","slug":"how-we-price-a-bathroom-renovation","excerpt":"What drives the price of a bathroom renovation.","seo_title":"","seo_description":"","cover_image_id":null,"cover_image_alt":"","social_title":"","social_description":"","social_image_id":null,"canonical_url":"","noindex":false,"seo_dismissed":[]}
```
## 3. Check the SEO before publishing
An empty JSON object checks the saved article. Pass any SEO field to check a change without saving it.
```sh
curl -X POST "{{BASE_URL}}/v1/article/1/seo/check" \
-H "Authorization: Bearer $RENEWCMS_API_KEY" \
-H "Content-Type: application/json" \
-d '{}'
```
Status `200`:
```json
{"status":"suggestions","suggestions":[{"code":"desc_short","field":"seo_description","params":{"length":47,"min":70}},{"code":"cover_none","field":"cover_image_id","params":{}},{"code":"no_au","field":"author_ids","params":{}},{"code":"short","field":"body","params":{"length":66,"min":300}}],"slug":{"available":true,"suggestion":null}}
```
Suggestions never block publishing.
## 4. Publish
```sh
curl -X PATCH "{{BASE_URL}}/v1/article/1/publish" \
-H "Authorization: Bearer $RENEWCMS_API_KEY"
```
Status `200`, same article object with `"is_online":true`. `PATCH /v1/article/{id}/unpublish` reverses it.
## 5. Read it back without credentials
```sh
curl "{{BASE_URL}}/v1/article/1?format=markdown"
```
Before step 4 this answers `404` with the text `Article not found`, because anonymous callers only see online articles.
+62
View File
@@ -0,0 +1,62 @@
# Recipe: upload an image and attach it to an article
> Upload a file with multipart form data, find it in the library and use it as an article cover.
## 1. Upload
Send the file in a form field named `file`. PNG, JPEG, WEBP and SVG are accepted.
```sh
curl -X POST "{{BASE_URL}}/v1/media/" \
-H "Authorization: Bearer $RENEWCMS_API_KEY" \
-F "file=@north-wall.png"
```
Status `201`:
```json
{"id":1,"filename":"north-wall.png","url":"/static/uploadedImages/8d9be79c-5db6-4d1d-9f06-b5d1b15cb4f0.png","size":100,"content_type":"image/png","width":32,"height":32,"sha256":"7654144c6e1ee8939fa061fa8129763869fa3c2de55954053a53a965848ef09c","uploaded_by":"florian","created_at":"2026-10-23T01:11:24.228947139+02:00","used_in":0,"duplicate":false,"variant_count":0,"variant_size":0}
```
`url` is relative to the instance: the public address is `{{BASE_URL}}` followed by `url`. `duplicate: true` means the same bytes were already in the library.
## 2. Find an image
```sh
curl "{{BASE_URL}}/v1/media/?size=5" \
-H "Authorization: Bearer $RENEWCMS_API_KEY"
```
Status `200`:
```json
{"items":[{"id":1,"filename":"north-wall.png","url":"/static/uploadedImages/8d9be79c-5db6-4d1d-9f06-b5d1b15cb4f0.png","size":100,"content_type":"image/png","width":32,"height":32,"sha256":"7654144c6e1ee8939fa061fa8129763869fa3c2de55954053a53a965848ef09c","uploaded_by":"florian","created_at":"2026-10-23T01:11:24.228947139+02:00","used_in":0,"duplicate":false,"variant_count":0,"variant_size":0}],"total":1,"page":1,"size":5,"counts":{"all":1,"unused":1,"duplicates":0}}
```
Filter with `q`, `hash`, `filter` (`all`, `unused`, `duplicates`), `sort` and `variants`.
## 3. Attach it as the cover
An image is attached by id. `cover_image_alt` is the alternative text.
```sh
curl -X PATCH "{{BASE_URL}}/v1/article/1" \
-H "Authorization: Bearer $RENEWCMS_API_KEY" \
-H "Content-Type: application/json" \
-d '{"cover_image_id":1,"cover_image_alt":"A tiled bathroom wall"}'
```
Status `200`, the article object with `"cover_image_id":1` and `"cover_image_alt":"A tiled bathroom wall"`. Use `social_image_id` for the sharing image, and `null` to remove either image.
## 4. See where an image is used
```sh
curl "{{BASE_URL}}/v1/media/1/usage" \
-H "Authorization: Bearer $RENEWCMS_API_KEY"
```
```json
[{"type":"article","id":1,"title":"How we price a bathroom renovation","published":true,"fields":["cover"]}]
```
Deleting or merging an image that is in use changes those articles, so read this first.
+67
View File
@@ -0,0 +1,67 @@
# Recipe: paginate, filter and choose a body format
> List articles page by page, search and sort them, and read bodies as markdown, HTML or JSON blocks.
`GET /v1/article/` always answers an envelope, never a bare array:
```sh
curl "{{BASE_URL}}/v1/article/?format=html&size=5&page=1" \
-H "Authorization: Bearer $RENEWCMS_API_KEY"
```
```json
{"items":[{"id":1,"title":"How we price a bathroom renovation","body":"<h2>What drives the price</h2><p>Room size, plumbing changes and finish level.</p>","body_format":"html","is_online":true,"site_id":2,"authors":[],"created_at":"2026-10-23T01:11:16.767761797+02:00","updated_at":"2026-10-23T01:11:24.236138156+02:00","excerpt":"What drives the price of a bathroom renovation.","slug":"how-we-price-a-bathroom-renovation","seo_status":"suggestions","seo_suggestions":3}],"total":1,"page":1,"size":5,"counts":{"all":1,"online":1,"draft":0,"suggestions":1}}
```
In JSON, `<` and `>` are escaped as `<` and `>`; a JSON parser returns the plain characters.
## Walking every page
1. Request `page=1` with the `size` you want (`5`, `25`, `50` or `100`).
2. Read `total` and `size`. The number of pages is `ceil(total / size)`.
3. Request the next pages until `page * size >= total`. A page past the end answers `200` with `items: []`, so an empty `items` also ends the loop.
Ordering is applied to the whole list before slicing and ends with the id, so pages never overlap or skip.
## Filters
Combine them freely.
| Parameter | Example | Effect |
| --- | --- | --- |
| `q` | `q=grout` | Title contains the text, ignoring case and accents. Up to 200 characters. |
| `status` | `status=draft` | `online` or `draft`. |
| `site` | `site=renew-blog` | Only that site's articles. |
| `seo` | `seo=suggestions` | `ready`, `suggestions` or `hidden`. |
| `sort` | `sort=title:asc` | `title`, `status`, `created_at` or `updated_at`, then `:asc` or `:desc`. Default `updated_at:desc`. |
`counts` ignores every filter, so tab totals do not move while searching. `total` follows the filters.
```sh
curl "{{BASE_URL}}/v1/article/?site=renew-blog&status=draft&sort=title:asc&q=grout" \
-H "Authorization: Bearer $RENEWCMS_API_KEY"
```
```json
{"items":[{"id":2,"title":"Draft about grout","body":"x","body_format":"markdown","is_online":false,"site_id":2,"authors":[],"created_at":"2026-10-23T01:12:24.922895943+02:00","updated_at":"2026-10-23T01:12:24.926728869+02:00","excerpt":"","slug":"draft-about-grout","seo_status":"suggestions","seo_suggestions":4}],"total":1,"page":1,"size":25,"counts":{"all":2,"online":1,"draft":1,"suggestions":2}}
```
## The `format` parameter
| Value | `body` | `body_format` |
| --- | --- | --- |
| absent or `markdown` | markdown string | `markdown` |
| `html` | the stored HTML | `html` |
| `json` | array of blocks | `json` |
It applies to every article route, including the writes. Request bodies of `POST` and `PATCH` stay HTML whatever the format. An invalid `format` is reported before any other error.
## Invalid values
A bad `page`, `size`, `status`, `sort` or `seo` answers `400` with a plain-text body:
```
The request cannot be processed due to a mismatch in the format of the body.
```
Media lists paginate the same way (`GET /v1/media/?page=2&size=50`) with their own `counts`.
+66
View File
@@ -0,0 +1,66 @@
# Recipe: sites and sitemaps
> Create a site (session only), move an article onto it and read its public sitemap.
An article belongs to one site. A site has a `key` (a slug used in URLs) and a `base_url` (the public address its pages are served from).
## 1. List the sites
```sh
curl "{{BASE_URL}}/v1/site/" \
-H "Authorization: Bearer $RENEWCMS_API_KEY"
```
```json
[{"id":1,"name":"Default","key":"default","base_url":"http://localhost:18080","default_social_image_id":null,"default_robots":"index","locale":null,"is_default":true,"article_count":0,"site_name":"","title_template":"%title% | %site%","default_description":""}]
```
## 2. Create a site: not with a key
Creating, editing, defaulting and deleting a site need a browser session from the owner. A key answers `403`:
```sh
curl -X POST "{{BASE_URL}}/v1/site/" \
-H "Authorization: Bearer $RENEWCMS_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name":"x","key":"x","base_url":"https://x.example"}'
```
```
HTTP/1.1 403 Forbidden
This action needs a real session.
```
Ask the owner to create the site in the app, or send the request with the owner's `jwt` cookie. With a session the same request answers `201`:
```json
{"id":2,"name":"Renew blog","key":"renew-blog","base_url":"https://blog.renew.example","default_social_image_id":null,"default_robots":"index","locale":null,"is_default":false,"article_count":0,"site_name":"","title_template":"%title% | %site%","default_description":""}
```
## 3. Put an article on the site
Use the site `id` as `site_id`:
```sh
curl -X PATCH "{{BASE_URL}}/v1/article/1" \
-H "Authorization: Bearer $RENEWCMS_API_KEY" \
-H "Content-Type: application/json" \
-d '{"site_id":2}'
```
## 4. Read the sitemap
The sitemap is public and lists the online articles of one site, by its `key`:
```sh
curl "{{BASE_URL}}/v1/site/renew-blog/sitemap"
```
```json
[{"url":"https://blog.renew.example/how-we-price-a-bathroom-renovation","modified_at":"2026-10-22T23:11:24Z","noindex":false}]
```
`url` is the site's `base_url` plus the article slug. Drafts are not listed. The response header `X-Total-Count` holds the number of entries. Page with `page` and `size` (`25`, `50`, `100` or `500`, default `100`); any other `size` answers `400`. An unknown key answers `404` with `site_not_found`.
List only one site's articles with `GET /v1/article/?site=renew-blog`.
+22
View File
@@ -0,0 +1,22 @@
# LLM documentation
A running instance serves its own documentation for language models, versioned with the binary:
| URL | Content |
| --- | --- |
| `/llms.txt` | Short index with links, following llmstxt.org. |
| `/llms-full.txt` | Every page below in one file. |
| `/llms/<page>.md` | One page: `api-reference`, `api`, `articles`, `api-keys`, `gotchas`, `recipe-articles`, `recipe-media`, `recipe-sites`, `recipe-pagination`, `configuration`. |
| `/openapi.json` | OpenAPI 3.1 description of the routes in the catalogue. |
All of them are public. `{{VERSION}}` and `{{BASE_URL}}` in the sources are replaced by the binary's version and `PUBLIC_URL` when served.
## How it is built
`task build:llms` runs `scripts/generate-llms.ts` (bun) and writes into `internal/infrastructure/llmdocs/generated/`, which is gitignored and embedded in the binary. `task build`, `task release`, `task dev:api` and the Docker image run it first. Without it the routes answer 404 with a notice.
- The API reference and `openapi.json` come from `web/src/data/apiCatalogue.ts`, the same file the Integration page renders. Edit the catalogue, not the output.
- `docs/api.md`, `docs/api/*.md`, the variables table of `docs/configuration.md` and every `docs/llm/*.md` are included as written. A page in `docs/llm/` starts with `# Title`, then a `> one-line summary` used by `llms.txt`.
- Recipes in `docs/llm/` hold real responses. Re-capture them when a response shape changes.
`TestRouterRoutesAreInTheCatalogue` fails when a route of `api/router.go` is missing from the catalogue. Routes still undocumented are listed in `routesNotYetInTheCatalogue` in `test/api_catalogue_drift_test.go`; remove an entry once the route is documented.
+37
View File
@@ -0,0 +1,37 @@
# MCP server
`cmd/mcp` builds `renewcms-mcp`, a stdio [MCP](https://modelcontextprotocol.io) server for Claude Desktop, Claude Code, Cursor and similar clients. It is an HTTP client of the public API: it holds no database access and sends the API key as `Authorization: Bearer`, so what the key's user may do is the limit of what the model may do.
Build it with `task build:mcp` (`bin/renewcms-mcp`).
## Configuration
| Name | Description |
| --- | --- |
| `RENEWCMS_URL` | Address of the instance, for example `https://cms.example`. |
| `RENEWCMS_API_KEY` | An API key created at `/integration/api-keys`. |
They belong to the MCP binary only and are not server variables.
```json
{
"mcpServers": {
"renewcms": {
"command": "/path/to/renewcms-mcp",
"env": { "RENEWCMS_URL": "https://cms.example", "RENEWCMS_API_KEY": "rcms_..." }
}
}
}
```
## Tools
`list_articles`, `get_article`, `create_article` (always a draft), `update_article_body`, `publish_article`, `check_seo`, `list_media`, `upload_media` (local `path`, or `base64` with `filename`), `list_sites`, `get_sitemap`.
`--allow-destructive` adds `delete_article` and `delete_media`.
Routes that need a browser session, such as creating a site, are not exposed. API errors come back as tool errors with the status and the plain-text message.
## Resources and prompts
The resource `renewcms://docs/llms-full.txt` is the instance's own [`/llms-full.txt`](llms.md), so the model reads the documentation of the exact version it talks to. The prompt `write_and_publish_article` drafts, checks the SEO and asks before publishing.
+4
View File
@@ -43,3 +43,7 @@ Each body lives in `docs/releases/<tag>.md`. Publish with `tea releases create -
| `v3.4.0-beta` | Custom content types |
| `v3.4.1-beta` | Media field and security updates |
| `v3.4.2-beta` | Security and privacy hardening |
| `v3.5.0-beta` | Relation field |
| `v3.5.1-beta` | Relation picker fix |
| `v3.5.2-beta` | LLM documentation and MCP server |
| `v3.5.3-beta` | OpenAPI response schemas |
+40
View File
@@ -0,0 +1,40 @@
This release adds a Relation field to custom content types, so an entry can point at entries of another type.
## New
**Relation field**
- A content type can now have a Relation field that links to another content type. Three kinds are available: one to one (a target can be used by only one entry), one to many (one target per entry) and many to many (up to 50 targets per entry).
- Entries are linked through a searchable picker in the entry form. Chosen targets appear as chips labelled with the first field of the target entry, or "Entry N" when that field is empty.
- Entry lists and cards show the linked entries of each relation column.
- When a linked entry is deleted afterwards, the relation is shown as missing instead of breaking the page. A required relation with a missing target must be fixed before the entry can be saved.
- The schema builder previews the inverse side of a relation, and the schema review dialog explains the impact of adding or removing one.
## Improvements and fixes
- Deleting a content type that another type points at is refused, and the delete dialog tells you which types depend on it.
- Adding a required relation to a type that already has entries is refused with the usual schema incompatibility message.
- The right side panel of the article editor no longer overflows vertically on short screens.
- The web app is split into smaller chunks, so the first page load transfers less code.
## API
- Changed: every entry answer (`POST`, `PUT` and `GET` of one entry, and each item of a list) carries a top-level `relations` object keyed by relation field key. Each value holds `id`, `content_type` and `first_field` for an existing target, or `id` and `missing: true` for a deleted one. Many to many fields return an array.
- `GET /v1/content-type/{key}/entry` accepts `q`, a text search over the entries of the type, applied before pagination. `total` reflects the filtered count.
- `POST /v1/content-type` and `PUT /v1/content-type/{key}` accept `type: "relation"` fields with `relation: {"content_type", "kind"}`. A bad definition answers `422` `invalid_field`.
- Entry writes answer `422` `invalid_entry: <key>: required` or `invalid_entry: <key>: type`, and `409` `invalid_entry: <key>: unique` for a one to one target already taken.
- `DELETE /v1/content-type/{key}` answers `409` `content_type_referenced` while another type has a relation to it.
## Under the hood
- New feature specs and tests cover the backend and the web app, in `features/relation_field_type.feature` and `features/relation_field_spa.feature`.
- Vendor chunk splitting is configured in `web/vite/vendorChunks.ts` and covered by a spec.
## Upgrading
- Replace the binary, or pull the new image. Back up the database first as usual.
- No schema migration and no new environment variable. Existing content types and entries are unchanged.
## Known limitations
- Relation search filters entries in memory, so it is meant for types with a moderate number of entries.
- The inverse side of a relation is only shown in the builder preview. The target type's form, list and API do not list the entries pointing at it.
+9
View File
@@ -0,0 +1,9 @@
This release fixes the Relation field picker, which could not load any entries.
## Improvements and fixes
- Choosing a target for a Relation field no longer fails with "Couldn't load" and a `400` error. The picker asked for pages of 10 entries, a size the entry list refuses, and now asks for 25.
## Upgrading
- Replace the binary, or pull the new image. No schema migration and no new environment variable.
+28
View File
@@ -0,0 +1,28 @@
This release lets language models read and use a RenewCMS instance: the server publishes its own documentation, an OpenAPI description, and a separate MCP server drives the API with a key.
## New
**Documentation for language models**
- Every instance serves `/llms.txt` (a short index), `/llms-full.txt` (all the documentation in one file), `/llms/<page>.md` (one page each) and `/openapi.json`. They are public, and carry the version and address of the instance that serves them.
- The pages include the API reference, the API key and article guides, ready-to-run recipes with real responses (publish an article, upload and attach an image, sites and sitemaps, pagination and formats), and a gotchas page on session-only routes, error texts, rate limits and draft visibility.
**MCP server**
- The new `renewcms-mcp` binary is a stdio MCP server for Claude Desktop, Claude Code, Cursor and similar clients. It calls the public API with an API key, so the key's rights limit what the model can do.
- Tools: list, get, create, update the body of and publish articles, check SEO, list and upload media, list sites and read a sitemap. Deletion tools are only offered with `--allow-destructive`.
- It exposes the instance's `llms-full.txt` as a resource and a prompt that drafts, checks and asks before publishing. Setup is in `docs/mcp.md`.
## API
- `GET /llms.txt`, `GET /llms-full.txt`, `GET /llms/{page}` and `GET /openapi.json` are public routes outside `/v1`. They answer `404` with a notice when the build did not generate them.
## Under the hood
- The API reference and `openapi.json` are generated from `web/src/data/apiCatalogue.ts` by `task build:llms`, which `task build`, `task release` and the Docker image run first.
- A new test fails when a route of the router is missing from the catalogue. Twenty-five existing routes (content types, entries, builtin types, image variants, media variants and the user lookup) are still undocumented and listed as exceptions in that test.
- The catalogue now records the success status of each endpoint.
- `task build:mcp` builds the MCP server. `task release` does not include it yet.
## Upgrading
- Replace the binary, or pull the new image. No schema migration and no new environment variable.
- The MCP server reads `RENEWCMS_URL` and `RENEWCMS_API_KEY` in its own process; the server does not need them.
+13
View File
@@ -0,0 +1,13 @@
This release fixes the OpenAPI description served at `/openapi.json`, whose response schemas were empty.
## Improvements and fixes
- Every successful response in `/openapi.json` now has a schema (object properties, required keys, array items and scalar types) instead of an empty one, so client generators produce typed models. The schemas are inferred from the sample responses of the API reference.
## Upgrading
- Replace the binary, or pull the new image. No schema migration and no new environment variable.
## Known limitations
- Because the schemas come from sample responses, a field that is `null` in a sample is typed `null`, a field missing from a sample is missing from its schema, and timestamps are plain strings.
+380
View File
@@ -0,0 +1,380 @@
Feature: Relation field in the SPA
As an owner or admin building a content type, and as a verified user filling an entry
I want a Relation field that links an entry to entries of another content type
So that structured content can point at other structured content
Background:
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
And API errors are plain text
And this slice changes only web/ (and web/visual); the backend of features/relation_field_type.feature is done
And the design is docs/design/screens/schema-later.md section 7 (3 states) and the board group "7 Relations" of "RenewCMS Screens Schema.dc.html" with SchemaFrame.dc.html; the frame markup wins over prose for layout
And the registry is lib/fieldTypes with lib/entryEditors, the single source for the builder, the list cells and the entry form; no screen branches on the type name "relation" where a registry property can say it
And the tags "Later" and "Relation columns: later" / "Relation field: later" drawn on the board are not rendered; the feature ships
And a relation value is an id (uint32 of at least 1) or null for one_to_one and one_to_many, and an array of ids ([] when empty, at most 50) for many_to_many
And a field loaded from the API has "relation": {"content_type","kind"} with kind "one_to_one", "one_to_many" or "many_to_many"
And every entry answer (POST 201, PUT 200, GET one, each list item) carries a top-level "relations" object keyed by relation field key: {"id","content_type","first_field":{"key","type","value"}} for an existing target, or {"id","missing":true}; an array of these for many_to_many; the label of a target is its first_field formatted by the same rule as the entry list, and "Entry N" when null
And the API refuses with 422 "invalid_entry: <key>: required", "invalid_entry: <key>: type", 409 "invalid_entry: <key>: unique", 409 "schema_incompatible" for a new required relation on a type with entries, 422 "invalid_field" for a bad definition, and 409 "content_type_referenced" when deleting a target type
And the picker searches GET /v1/content-type/{target}/entry?q=&page=&size= and reads total from the answer
And the inverse side is shown in the builder preview only; the target type's form, list and API are unchanged
And sentence case, buttons are verbs, every string goes through t() and has a French entry in i18n/messages.ts
And a copy tagged "(proposed copy)" is not in the design and is the coder's single point of change
And the sample data is the board's: Event with Venue (one_to_many) and Speakers (many_to_many); venues "Rue Verte hall" (Lyon · 120 seats), "Rue Verte yard" (Lyon · outdoor), "Rue du Port studio" (Nantes · 24 seats); speakers "Ines Duarte" and "Jonas Pereira"; entries 42 "Lime plaster workshop", 41 "Heat pumps: what the numbers say", 40 "Open day at the Rue Verte site"
Scenario Outline: Relation in the registry
Given the registry entry for "relation"
Then <property> is <value>
Examples:
| property | value |
| type name in the API | relation (the eighth entry, after media) |
| label | Relation |
| description | Links to another type's entries (proposed copy) |
| icon | lucide:link |
| control | RelationField |
| pairs with a neighbour | no, full width |
| empty value | null for one_to_one and one_to_many, [] for many_to_many |
| initial on create | the empty value; a relation has no default, so no "Default" tag ever shows |
| initial on edit | the stored id or ids |
| supports unique | no |
| supports limits | no |
| supports default | no |
| supports choices | no |
| counter | none |
| list cell | chips: one chip, two chips and "+N", or "–"; not sortable |
| sample in the API preview | null for a single kind, [] for many_to_many |
Scenario: A loaded relation field is not shown as Text
Given GET /v1/content-type/events returns a field {"key":"venue","label":"Venue","type":"relation","required":false,"unique":false,"default":null,"min":null,"max":null,"options":[],"relation":{"content_type":"venues","kind":"one_to_many"}}
Then the builder, the entry form and the list resolve it to the relation entry of the registry, never to the fallback type "text"
Scenario Outline: Client validation of a relation value
Given a <kind> relation "Venue" that is <required>
When the value is <value>
Then the rule is <rule>
Examples:
| kind | required | value | rule |
| single | required | null | required |
| single | optional | null | none |
| single | required | 3 | none |
| single | optional | 0 | type |
| single | optional | "3" | type |
| single | optional | [3] | type |
| many_to_many | required | [] | required |
| many_to_many | optional | [] | none |
| many_to_many | optional | [11, 12] | none |
| many_to_many | optional | [11, 11] | type |
| many_to_many | optional | 11 | type |
| many_to_many | optional | 51 ids | type |
Scenario Outline: Messages of a relation field
Given a relation field labelled "Venue" whose related type is named "Venues"
Then the message of the rule <rule> reads <message>
Examples:
| rule | message |
| required | Choose a Venue. (proposed copy) |
| type | Venue must point to an existing entry. (proposed copy) |
| unique | That Venue is already used by another entry. (proposed copy) |
| min | not produced for relation |
| max | not produced for relation |
| options | not produced for relation |
Scenario: The type gallery gains Relation
Given the inspector of a field that can still change type
Then the tile "Relation" with the link icon is the last tile, selectable like the others
And on a saved field the other tiles are dimmed to 40 % and not selectable, as for any locked type
Scenario: Adding a relation field
Given Events and a second content type Venues exist
When the user activates "Add field", types the label "Venue" and chooses the tile "Relation"
Then the new row shows the badge "New", the key "venue" (Auto, editable) and the chip reads "Unsaved changes"
And the inspector reads "Field: Venue" and shows, after the Type tiles and in this order, the select "Related content type" with the help "Choose the content type this field points to." and the group "How are they connected?"
And no related type is chosen yet and "Save" cannot send a relation without one (proposed copy for the message: "Choose a related content type.")
Scenario: The related content type select
Given the user is editing Events
Then the select lists the other content types by name, and Events itself, each with its key as a hint (proposed)
And choosing Venues sets the sentences of the preview to "Venue" and "Events"
Scenario: Three shape cards (design "Relation in the builder")
Given the related type is Venues, the owner Events
Then three cards are shown in a row (one column on mobile), each with a diagram of squares and a line, a title and a sentence
| card | sentence |
| One to one | Each Event has one Venue, and each Venue has one Event. |
| One to many | Each Event has one Venue. A Venue has many Events. |
| Many to many | Each Event has many Venues, and each Venue has many Events. |
And the selected card has the primary border and the sand fill with --rc-on-sand text, the others the accented border
And the cards are a radio group, one is selected at a time, and a new relation starts with "One to many" selected (proposed default)
Scenario: The preview of both sides
Given "One to many" is selected with Event and Venue
Then a block with the elevated background reads "Each Event has [one] Venue" and "Each Venue has [many] Events" followed by the muted text `· shown on Venue as the field "Events"`
And the bracketed words are drawn as selects showing the chosen kind and follow the selected card
And below it two cards "Event" (Venue: chip "Rue Verte hall") and "Venue" (Events: chips "Open day", "Lime plaster workshop" and "+1") illustrate both sides, side by side on desktop and stacked on mobile
And the inverse field is not stored anywhere and nothing about it is sent
Scenario Outline: The preview follows the kind
Given the owner Event and the related type Venue
When the user selects <card>
Then the sentences read <owner side> and <inverse side>
Examples:
| card | owner side | inverse side |
| One to one | Each Event has one Venue | Each Venue has one Event |
| One to many | Each Event has one Venue | Each Venue has many Events |
| Many to many | Each Event has many Venues| Each Venue has many Events |
Scenario: Plural and names come from the types
Given the owner "Events" and the related type "Venues"
Then "Event"/"Events" and "Venue"/"Venues" in the sentences are the singular and plural forms drawn from the type names (proposed rule: singular is the name without a final "s"; the field label is used for the singular of the related side)
Scenario: The PUT and POST body of a relation field
Given a relation "Venue" to "venues", kind "One to many", Required off
When the type is saved
Then the field is sent as {"key":"venue","label":"Venue","type":"relation","required":false,"unique":false,"default":null,"min":null,"max":null,"options":[],"relation":{"content_type":"venues","kind":"one_to_many"}}
And every other field is sent with "relation": null
And a round trip of the loaded field to the payload produces no change
Scenario: The inspector of a saved relation (locked) (state not drawn; proposed copy)
Given Events with a saved relation "Venue" as its field
When the user selects its row
Then the Label input and the Required switch are editable
And the Key is locked with "Used in the API, so it can't change."
And the legend of the tiles reads "Type" with a lock and "Can't change after saving", Relation is selected and the other tiles are dimmed to 40 %
And "Related content type" and the three cards are shown disabled with the selected card kept, under the note "The related type and the connection can't change after saving. (proposed copy)"
Scenario: A required relation added to a type with entries is refused first
Given Events with 12 entries and a new relation "Venue" that is required
When the user activates Save
Then no PUT is sent and the dialog "Review changes to Events" opens
And the row "Add Venue" has the warning badge "Can't be applied" and the text "Relation, required. A relation can't have a default, so the 12 existing entries would have no Venue. Make Venue optional to add it. (proposed copy)"
And "Back to editing" is enabled and "Apply changes" is disabled, so pressing it sends nothing
And an optional relation shows the clean row "Relation, optional. 12 entries are unaffected. (proposed copy)" with "Apply changes" enabled
Scenario: The server answers on the builder
Given the user applies a type with a relation
When the server answers <status> "<body>"
Then <result>
Examples:
| status | body | result |
| 409 | schema_incompatible | the existing "Nothing was changed" refusal flow runs unchanged |
| 422 | invalid_field | the existing invalid-field failure of the builder is shown, the edits stay |
Scenario: Deleting a type that another type points at (proposed copy)
Given Venues is the target of the relation on Events and Venues has no entries
When the user confirms the delete of Venues
Then the API answers 409 "content_type_referenced"
And the existing delete failure surface shows the title "You can't delete Venues yet" and the text "Events has a field that points to Venues. Remove that field first. (proposed copy)"
And the type is still listed
Scenario: The builder is for owners and admins
Given a verified user who is neither owner nor admin
Then the builder keeps its existing "You don't have access to Schema" state and no relation control is rendered
Scenario: Where the controls sit
Given Events with the fields Title, Venue and Speakers
Then the controls follow the schema order, full width in the 760 px column, each with its label ("Venue", "Speakers") in weight 500
Scenario: Single relation, empty, focused search (design "Venue")
Given /content/events/42 whose venue is null
When the user focuses the "Venue" control and types "rue"
Then the input shows the search icon, the typed text and "Search to add"
And a popover list under the input shows rows of at least 40 px (48 on mobile) with the title in weight 500 and a second muted 12/18 line, each row a button
| title | second line |
| Rue Verte hall | Lyon · 120 seats |
| Rue Verte yard | Lyon · outdoor |
| Rue du Port studio | Nantes · 24 seats|
And the first row has the elevated background
And the title is the first field of the related type and the second line is the next fields formatted as the entry list does, joined by " · " (up to 2 fields, proposed rule)
Scenario: Picking a single target
When the user activates the row "Rue Verte hall"
Then the list closes, the control shows one chip "Rue Verte hall" with an x, the value becomes 3, and the chip of the page reads "Unsaved changes"
And the live region says "Venue set to Rue Verte hall. (proposed copy)" and the focus stays in the control
And the chip's x removes it, sets the value to null, and says "Venue cleared. (proposed copy)"
Scenario: Many relation (design "Speakers")
Given Events with speakers [11, 12]
Then the control is a bordered box (1 px accented, min height 40, 44 on mobile) holding the chips "Ines Duarte" and "Jonas Pereira", each 24 px high (32 on mobile) with an x, then the muted text "Search to add"
And the help line under it reads "An event can have many speakers."
And a chip is a sand chip with --rc-on-sand text, weight 500
Scenario: Adding and removing in a many relation
When the user types "ines" in the control and activates the row "Ines Duarte"
Then the chip is added at the end in the chosen order and the row no longer appears in later results
When the user activates the x of a chip, or presses Backspace in the empty input
Then that chip is removed and the live region says "Ines Duarte removed from Speakers. (proposed copy)"
And a 51st target cannot be added: the search shows "You can add up to 50. (proposed copy)" and no row is selectable
Scenario: One to one targets already used (proposed copy)
Given a one_to_one relation
When the server answers 409 "invalid_entry: room: unique"
Then "That Venue is already used by another entry." shows under the control with a circle-alert icon, the error border applies, the chip reads "Not saved" and the focus moves to the control
Scenario: The search request
When the user types "rue"
Then the input is trimmed and debounced, and only GET /v1/content-type/venues/entry?q=rue&page=1&size=<page size> is sent
And the response replaces the list and a stale answer never overwrites a newer one
And with an empty input the first page of the type is listed without q (proposed)
Scenario: Picker loading (not drawn; proposed copy)
Given the search has not answered
Then after 150 ms the list shows three skeleton rows of the same height, with "Searching… (proposed copy)" announced politely, and no row is selectable
Scenario: No match (not drawn; proposed copy)
Given the search answers total 0 for "zzz"
Then the list shows `No Venues match "zzz"` (proposed copy) and the action "Clear search" that empties the input
And when the related type has no entries at all the list reads "No Venues yet. Add one in Content, then come back. (proposed copy)"
Scenario Outline: Search failures (not drawn; proposed copy)
Given the search answers <outcome>
Then <result>
Examples:
| outcome | result |
| 500 | the list shows "Couldn't load Venues" / "Check your connection and try again." with "Try again" (proposed copy) |
| a network error | the same |
| 429 | the existing rate-limit countdown alert |
| 401 | the global redirect, no local copy |
| 404 | "Couldn't load Venues" as for 500, since the related type may have been deleted (proposed copy) |
Scenario: Load more in the list
Given the search has more results than one page
When the user scrolls to the end of the list or activates "Load more" (proposed copy)
Then the next page is appended and the focus stays on the active row
Scenario: Keyboard
Given the control is focused and the list is open
Then ArrowDown and ArrowUp move the active row, Enter picks it, Esc closes the list and keeps the typed text, Tab leaves the control
And in a many relation Backspace on an empty input removes the last chip and chips are reachable with ArrowLeft
Scenario: A missing target (not drawn; proposed copy)
Given relations.venue is {"id":3,"missing":true}
Then the control shows a dashed chip "Entry no longer exists (proposed copy)" with an x and the help "You can still save. The entry keeps the link until you change it. (proposed copy)" when the field is optional
And when the field is required the help reads "Venue is required. Choose another to save. (proposed copy)", and saving with the missing target sends no request, shows the required message and focuses the control
And saving an optional field with the missing target sends the same id
Scenario: Required and empty
Given a required relation with no target
When the user activates "Save"
Then no request is sent, the error "Choose a Venue." replaces the help line, the border is --ui-error, the chip reads "Not saved" and the focus goes to the control
And only the first field in schema order with an error takes the focus
When the user picks a target
Then the error goes and the chip reads "Unsaved changes"
Scenario: Saving
Given the PUT has not answered
Then the form is dimmed to 70 %, the chips and the input are not operable and the list cannot open
And Save reads "Saving…"
Scenario Outline: What the control shows and sends
Given the loaded value <loaded> with relations <relations>
When the user <action> and activates "Save"
Then the control shows <shown>
And the data holds <sent>
Examples:
| loaded | relations | action | shown | sent |
| null | none | saves with nothing changed | no chip | "venue": null |
| 3 | existing venue 3 | saves with nothing changed | the chip "Rue Verte hall"| "venue": 3 |
| 3 | missing venue 3 | saves with nothing changed | the missing chip | "venue": 3 |
| 3 | existing venue 3 | picks "Rue Verte yard" | the chip "Rue Verte yard"| "venue": 4 |
| 3 | existing venue 3 | activates the x | no chip | "venue": null |
| [11] | speaker 11 | adds Jonas Pereira | two chips | "speakers": [11, 12] |
| [11,12] | speakers 11, 12 | removes both | no chip | "speakers": [] |
Scenario: Create payload with relations
Given /content/events/new with Title "Open day", Venue left empty and Speakers left empty
When the user activates "Save"
Then POST /v1/content-type/events/entry is sent once with "venue": null and "speakers": [] among the other keys, never absent
And with Rue Verte hall picked it holds "venue": 3, a JSON number
Scenario: Right after a pick the control uses the picked row
Given the user picks "Rue Verte yard" from the results
Then before any save the chip shows its title from the result and no extra request is made
When the PUT answers 200 with relations.venue
Then the control is rebuilt from the answered relations object
Scenario: Dirty tracking of a relation value
Given an entry whose venue is 3
When the user picks 4 then picks 3 again
Then the chip reads "Saved", "Save" is disabled and the leave guard does not prompt
And for a many relation the same ids in another order count as changed
Scenario Outline: Server answers for a relation field
Given the client found no error and the PUT or POST is sent
When the server answers <status> "<body>"
Then <result>
Examples:
| status | body | result |
| 422 | invalid_entry: venue: required | "Choose a Venue." under the control, error border, chip "Not saved", focus on the control |
| 422 | invalid_entry: venue: type | "Venue must point to an existing entry." (proposed copy) under the control, chip "Not saved" |
| 409 | invalid_entry: venue: unique | the one to one copy above |
| 422 | invalid_entry: venue: unknown_field | the read-only reload alert of features/content_entry_editor.feature, same as for media |
Scenario: Layout of the generated form with a relation
Given a boolean, a number or a date field before the relation
Then the relation never pairs and is full width at every viewport
Scenario: Mobile form
Given a 390 px viewport
Then chips are 32 px high, rows are 48 px high, the input is 44 px high, and the list opens as a bottom sheet (proposed) or under the input as drawn
Scenario Outline: The relation cell (design "Relation in the list")
Given the entry list of Events with the columns Title, Starts on, Venue and Speakers
And the item's relations <relations>
Then the cell shows <cell>
Examples:
| relations | cell |
| venue 3 "Rue Verte hall" | one chip "Rue Verte hall" (20 px high, 6 px padding) |
| speakers 11, 12 | two chips "Ines Duarte" and "Jonas Pereira" |
| speakers 11, 12 and two more | two chips and the muted 12 px text "+2" |
| no venue | the muted "–" |
| an empty speakers list | the muted "–" |
| a missing venue | a dashed chip "Entry no longer exists" (proposed copy) |
Scenario: Columns of the board (desktop)
Given the items 42, 41 and 40
Then the grid reads ID, Title, Starts on, Venue, Speakers with the columns 48 px, 1.4fr, 110 px, 200 px, 200 px
And row 42 shows "Rue Verte hall" and "Ines Duarte", "Jonas Pereira", "+2"; row 41 shows "–" and "Jonas Pereira"; row 40 shows "Rue Verte yard" and "–"
And rows stay 48 px high and the header is 36 px high on the elevated background
And the note "One chip for a single relation. Up to two chips and a "+N" for many. Empty shows a dash." is a design annotation and is not rendered
Scenario: The mobile card
Given a 390 px viewport and Venue and Speakers among the columns
Then each card lists the title, then a line "Venue" (12 px muted) followed by its chips, then a line "Speakers" followed by its chips (wrapping), and "–" for none
And the card keeps its minimum height
Scenario: Columns menu
When the user opens "Columns"
Then "Venue" and "Speakers" are listed with the link icon, their keys, and a checkbox like other fields
And the cap of 6, Reset and the stored choice work as for any field
And a relation column is not sortable and has no sort icon and no aria-sort
Scenario: Cell data comes from the item
Then the chips are read from each item's own "relations" object with no extra request
And the plain text of a relation cell (card title, page title) reads the labels joined by ", " or "–", never the numeric id
Scenario: Relation as the first column
Given a type whose first field is a relation
Then the first column still links to the editor and the chips are the link content
And the page title and breadcrumb of such an entry read "Entry 42"
Scenario: Accessibility of the control
Then the control is a combobox with role="combobox", aria-expanded, aria-controls and aria-activedescendant on the input, labelled by the field label
And the list is role="listbox" with role="option" rows
And chips are a group labelled by the field label, each x is a button named "Remove Ines Duarte from Speakers"
And required adds aria-required, the error text has an id and aria-invalid and aria-describedby point at it then at the help
And one polite live region announces added, removed and cleared values and the result count ("3 results" / "No results", proposed copy)
And mobile targets are 44 px
Scenario: Accessibility of the builder
Then the shape cards are a radio group with a visible selected state that is not only a colour, the disabled locked controls are announced as disabled, and "Can't be applied" is a text badge
+59
View File
@@ -0,0 +1,59 @@
# QA procedure: relation field in the SPA
Two parts. Part 1 is automated (Vitest component tests, `task test:web`). Part 2 is the visual gate (`task visual:check`). Part 3 is manual. The Go side is in `relation_field_type.qa.md`. Until `task test:web` exists, SPA tests are reported NOT RUN, never passing.
## Part 1: automated (Vitest + Vue Test Utils)
Mock `/v1` per test with the shapes below; no live server. A field is `{"key","label","type":"relation","required","unique":false,"default":null,"min":null,"max":null,"options":[],"relation":{"content_type","kind"}}` and every other field carries `"relation": null`.
Registry
1. `lib/fieldTypes`: the relation entry has the properties of the registry outline (label, icon `lucide:link`, control `RelationField`, no unique/limits/default/choices, empty value per kind, sample null or []). An unknown type still falls back to text; a relation never does.
2. Client validation table (single and many, required/optional, 0, "3", [3], duplicates, 51 ids) and the message map including the "not produced" rules.
Builder (one test per state)
3. Type gallery: Relation is the last tile; locked on a saved field with the other tiles dimmed.
4. New relation: the related-type select lists the other types (mock `GET /v1/content-type`), the help text, the three cards with the exact sentences, default "One to many" (proposed); choosing a type updates the sentences.
5. Preview outline: the kind change updates both sentences and the line `· shown on Venue as the field "Events"`; the example cards "Event" and "Venue" show the board's chips (Rue Verte hall, Open day, Lime plaster workshop, +1). Nothing about the inverse is in any request.
6. Save body: relation sent as `{"content_type","kind"}`, others `"relation": null`; a loaded field round-trips unchanged; no related type chosen blocks Save with the proposed message.
7. Saved relation: key, tiles, related type and cards are disabled; Label and Required editable; the proposed lock note shows.
8. Review: required relation + entries > 0 shows the flagged row and disabled "Apply changes" with no PUT; optional shows the clean row; required with 0 entries sends at once; making an optional relation required shows "Entries may not fit" with Apply enabled.
9. Server answers: 409 `schema_incompatible` and 422 `invalid_field` map to the existing flows.
10. Delete refused: 409 `content_type_referenced` shows the proposed copy and the type stays listed.
11. A non-owner/admin sees no builder.
Entry form (one test per state)
12. Single control: type "rue" -> only `GET /v1/content-type/venues/entry?q=rue&page=1&size=...` is sent (debounced, trimmed, stale answers ignored); rows show title and second line; pick sets the value to 3, one chip, "Unsaved changes", live message.
13. Many control: chips for [11, 12], "Search to add", the help line; add keeps order; x and Backspace remove; picked ids are not offered again; the 51st is blocked with the proposed message.
14. States: loading (skeleton after 150 ms), no match with "Clear search", empty type, 500, network error, 429 countdown, 401 redirect, 404 (all with the proposed copy where tagged), "Try again" re-sends only the search.
15. Missing target (optional and required), saving, keyboard (arrows, Enter, Esc, Tab, Backspace), required-empty error and focus order (first invalid field only).
16. Outline "What the control shows and sends" (all 7 rows) and the create payload with `venue: null`, `speakers: []` and with a picked number.
17. Dirty tracking: back to the original value gives "Saved"; reordered many ids count as changed.
18. Server answers table: `required`, `type`, `unique`, `unknown_field` (reload alert), each with the right copy, chip and focus.
19. Layout: a relation after boolean/number/date never pairs.
List
20. Cell outline (one chip, two chips, two chips + "+2", dash for null, dash for [], missing chip) from each item's `relations` with no extra request; relation columns are not sortable (no sort icon, no `aria-sort`).
21. Desktop grid for items 42/41/40 matches the board texts; the mobile card shows the labelled lines; the Columns menu lists Venue and Speakers with the link icon and the cap of 6.
22. Plain text of a relation cell never shows the numeric id; a first-field relation keeps the link and the "Entry N" title.
Accessibility
23. Combobox/listbox roles and attributes, chip group label, "Remove X from Y" button names, required/invalid/describedby wiring, the live region texts.
## Part 2: visual (`task visual:check -- <screen>`)
Hard gate: each capture within 10 % at 1440x900 and 390x844, light and dark. Add setups in `web/visual/states.ts` with the board's own sample data; no clock-sensitive state exists in this group.
| Screen | State | Board sample data the mock must reuse |
| --- | --- | --- |
| schema | Relation in the builder | Events with Venue (label), key `venue`, related type Venue, "One to many" selected, preview sentences, example cards with chips "Rue Verte hall", "Open day", "Lime plaster workshop", "+1" |
| entry (content/events/42) | Relation in the entry form | Title "Lime plaster workshop" (21 / 80); Venue search "rue" with rows "Rue Verte hall / Lyon · 120 seats", "Rue Verte yard / Lyon · outdoor", "Rue du Port studio / Nantes · 24 seats"; Speakers chips "Ines Duarte", "Jonas Pereira"; help "An event can have many speakers." |
| content (events) | Relation in the list | Items 42 "Lime plaster workshop" 21 Nov 2026 (Rue Verte hall; Ines Duarte, Jonas Pereira, +2), 41 "Heat pumps: what the numbers say" 3 Nov 2026 (–; Jonas Pereira), 40 "Open day at the Rue Verte site" 12 Nov 2026 (Rue Verte yard; –) |
Notes:
- The board's states are drawn with a "Later" badge; the SPA does not render it. Expect a pixel difference at the badge. If the 10 % gate fails because of it, the user decides on a documented `exception` (`approvedBy`); the QA never adds one.
- The board's builder shows a four-tile gallery plus Relation; the SPA shows the full gallery. The mismatch is reported to the user, not worked around.
- States tagged "(proposed copy)" (loading, no match, error, missing chip, locked inspector, review refusal, delete refusal) are not on the board and get Vitest tests only, no visual capture.
## Part 3: manual (screenshots can't cover)
- Keyboard and focus order across the combobox, chips and list; screen reader announcements of the live region.
- Hover and motion of the popover and of the chips' x; the mobile bottom-sheet versus under-input choice.
- Real SQLite end to end with the built binary: build the type pair, pick, save, reload, delete a target and see the missing chip.
- `bunx playwright install chromium` the first time on a machine.
+235
View File
@@ -0,0 +1,235 @@
Feature: Relation field type for custom content types
As a site owner or admin
I want a content type field that links an entry to entries of another content type
So that structured content can refer to other structured content
Background:
Given internal/domain/contenttype adds the field type "relation" next to text, richtext, number, boolean, date, select and media
And a relation field carries "relation": {"content_type": <key of an existing type>, "kind": "one_to_one" | "one_to_many" | "many_to_many"}
And "one_to_many" reads from the owner: each owner entry has one target, a target has many owner entries
And every field response gains the key "relation", null for the other types, so a field has exactly ten keys
And a relation field accepts only label, key, required and relation; unique, default, min, max and options are refused with ErrInvalidField
And the target type must exist, else ErrInvalidField; a self relation is allowed for one_to_many and many_to_many and refused for one_to_one
And the connection is stored once, on the owner field; the inverse side is derived, never stored, never added to the target schema, and the target type's schema, entry responses, list and routes are unchanged
And the owner value is an id (uint32, at least 1) or null for one_to_one and one_to_many, and an array of ids ([] when empty, at most 50, no duplicates, order kept) for many_to_many
And entry.Validate stays pure; the existence of target entries is checked by CreateEntry and UpdateEntry through entry.Repository
And a changed value means an id not equal to the one in the stored document for that key; on POST every id is changed; on PUT an unchanged id is not checked for existence unless the field is required
And a changed id must be an existing entry of the target type, else 422 "invalid_entry: <key>: type"
And a required relation is never saved empty: null, absent or [] give 422 "invalid_entry: <key>: required", and so does an unchanged id whose entry is gone
And a one_to_one id already held by another entry of the owner type is refused with 409 "invalid_entry: <key>: unique" (entry.ErrUniqueViolation)
And rules are checked in field order for Validate, then target existence in field order, then unique, and the body names one field per answer
And an entry response keeps its eight keys and adds "relations", always present ({} when no relation is set)
And "relations"[key] is {"id","content_type","first_field":{"key","type","value"}} for an existing target, or {"id","missing":true} when it is gone; for many_to_many it is an array of these in stored order
And first_field is the first field of the target type in schema order with its raw stored value, never formatted by the server
And the same "relations" object is on POST 201, PUT 200, GET one and every item of the list
And GET /v1/content-type/{key}/entry accepts ?q=, a trimmed case-insensitive substring of the display text of the first field, filtered in Go on the unpaged list before pagination, so total counts the matches; an empty q means no filter
And deleting an entry that other entries reference is allowed and leaves them untouched
And DELETE /v1/content-type/{key} on a type that is the target of a relation field is refused with 409 "content_type_referenced" (contenttype.ErrReferenced, new apperr string), even with no entries
And a saved relation field's type, target and kind never change: a change is refused with 422 "invalid_field"
And a new required relation on a type with entries gives 409 "schema_incompatible"
And no repository method is added; the code works on SQLite, MySQL/MariaDB and PostgreSQL with no JSON operators
And the key-set assertions of the earlier custom content type, entry and media features and tests are amended (field 9 to 10 keys, entry 8 to 9 keys)
And types: "venue" has title (text, required) and city (text); "event" has title (text, required) then venue (relation to venue, one_to_many, label "Venue") then speakers (relation to speaker, many_to_many); "speaker" has name (text, required)
And entries: venue 3 "Rue Verte hall", venue 4 "Rue Verte yard"; speaker 11 "Ines Duarte", speaker 12 "Jonas Pereira"
And users: admin id 2 (verified) can write types; any verified user can write entries
Scenario: Creating a content type with a relation field
Given a valid jwt cookie for admin 2 and the type "venue"
When the client sends POST /v1/content-type with fields title (text, required) and
{"key":"venue","label":"Venue","type":"relation","required":false,"unique":false,"default":null,"min":null,"max":null,"options":[],"relation":{"content_type":"venue","kind":"one_to_many"}}
Then the response status is 201
And the venue field comes back with that relation object and the other fields have "relation": null
Scenario Outline: A relation field with a bad definition is refused
Given a valid jwt cookie for admin 2
When the client sends POST /v1/content-type with a relation field that has <defect>
Then the response status is 422
And the response body is "invalid_field"
And no content type is stored
Examples:
| defect |
| relation null |
| content_type "nope" (unknown type) |
| content_type "" or missing |
| kind "many_to_one" |
| kind missing |
| a relation object on a text field |
| unique true |
| default 3 |
| min 1 |
| max 5 |
| options ["a"] |
| a one_to_one self relation |
Scenario: The shape of a saved relation never changes
Given the type "event" has a saved relation "venue" (one_to_many to venue) and at least one entry
When admin 2 sends PUT /v1/content-type/event changing its kind to many_to_many
Then the response is 422 invalid_field and the schema is unchanged
When admin 2 sends PUT changing its target to speaker
Then the response is 422 invalid_field and the schema is unchanged
When admin 2 sends PUT turning it into a text field
Then the response is 422 invalid_field and the schema is unchanged
Scenario Outline: Adding a relation field to a type that has entries
Given the type "event" has 12 entries
When admin 2 sends PUT adding a relation field "venue" that is <required>
Then the response status is <status> and the body is <message>
Examples:
| required | status | message |
| required | 409 | schema_incompatible |
| optional | 200 | |
Scenario: Deleting a type that another type points at
Given the type "venue" has no entries and "event" has a relation to it
When admin 2 sends DELETE /v1/content-type/venue
Then the response status is 409 with "content_type_referenced" and venue still exists
When the relation field is removed from "event" and DELETE is sent again
Then the response status is 204
Scenario: Creating an entry with a single target
When a verified user sends POST /v1/content-type/event/entry with {"data":{"title":"Lime plaster workshop","venue":3}}
Then the response status is 201 and data.venue is 3
And relations is {"venue":{"id":3,"content_type":"venue","first_field":{"key":"title","type":"text","value":"Rue Verte hall"}}}
Scenario: Creating an entry with many targets
When the client sends POST with {"data":{"title":"A","speakers":[12,11]}}
Then data.speakers is [12,11] and relations.speakers lists speaker 12 then speaker 11
Scenario Outline: Empty optional relations
When the client sends POST with <data>
Then the response status is 201, <stored>, and relations is {}
Examples:
| data | stored |
| {"data":{"title":"A","venue":null}} | data.venue is null |
| {"data":{"title":"A"}} | data.venue is absent |
| {"data":{"title":"A","speakers":[]}} | data.speakers is [] |
Scenario Outline: Values that break a relation are refused and store nothing
Given "venue" is <required> and "speakers" is many_to_many
When the client sends POST with the data <data>
Then the response status is <status> and the body is <message>
And no entry exists
Examples:
| required | data | status | message |
| required | {"title":"A"} | 422 | invalid_entry: venue: required |
| required | {"title":"A","venue":null} | 422 | invalid_entry: venue: required |
| optional | {"title":"A","venue":999} | 422 | invalid_entry: venue: type |
| optional | {"title":"A","venue":"3"} | 422 | invalid_entry: venue: type |
| optional | {"title":"A","venue":0} | 422 | invalid_entry: venue: type |
| optional | {"title":"A","venue":3.5} | 422 | invalid_entry: venue: type |
| optional | {"title":"A","venue":[3]} | 422 | invalid_entry: venue: type |
| optional | {"title":"A","speakers":11} | 422 | invalid_entry: speakers: type |
| optional | {"title":"A","speakers":[11,11]} | 422 | invalid_entry: speakers: type |
| optional | {"title":"A","speakers":[11,999]}| 422 | invalid_entry: speakers: type |
| optional | {"title":"A","speakers":[3]} | 422 | invalid_entry: speakers: type |
| optional | speakers with 51 ids | 422 | invalid_entry: speakers: type |
Scenario: A required many relation is never empty
Given "speakers" is required
When the client sends POST with speakers [] or with the key absent
Then the response is 422 invalid_entry: speakers: required
Scenario: One to one keeps targets exclusive
Given the type "talk" has a one_to_one relation "room" to "venue" and a talk already holds venue 3
When the client sends POST with room 3
Then the response is 409 "invalid_entry: room: unique" and nothing is stored
When the holder is updated with room 3 unchanged
Then the response is 200
When the holder is deleted and the POST is sent again
Then the response is 201
Scenario: Replacing and clearing targets
Given the entry 5 holds venue 3 and speakers [11]
When a verified user sends PUT with venue 4 and speakers [11,12]
Then data and relations reflect venue 4 and speakers 11, 12
When the user sends PUT with venue null and speakers []
Then relations is {}
Scenario: A target deleted after the entry was saved
Given the entry 5 holds venue 3 and speakers [11,12]
When entry 3 of venue and entry 12 of speaker are deleted (both answer 204)
And the client sends GET /v1/content-type/event/entry/5
Then data is unchanged
And relations.venue is {"id":3,"missing":true}
And relations.speakers is [{"id":11,"content_type":"speaker","first_field":{"key":"name","type":"text","value":"Ines Duarte"}},{"id":12,"missing":true}]
And the entry 5 was not modified (updated_at and updated_by unchanged)
Scenario Outline: Unchanged and changed ids when the target is gone
Given the entry 5 holds venue 3 and venue 3 was deleted
When the user sends PUT with venue <value>
Then the response status is <status> and the body is <message>
Examples:
| value | status | message |
| 3 | 200 | |
| 999 | 422 | invalid_entry: venue: type |
| 4 | 200 | |
| null | 200 | |
Scenario Outline: A required relation with a missing target can't be saved as is
Given venue is required, entry 5 holds venue 3 and venue 3 was deleted
When the user sends PUT with venue <value>
Then the status is <status>, the body is <message> and the stored entry is <outcome>
Examples:
| value | status | message | outcome |
| 3 | 422 | invalid_entry: venue: required | unchanged |
| null | 422 | invalid_entry: venue: required | unchanged |
| 4 | 200 | | updated |
Scenario: A create always treats the id as changed
Given venue 3 was deleted
When the client sends POST with venue 3
Then the response is 422 invalid_entry: venue: type
Scenario: Two broken fields name only one
Given a body with a required text left empty and a relation to a missing target
Then the answer names one field: Validate rules first in field order, then existence, then unique
Scenario: Entry list responses carry relations per item
Given 3 events: one with a venue and two speakers, one with a deleted venue, one with nothing
When the client sends GET /v1/content-type/event/entry
Then each item keeps its eight keys and adds "relations"
And items, total, page and size are unchanged
And a type without a relation field returns "relations": {} and makes no target repository call
Scenario Outline: Searching the entries of a type
Given the type "venue" has entries titled "Rue Verte hall", "Rue Verte yard", "Rue du Port studio"
When the client sends GET /v1/content-type/venue/entry?q=<q>
Then total is <total>
Examples:
| q | total |
| rue | 3 |
| RUE VERTE | 2 |
| yard | 1 |
| nothing | 0 |
| | 3 |
Scenario: Search is paginated after filtering
Given 30 venues match "rue"
When the client sends GET /v1/content-type/venue/entry?q=rue&page=2&size=10
Then total is 30, page is 2, size is 10 and items holds the second ten matches in the requested sort
Scenario: Deleting an entry that is referenced
Given 4 events hold venue 3
When a verified user sends DELETE /v1/content-type/venue/entry/3
Then the response status is 204 and the 4 events are not modified
Scenario: The target type, entries and API are unchanged
Given "event" has a one_to_many relation to "venue"
When the client sends GET /v1/content-type/venue and GET /v1/content-type/venue/entry/3
Then neither response carries the inverse field "Events" and the venue field list is the one saved
Scenario: Use case level
Given fake contenttype and entry repositories
Then contenttype.ValidateFields returns ErrInvalidField for each refused definition
And entry.Validate returns errors.Is(err, entry.ErrInvalidEntry) with Key and Rule "required" or "type" for the shapes above
And CreateEntry and UpdateEntry return the same for a missing target and perform no Create or Update
And UpdateContentType returns contenttype.ErrSchemaIncompatible for a new required relation and ErrInvalidField for a changed shape
And DeleteContentType returns contenttype.ErrReferenced for a target type
+48
View File
@@ -0,0 +1,48 @@
# QA procedure: relation field type (API only)
Package: `test` (black-box). No live server, no real SQLite file, no real SMTP, no SPA.
## Setup shared by every case
1. Call `validator.InitValidator()` once per test.
2. Reuse `mockContentTypeRepo` and `mockEntryRepo` of the custom content type and media pairs. Fake names stay unique across the package. The entry fake needs `createCalls`, `updateCalls`, a `getCalls` counter per content type and a `deleteEntry(contentTypeID, id)` helper. No repository method is added.
3. Build `NewHandler(...)` for the content type and entry handlers over use cases wired to the fakes. Mount them on a fresh `chi.NewRouter()` mirroring api/router.go under `/v1/content-type`, with `jwtauth.Verifier`, `jwtauth.Authenticator` and a test `jwtauth.New("HS256", []byte("test-secret"), nil)`, and `RequireOwnerOrAdmin` on the type write routes. Prefer `api.InitBackendRoutes` with a partial `*api.UseCases` if it works.
4. Seed admin 2 and a plain verified user. Seed the types venue, speaker, event and talk, and the entries venue 3, 4 and speaker 11, 12 from the feature.
5. Inject a fake clock so `updated_at` > `created_at`. Decode bodies into `map[string]any` and compare numbers as `float64`.
## Schema
6. POST a valid relation field -> 201; `relation` is the object sent; every other field has `"relation": null`; every field has exactly ten keys.
7. Refusal table (null relation, unknown target, empty target, bad kind, missing kind, relation on a text field, unique/default/min/max/options, one_to_one self) -> 422 `invalid_field`, repo empty.
8. Locking: kind, target and type changes on a saved relation -> 422 `invalid_field`, schema byte-identical. A type with no entries keeps today's free type change for non-saved shapes.
9. Type with 12 entries: add required relation -> 409 `schema_incompatible`, unchanged; add optional -> 200 and the old entries read with `relations` `{}`.
10. DELETE a target type with no entries -> 409 `content_type_referenced` (plain text); after removing the relation field -> 204. A type with entries is still 409 `content_type_has_entries`.
## Entry writes
11. Single and many targets -> 201, `data` as sent (array order kept), `relations` as in the feature. The target object has exactly `id`, `content_type`, `first_field`; `first_field` has exactly `key`, `type`, `value`, with the raw stored value.
12. Empty optional (null, absent, []) -> 201, `relations` is `{}` (assert JSON `{}`, not null). A required many field with [] or absent -> 422 required.
13. Refusal table -> exact status and body, `createCalls == 0`. The 51-id case is built in the test.
14. A venue id in a speaker field -> 422 type.
15. One-to-one exclusivity: 409 `invalid_entry: room: unique`, nothing stored; PUT of the holder unchanged -> 200; after deleting the holder, POST -> 201.
16. PUT replace/clear -> 200 with updated `relations`.
17. Dangling targets: `deleteEntry` venue 3 and speaker 12 -> GET entry 5 shows `{"id":3,"missing":true}` and the mixed array; `updated_at`/`updated_by` unchanged. PUT unchanged id -> 200; 999 -> 422 type; other id or null -> 200.
18. Required relation with a gone target: PUT same id -> 422 required; null -> 422 required; other id -> 200. POST with a deleted id -> 422 type.
19. Ordering: two bad fields name one only (Validate in field order, then existence, then unique).
## Reads
20. List with 3 events (full, dangling, empty) -> every item has the 8 old keys plus `relations`; `total`, `page`, `size` unchanged; `items` is `[]` for an empty type.
21. A type without a relation field -> `relations` `{}` and zero Get calls on target types. 100 entries pointing at one target call Get at most once for that id.
22. `?q=` table (case-insensitive, trimmed, empty = all, none = 0); `total` counts matches; page 2 size 10 of 30 matches returns the second ten; invalid `page`/`size`/`sort` keep their existing errors.
23. GET venue and GET a venue entry after the relation exists on event -> no inverse field, same keys as before.
## Delete
24. DELETE a referenced venue entry -> 204; the referencing events are byte-identical and no Update is recorded.
## Use case level (no HTTP)
25. `ValidateFields`, `entry.Validate`, `CreateEntry`/`UpdateEntry`, `UpdateContentType`, `DeleteContentType` as in the last scenario (`errors.Is`).
## Existing tests to amend
26. Key-set assertions in the custom content type, entry and media specs and tests: field 9 -> 10 keys, entry 8 -> 9 keys. The coder owns this.
## Manual verification (not exercised by the Go tests)
- Real SQLite, then MySQL/MariaDB and PostgreSQL via the driver tasks: create venue and event with a relation, save entries, delete the venue entry, reload the event and confirm the dangling id and `missing`.
- Time `GET .../entry?q=` against a type with 1,000 entries (the filter loads the whole type).
- The SPA is the second pair and is not checked here.
+7
View File
@@ -14,6 +14,7 @@ require (
github.com/go-sql-driver/mysql v1.10.1
github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.11.0
github.com/modelcontextprotocol/go-sdk v1.8.0
golang.org/x/crypto v0.58.0
golang.org/x/image v0.47.0
golang.org/x/net v0.61.0
@@ -45,6 +46,7 @@ require (
github.com/glebarez/go-sqlite v1.23.0 // indirect
github.com/go-playground/locales v0.14.2 // indirect
github.com/go-playground/universal-translator v0.18.2 // indirect
github.com/google/jsonschema-go v0.4.3 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.3 // indirect
@@ -54,9 +56,14 @@ require (
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/ncruces/go-strftime v1.1.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/segmentio/asm v1.1.3 // indirect
github.com/segmentio/encoding v0.5.4 // indirect
github.com/stretchr/testify v1.12.1 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
golang.org/x/oauth2 v0.35.0 // indirect
golang.org/x/sync v0.24.0 // indirect
golang.org/x/sys v0.49.0 // indirect
golang.org/x/time v0.15.0 // indirect
modernc.org/libc v1.79.0 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.12.1 // indirect
+18
View File
@@ -61,6 +61,12 @@ github.com/go-playground/validator/v10 v10.30.5 h1:YyCXvVShZbs2Sm3Mb53eNOlhRXctS
github.com/go-playground/validator/v10 v10.30.5/go.mod h1:wEqiaov48pXX1kjhc3Da8y0M0Dtg/BK7gurFBLgwFrQ=
github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME=
github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs=
github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -85,16 +91,24 @@ github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsRe
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=
github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
@@ -105,12 +119,16 @@ golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw=
golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
@@ -13,6 +13,7 @@ var (
ErrInvalidIcon = errors.New("invalid content type icon")
ErrInvalidField = errors.New("invalid field")
ErrHasEntries = errors.New("the content type still has entries")
ErrReferenced = errors.New("the content type is the target of a relation field")
ErrSchemaIncompatible = errors.New("the schema is incompatible with the stored entries")
)
@@ -26,6 +27,7 @@ const (
TypeDate FieldType = "date"
TypeSelect FieldType = "select"
TypeMedia FieldType = "media"
TypeRelation FieldType = "relation"
)
const (
@@ -54,6 +56,7 @@ type Field struct {
Min any `json:"min"`
Max any `json:"max"`
Options []string `json:"options"`
Relation *Relation `json:"relation"`
}
type ContentType struct {
@@ -21,6 +21,7 @@ var kinds = map[FieldType]kind{
TypeDate: {accepts: isDate, measure: dateDays, bound: dateDays, unique: true},
TypeSelect: {accepts: isString, unique: true},
TypeMedia: {accepts: isMediaID},
TypeRelation: {},
}
func MediaID(value any) (uint32, bool) {
+2 -2
View File
@@ -63,7 +63,7 @@ func (f Field) validSchema() bool {
if f.Unique && !fieldKind.unique {
return false
}
return f.validOptions() && f.validBounds(fieldKind) && f.validDefault()
return f.validRelation() && f.validOptions() && f.validBounds(fieldKind) && f.validDefault()
}
func (f Field) validOptions() bool {
@@ -109,7 +109,7 @@ func (f Field) validDefault() bool {
if f.Default == nil {
return true
}
if f.Type == TypeMedia {
if f.Type == TypeMedia || f.Type == TypeRelation {
return false
}
return !f.Unique && f.Violation(f.Default) == ""
@@ -3,6 +3,9 @@ package contenttype
import "slices"
func (f Field) Violation(value any) string {
if f.Type == TypeRelation {
return f.relationViolation(value)
}
fieldKind, known := kinds[f.Type]
if !known || !fieldKind.accepts(value) {
return RuleType
@@ -0,0 +1,134 @@
package contenttype
const MaxRelationIDs = 50
type RelationKind string
const (
RelationOneToOne RelationKind = "one_to_one"
RelationOneToMany RelationKind = "one_to_many"
RelationManyToMany RelationKind = "many_to_many"
)
type Relation struct {
ContentType string `json:"content_type"`
Kind RelationKind `json:"kind"`
}
func (r Relation) validKind() bool {
return r.Kind == RelationOneToOne || r.Kind == RelationOneToMany || r.Kind == RelationManyToMany
}
func (f Field) validRelation() bool {
if f.Type != TypeRelation {
return f.Relation == nil
}
return f.Relation != nil && f.Relation.ContentType != "" && f.Relation.validKind()
}
func (f Field) IsRelation() bool {
return f.Type == TypeRelation && f.Relation != nil
}
func (f Field) HoldsManyRelations() bool {
return f.IsRelation() && f.Relation.Kind == RelationManyToMany
}
func (f Field) IsExclusiveRelation() bool {
return f.IsRelation() && f.Relation.Kind == RelationOneToOne
}
func (f Field) RelationIDs(value any) ([]uint32, bool) {
if value == nil {
return []uint32{}, true
}
if !f.HoldsManyRelations() {
id, ok := MediaID(value)
if !ok {
return nil, false
}
return []uint32{id}, true
}
return manyRelationIDs(value)
}
func manyRelationIDs(value any) ([]uint32, bool) {
var items []any
switch typed := value.(type) {
case []any:
items = typed
case []uint32:
for _, id := range typed {
items = append(items, id)
}
default:
return nil, false
}
if len(items) > MaxRelationIDs {
return nil, false
}
ids := make([]uint32, 0, len(items))
seen := make(map[uint32]bool, len(items))
for _, item := range items {
id, ok := MediaID(item)
if !ok || seen[id] {
return nil, false
}
seen[id] = true
ids = append(ids, id)
}
return ids, true
}
func (f Field) relationViolation(value any) string {
if _, ok := f.RelationIDs(value); !ok {
return RuleType
}
return ""
}
func EmptyRelation(field Field, value any) bool {
if !field.HoldsManyRelations() {
return false
}
ids, ok := field.RelationIDs(value)
return ok && len(ids) == 0
}
type RelationRef struct {
Field Field
IDs []uint32
}
func RelationRefs(fields []Field, data map[string]any) []RelationRef {
var refs []RelationRef
for _, field := range RelationFields(fields) {
if ids, ok := field.RelationIDs(data[field.Key]); ok && len(ids) > 0 {
refs = append(refs, RelationRef{Field: field, IDs: ids})
}
}
return refs
}
func RelationFields(fields []Field) []Field {
var relations []Field
for _, field := range fields {
if field.IsRelation() {
relations = append(relations, field)
}
}
return relations
}
func ReferencesType(fields []Field, key string) bool {
for _, field := range RelationFields(fields) {
if field.Relation.ContentType == key {
return true
}
}
return false
}
func SameRelation(left Field, right Field) bool {
return left.IsRelation() && right.IsRelation() && *left.Relation == *right.Relation
}
+40 -2
View File
@@ -2,8 +2,11 @@ package entry
import (
"RenewCMS/internal/domain/contenttype"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
)
func SameValue(left any, right any) bool {
@@ -49,7 +52,7 @@ func Validate(fields []contenttype.Field, data map[string]any) error {
func validateField(field contenttype.Field, data map[string]any) error {
value := data[field.Key]
if value == nil {
if value == nil || contenttype.EmptyRelation(field, value) {
if field.Required {
return InvalidField(field.Key, RuleRequired)
}
@@ -82,7 +85,7 @@ func firstUnknownField(fields []contenttype.Field, data map[string]any) error {
func UniqueValues(fields []contenttype.Field, data map[string]any) []UniqueValue {
var values []UniqueValue
for _, field := range fields {
if value := data[field.Key]; field.Unique && value != nil {
if value := data[field.Key]; (field.Unique || field.IsExclusiveRelation()) && value != nil {
values = append(values, UniqueValue{Key: field.Key, Value: value})
}
}
@@ -103,3 +106,38 @@ func MissingMedia(field contenttype.Field, unchanged bool) error {
}
return InvalidField(field.Key, contenttype.RuleType)
}
func RelationIDs(fields []contenttype.Field, data map[string]any) map[string]map[uint32]bool {
ids := map[string]map[uint32]bool{}
for _, ref := range contenttype.RelationRefs(fields, data) {
held := make(map[uint32]bool, len(ref.IDs))
for _, id := range ref.IDs {
held[id] = true
}
ids[ref.Field.Key] = held
}
return ids
}
func MissingRelation(field contenttype.Field, unchanged bool) error {
return MissingMedia(field, unchanged)
}
func MatchesQuery(fields []contenttype.Field, data map[string]any, query string) bool {
if len(fields) == 0 {
return false
}
return strings.Contains(strings.ToLower(displayText(data[fields[0].Key])), strings.ToLower(query))
}
func displayText(value any) string {
switch typed := value.(type) {
case nil:
return ""
case string:
return typed
case float64:
return strconv.FormatFloat(typed, 'f', -1, 64)
}
return fmt.Sprint(value)
}
Whitespace-only changes.
@@ -0,0 +1,19 @@
package llmdocs
import (
"embed"
"io/fs"
)
//go:embed all:generated
var generatedEmbed embed.FS
var Docs = mustSub(generatedEmbed, "generated")
func mustSub(fsys fs.FS, dir string) fs.FS {
sub, err := fs.Sub(fsys, dir)
if err != nil {
panic("llmdocs: " + err.Error())
}
return sub
}
@@ -0,0 +1,77 @@
package mcpserver
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
const (
requestTimeout = 60 * time.Second
maxResponseSize = 8 << 20
)
type Client struct {
baseURL string
apiKey string
http *http.Client
}
type Response struct {
Status int
Body string
}
func NewClient(baseURL string, apiKey string, httpClient *http.Client) *Client {
if httpClient == nil {
httpClient = &http.Client{Timeout: requestTimeout}
}
return &Client{baseURL: strings.TrimRight(baseURL, "/"), apiKey: apiKey, http: httpClient}
}
func (c *Client) Do(ctx context.Context, method string, path string, query url.Values, body []byte, contentType string) (Response, error) {
target := c.baseURL + path
if len(query) > 0 {
target += "?" + query.Encode()
}
req, err := http.NewRequestWithContext(ctx, method, target, bytes.NewReader(body))
if err != nil {
return Response{}, err
}
if c.apiKey != "" {
req.Header.Set("Authorization", "Bearer "+c.apiKey)
}
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
res, err := c.http.Do(req)
if err != nil {
return Response{}, err
}
defer res.Body.Close()
raw, err := io.ReadAll(io.LimitReader(res.Body, maxResponseSize))
if err != nil {
return Response{}, err
}
return Response{Status: res.StatusCode, Body: string(raw)}, nil
}
func (r Response) Failed() bool {
return r.Status < 200 || r.Status > 299
}
func (r Response) Describe() string {
text := strings.TrimSpace(r.Body)
if r.Status == http.StatusNoContent || text == "" {
return fmt.Sprintf("HTTP %d", r.Status)
}
if r.Failed() {
return fmt.Sprintf("HTTP %d: %s", r.Status, text)
}
return text
}
+305
View File
@@ -0,0 +1,305 @@
package mcpserver
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
const (
docsResourceURI = "renewcms://docs/llms-full.txt"
jsonType = "application/json"
)
type Options struct {
Version string
AllowDestructive bool
}
type server struct {
client *Client
}
type listArticlesInput struct {
Page int `json:"page,omitempty" jsonschema:"page number from 1"`
Size int `json:"size,omitempty" jsonschema:"page size: 5, 25, 50 or 100"`
Query string `json:"q,omitempty" jsonschema:"text matched in the title"`
Status string `json:"status,omitempty" jsonschema:"online or draft"`
Sort string `json:"sort,omitempty" jsonschema:"field:direction, e.g. title:asc or updated_at:desc"`
Site string `json:"site,omitempty" jsonschema:"site key"`
SEO string `json:"seo,omitempty" jsonschema:"ready, suggestions or hidden"`
Format string `json:"format,omitempty" jsonschema:"body format: markdown, html or json"`
}
type getArticleInput struct {
ID int `json:"id" jsonschema:"article id"`
Format string `json:"format,omitempty" jsonschema:"body format: markdown, html or json"`
}
type createArticleInput struct {
Title string `json:"title" jsonschema:"3 to 200 characters, cannot be changed later"`
Body string `json:"body" jsonschema:"HTML body"`
}
type updateArticleBodyInput struct {
ID int `json:"id" jsonschema:"article id"`
Body string `json:"body" jsonschema:"new HTML body, replaces the old one"`
}
type articleIDInput struct {
ID int `json:"id" jsonschema:"article id"`
}
type listMediaInput struct {
Query string `json:"q,omitempty" jsonschema:"search text"`
Filter string `json:"filter,omitempty" jsonschema:"all, unused or duplicates"`
Sort string `json:"sort,omitempty" jsonschema:"newest, oldest, name, largest or total_size"`
Page int `json:"page,omitempty" jsonschema:"page number from 1"`
Size int `json:"size,omitempty" jsonschema:"page size: 5, 25, 50 or 100"`
}
type uploadMediaInput struct {
Path string `json:"path,omitempty" jsonschema:"path of a local PNG, JPEG, WEBP or SVG file"`
Base64 string `json:"base64,omitempty" jsonschema:"base64 file content, instead of path"`
Filename string `json:"filename,omitempty" jsonschema:"file name, required with base64"`
}
type emptyInput struct{}
type sitemapInput struct {
Key string `json:"key" jsonschema:"site key"`
Page int `json:"page,omitempty" jsonschema:"page number from 1"`
Size int `json:"size,omitempty" jsonschema:"25, 50, 100 or 500"`
}
type mediaIDInput struct {
ID int `json:"id" jsonschema:"image id"`
}
func New(client *Client, opts Options) *mcp.Server {
s := &server{client: client}
srv := mcp.NewServer(&mcp.Implementation{Name: "renewcms", Version: opts.Version}, &mcp.ServerOptions{
Instructions: "Tools for a RenewCMS instance. Read the renewcms://docs/llms-full.txt resource for the API rules. Articles are created as drafts; ask before publishing.",
})
readOnly := &mcp.ToolAnnotations{ReadOnlyHint: true}
additive := &mcp.ToolAnnotations{DestructiveHint: boolPtr(false)}
mcp.AddTool(srv, &mcp.Tool{Name: "list_articles", Description: "List one page of articles with total and counts.", Annotations: readOnly}, s.listArticles)
mcp.AddTool(srv, &mcp.Tool{Name: "get_article", Description: "Get one article.", Annotations: readOnly}, s.getArticle)
mcp.AddTool(srv, &mcp.Tool{Name: "create_article", Description: "Create a draft article.", Annotations: additive}, s.createArticle)
mcp.AddTool(srv, &mcp.Tool{Name: "update_article_body", Description: "Replace the body of an article. The previous body is overwritten.", Annotations: &mcp.ToolAnnotations{IdempotentHint: true}}, s.updateArticleBody)
mcp.AddTool(srv, &mcp.Tool{Name: "publish_article", Description: "Make an article visible to everyone.", Annotations: &mcp.ToolAnnotations{IdempotentHint: true, DestructiveHint: boolPtr(false)}}, s.publishArticle)
mcp.AddTool(srv, &mcp.Tool{Name: "check_seo", Description: "Check the SEO of the saved article and list suggestions.", Annotations: readOnly}, s.checkSEO)
mcp.AddTool(srv, &mcp.Tool{Name: "list_media", Description: "List one page of the image library.", Annotations: readOnly}, s.listMedia)
mcp.AddTool(srv, &mcp.Tool{Name: "upload_media", Description: "Upload an image from a local path or base64 content.", Annotations: additive}, s.uploadMedia)
mcp.AddTool(srv, &mcp.Tool{Name: "list_sites", Description: "List the sites.", Annotations: readOnly}, s.listSites)
mcp.AddTool(srv, &mcp.Tool{Name: "get_sitemap", Description: "Read the public sitemap of a site.", Annotations: readOnly}, s.getSitemap)
if opts.AllowDestructive {
mcp.AddTool(srv, &mcp.Tool{Name: "delete_article", Description: "Permanently delete an article."}, s.deleteArticle)
mcp.AddTool(srv, &mcp.Tool{Name: "delete_media", Description: "Permanently delete an image."}, s.deleteMedia)
}
srv.AddResource(&mcp.Resource{
URI: docsResourceURI,
Name: "llms-full.txt",
Description: "The full RenewCMS documentation served by the instance.",
MIMEType: "text/plain",
}, s.readDocs)
srv.AddPrompt(&mcp.Prompt{
Name: "write_and_publish_article",
Description: "Draft an article, check its SEO and publish it after confirmation.",
Arguments: []*mcp.PromptArgument{{Name: "topic", Description: "what the article is about", Required: true}},
}, writePrompt)
return srv
}
func boolPtr(value bool) *bool { return &value }
func intQuery(query url.Values, name string, value int) {
if value > 0 {
query.Set(name, strconv.Itoa(value))
}
}
func textQuery(query url.Values, name string, value string) {
if value != "" {
query.Set(name, value)
}
}
func result(res Response, err error) (*mcp.CallToolResult, any, error) {
if err != nil {
return nil, nil, err
}
return &mcp.CallToolResult{
IsError: res.Failed(),
Content: []mcp.Content{&mcp.TextContent{Text: res.Describe()}},
}, nil, nil
}
func (s *server) call(ctx context.Context, method string, path string, query url.Values, body any) (*mcp.CallToolResult, any, error) {
var raw []byte
contentType := ""
if body != nil {
encoded, err := json.Marshal(body)
if err != nil {
return nil, nil, err
}
raw, contentType = encoded, jsonType
}
return result(s.client.Do(ctx, method, path, query, raw, contentType))
}
func articlePath(id int, suffix string) string {
return "/v1/article/" + strconv.Itoa(id) + suffix
}
func (s *server) listArticles(ctx context.Context, _ *mcp.CallToolRequest, in listArticlesInput) (*mcp.CallToolResult, any, error) {
query := url.Values{}
intQuery(query, "page", in.Page)
intQuery(query, "size", in.Size)
textQuery(query, "q", in.Query)
textQuery(query, "status", in.Status)
textQuery(query, "sort", in.Sort)
textQuery(query, "site", in.Site)
textQuery(query, "seo", in.SEO)
textQuery(query, "format", in.Format)
return s.call(ctx, http.MethodGet, "/v1/article/", query, nil)
}
func (s *server) getArticle(ctx context.Context, _ *mcp.CallToolRequest, in getArticleInput) (*mcp.CallToolResult, any, error) {
query := url.Values{}
textQuery(query, "format", in.Format)
return s.call(ctx, http.MethodGet, articlePath(in.ID, ""), query, nil)
}
func (s *server) createArticle(ctx context.Context, _ *mcp.CallToolRequest, in createArticleInput) (*mcp.CallToolResult, any, error) {
return s.call(ctx, http.MethodPost, "/v1/article/", nil, map[string]string{"title": in.Title, "body": in.Body})
}
func (s *server) updateArticleBody(ctx context.Context, _ *mcp.CallToolRequest, in updateArticleBodyInput) (*mcp.CallToolResult, any, error) {
return s.call(ctx, http.MethodPatch, articlePath(in.ID, ""), nil, map[string]string{"body": in.Body})
}
func (s *server) publishArticle(ctx context.Context, _ *mcp.CallToolRequest, in articleIDInput) (*mcp.CallToolResult, any, error) {
return s.call(ctx, http.MethodPatch, articlePath(in.ID, "/publish"), nil, nil)
}
func (s *server) checkSEO(ctx context.Context, _ *mcp.CallToolRequest, in articleIDInput) (*mcp.CallToolResult, any, error) {
return s.call(ctx, http.MethodPost, articlePath(in.ID, "/seo/check"), nil, map[string]string{})
}
func (s *server) deleteArticle(ctx context.Context, _ *mcp.CallToolRequest, in articleIDInput) (*mcp.CallToolResult, any, error) {
return s.call(ctx, http.MethodDelete, articlePath(in.ID, ""), nil, nil)
}
func (s *server) listMedia(ctx context.Context, _ *mcp.CallToolRequest, in listMediaInput) (*mcp.CallToolResult, any, error) {
query := url.Values{}
textQuery(query, "q", in.Query)
textQuery(query, "filter", in.Filter)
textQuery(query, "sort", in.Sort)
intQuery(query, "page", in.Page)
intQuery(query, "size", in.Size)
return s.call(ctx, http.MethodGet, "/v1/media/", query, nil)
}
func (s *server) deleteMedia(ctx context.Context, _ *mcp.CallToolRequest, in mediaIDInput) (*mcp.CallToolResult, any, error) {
return s.call(ctx, http.MethodDelete, "/v1/media/"+strconv.Itoa(in.ID), nil, nil)
}
func (s *server) uploadMedia(ctx context.Context, _ *mcp.CallToolRequest, in uploadMediaInput) (*mcp.CallToolResult, any, error) {
name, content, err := uploadContent(in)
if err != nil {
return nil, nil, err
}
var form bytes.Buffer
writer := multipart.NewWriter(&form)
part, err := writer.CreateFormFile("file", name)
if err != nil {
return nil, nil, err
}
if _, err := part.Write(content); err != nil {
return nil, nil, err
}
if err := writer.Close(); err != nil {
return nil, nil, err
}
return result(s.client.Do(ctx, http.MethodPost, "/v1/media/", nil, form.Bytes(), writer.FormDataContentType()))
}
func uploadContent(in uploadMediaInput) (string, []byte, error) {
switch {
case in.Path != "" && in.Base64 != "":
return "", nil, fmt.Errorf("give either path or base64, not both")
case in.Path != "":
content, err := os.ReadFile(in.Path)
if err != nil {
return "", nil, err
}
name := in.Filename
if name == "" {
name = filepath.Base(in.Path)
}
return name, content, nil
case in.Base64 != "":
if in.Filename == "" {
return "", nil, fmt.Errorf("filename is required with base64")
}
content, err := base64.StdEncoding.DecodeString(in.Base64)
if err != nil {
return "", nil, fmt.Errorf("base64 content is not valid: %w", err)
}
return in.Filename, content, nil
}
return "", nil, fmt.Errorf("give a path or base64 content")
}
func (s *server) listSites(ctx context.Context, _ *mcp.CallToolRequest, _ emptyInput) (*mcp.CallToolResult, any, error) {
return s.call(ctx, http.MethodGet, "/v1/site/", nil, nil)
}
func (s *server) getSitemap(ctx context.Context, _ *mcp.CallToolRequest, in sitemapInput) (*mcp.CallToolResult, any, error) {
query := url.Values{}
intQuery(query, "page", in.Page)
intQuery(query, "size", in.Size)
return s.call(ctx, http.MethodGet, "/v1/site/"+url.PathEscape(in.Key)+"/sitemap", query, nil)
}
func (s *server) readDocs(ctx context.Context, req *mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error) {
res, err := s.client.Do(ctx, http.MethodGet, "/llms-full.txt", nil, nil, "")
if err != nil {
return nil, err
}
if res.Failed() {
return nil, fmt.Errorf("the instance did not serve its documentation: %s", res.Describe())
}
return &mcp.ReadResourceResult{Contents: []*mcp.ResourceContents{{
URI: req.Params.URI,
MIMEType: "text/plain",
Text: res.Body,
}}}, nil
}
func writePrompt(_ context.Context, req *mcp.GetPromptRequest) (*mcp.GetPromptResult, error) {
text := "Write an article about " + req.Params.Arguments["topic"] + " for this RenewCMS instance. " +
"Create it as a draft with create_article, run check_seo and fix what is worth fixing with update_article_body, " +
"then show me the result and ask before calling publish_article."
return &mcp.GetPromptResult{
Description: "Draft, check and publish an article",
Messages: []*mcp.PromptMessage{{Role: "user", Content: &mcp.TextContent{Text: text}}},
}, nil
}
@@ -37,6 +37,9 @@ func (u *CreateContentTypeUseCase) Create(command CreateContentTypeCommand) (con
if err != nil {
return contenttype.ContentType{}, err
}
if err := ensureRelationTargets(u.contentTypes, command.Key, fields); err != nil {
return contenttype.ContentType{}, err
}
if err := u.ensureKeyFree(command.Key); err != nil {
return contenttype.ContentType{}, err
}
@@ -36,6 +36,10 @@ func (u *CreateEntryUseCase) Create(command CreateEntryCommand) (TypedEntry, err
if err := ensureMediaExists(u.images, owner, data, nil); err != nil {
return TypedEntry{}, err
}
resolvers := newEntryResolvers(u.images, u.contentTypes, u.entries)
if err := ensureRelationsExist(resolvers.relations, owner, data, nil); err != nil {
return TypedEntry{}, err
}
if err := ensureUnique(u.entries, owner, data, 0); err != nil {
return TypedEntry{}, err
}
@@ -51,5 +55,5 @@ func (u *CreateEntryUseCase) Create(command CreateEntryCommand) (TypedEntry, err
if err != nil {
return TypedEntry{}, err
}
return typedEntry(owner, stored, newMediaResolver(u.images))
return typedEntry(owner, stored, resolvers)
}
@@ -19,6 +19,15 @@ func (u *DeleteContentTypeUseCase) Delete(key string) error {
if err != nil {
return err
}
types, err := u.contentTypes.List()
if err != nil {
return err
}
for _, other := range types {
if other.ID != target.ID && contenttype.ReferencesType(other.Fields, target.Key) {
return contenttype.ErrReferenced
}
}
count, err := u.entries.CountByContentType(target.ID)
if err != nil {
return err
+1 -1
View File
@@ -25,5 +25,5 @@ func (u *GetEntryUseCase) Get(contentTypeKey string, id uint32) (TypedEntry, err
if err != nil {
return TypedEntry{}, err
}
return typedEntry(owner, found, newMediaResolver(u.images))
return typedEntry(owner, found, newEntryResolvers(u.images, u.contentTypes, u.entries))
}
@@ -4,6 +4,7 @@ import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image"
"strings"
)
type ListEntriesUseCase struct {
@@ -17,6 +18,7 @@ type ListEntriesCommand struct {
Page int
Size int
Sort entry.Sort
Query string
}
type EntryPage struct {
@@ -41,12 +43,12 @@ func (u *ListEntriesUseCase) ListPage(command ListEntriesCommand) (EntryPage, er
if err != nil {
return EntryPage{}, err
}
found, err := u.entries.ListPage(entry.Filters{ContentTypeID: owner.ID, Page: command.Page, Size: command.Size, Sort: command.Sort})
found, err := u.page(owner, command)
if err != nil {
return EntryPage{}, err
}
items := make([]TypedEntry, 0, len(found.Items))
resolver := newMediaResolver(u.images)
resolver := newEntryResolvers(u.images, u.contentTypes, u.entries)
for _, record := range found.Items {
typed, err := typedEntry(owner, record, resolver)
if err != nil {
@@ -56,3 +58,25 @@ func (u *ListEntriesUseCase) ListPage(command ListEntriesCommand) (EntryPage, er
}
return EntryPage{Items: items, Total: found.Total, Page: command.Page, Size: command.Size}, nil
}
func (u *ListEntriesUseCase) page(owner contenttype.ContentType, command ListEntriesCommand) (entry.PageResult, error) {
query := strings.TrimSpace(command.Query)
if query == "" {
return u.entries.ListPage(entry.Filters{ContentTypeID: owner.ID, Page: command.Page, Size: command.Size, Sort: command.Sort})
}
all, err := u.entries.ListPage(entry.Filters{ContentTypeID: owner.ID, Unpaged: true, Sort: command.Sort})
if err != nil {
return entry.PageResult{}, err
}
matching := make([]entry.Entry, 0, len(all.Items))
for _, record := range all.Items {
if entry.MatchesQuery(owner.Fields, record.Data, query) {
matching = append(matching, record)
}
}
pageNumber := max(command.Page, 1)
size := max(command.Size, 0)
start := min((pageNumber-1)*size, len(matching))
end := min(start+size, len(matching))
return entry.PageResult{Items: matching[start:end], Total: len(matching)}, nil
}
@@ -39,6 +39,12 @@ func (u *UpdateContentTypeUseCase) Update(command UpdateContentTypeCommand) (con
if err != nil {
return contenttype.ContentType{}, err
}
if relationShapeChanged(current.Fields, fields) {
return contenttype.ContentType{}, contenttype.ErrInvalidField
}
if err := ensureRelationTargets(u.contentTypes, current.Key, fields); err != nil {
return contenttype.ContentType{}, err
}
stored, err := u.storedEntries(current.ID)
if err != nil {
return contenttype.ContentType{}, err
@@ -40,6 +40,10 @@ func (u *UpdateEntryUseCase) Update(command UpdateEntryCommand) (TypedEntry, err
if err := ensureMediaExists(u.images, owner, command.Data, current.Data); err != nil {
return TypedEntry{}, err
}
resolvers := newEntryResolvers(u.images, u.contentTypes, u.entries)
if err := ensureRelationsExist(resolvers.relations, owner, command.Data, current.Data); err != nil {
return TypedEntry{}, err
}
if err := ensureUnique(u.entries, owner, command.Data, current.ID); err != nil {
return TypedEntry{}, err
}
@@ -50,5 +54,5 @@ func (u *UpdateEntryUseCase) Update(command UpdateEntryCommand) (TypedEntry, err
if err != nil {
return TypedEntry{}, err
}
return typedEntry(owner, stored, newMediaResolver(u.images))
return typedEntry(owner, stored, resolvers)
}
@@ -0,0 +1,168 @@
package useCases
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"errors"
)
type EntryFirstField struct {
Key string
Type contenttype.FieldType
Value any
}
type EntryRelation struct {
ID uint32
Missing bool
ContentType string
FirstField EntryFirstField
}
type EntryRelations struct {
Many bool
Items []EntryRelation
}
type targetEntryKey struct {
contentType string
id uint32
}
type relationResolver struct {
contentTypes contenttype.Repository
entries entry.Repository
types map[string]*contenttype.ContentType
found map[targetEntryKey]EntryRelation
}
func newRelationResolver(contentTypes contenttype.Repository, entries entry.Repository) *relationResolver {
return &relationResolver{contentTypes: contentTypes, entries: entries, types: map[string]*contenttype.ContentType{}, found: map[targetEntryKey]EntryRelation{}}
}
func (r *relationResolver) resolve(owner contenttype.ContentType, record entry.Entry) (map[string]EntryRelations, error) {
resolved := map[string]EntryRelations{}
for _, ref := range contenttype.RelationRefs(owner.Fields, record.Data) {
items := make([]EntryRelation, 0, len(ref.IDs))
for _, id := range ref.IDs {
item, err := r.lookup(ref.Field.Relation.ContentType, id)
if err != nil {
return nil, err
}
items = append(items, item)
}
resolved[ref.Field.Key] = EntryRelations{Many: ref.Field.HoldsManyRelations(), Items: items}
}
return resolved, nil
}
func (r *relationResolver) targetType(key string) (*contenttype.ContentType, error) {
if cached, found := r.types[key]; found {
return cached, nil
}
target, err := r.contentTypes.GetByKey(key)
if errors.Is(err, contenttype.ErrContentTypeNotFound) {
r.types[key] = nil
return nil, nil
}
if err != nil {
return nil, err
}
r.types[key] = &target
return &target, nil
}
func (r *relationResolver) lookup(typeKey string, id uint32) (EntryRelation, error) {
cacheKey := targetEntryKey{typeKey, id}
if cached, found := r.found[cacheKey]; found {
return cached, nil
}
target, err := r.fetch(typeKey, id)
if err != nil {
return EntryRelation{}, err
}
r.found[cacheKey] = target
return target, nil
}
func (r *relationResolver) fetch(typeKey string, id uint32) (EntryRelation, error) {
missing := EntryRelation{ID: id, Missing: true}
target, err := r.targetType(typeKey)
if err != nil || target == nil || len(target.Fields) == 0 {
return missing, err
}
record, err := r.entries.Get(target.ID, id)
if errors.Is(err, entry.ErrEntryNotFound) {
return missing, nil
}
if err != nil {
return EntryRelation{}, err
}
first := target.Fields[0]
return EntryRelation{ID: id, ContentType: typeKey, FirstField: EntryFirstField{Key: first.Key, Type: first.Type, Value: record.Data[first.Key]}}, nil
}
func (r *relationResolver) exists(typeKey string, id uint32) (bool, error) {
target, err := r.targetType(typeKey)
if err != nil || target == nil || len(target.Fields) == 0 {
return false, err
}
_, err = r.entries.Get(target.ID, id)
if errors.Is(err, entry.ErrEntryNotFound) {
return false, nil
}
return err == nil, err
}
func ensureRelationsExist(resolver *relationResolver, owner contenttype.ContentType, data map[string]any, stored map[string]any) error {
storedIDs := entry.RelationIDs(owner.Fields, stored)
for _, ref := range contenttype.RelationRefs(owner.Fields, data) {
for _, id := range ref.IDs {
unchanged := stored != nil && storedIDs[ref.Field.Key][id]
if unchanged && !ref.Field.Required {
continue
}
exists, err := resolver.exists(ref.Field.Relation.ContentType, id)
if err != nil {
return err
}
if !exists {
return entry.MissingRelation(ref.Field, unchanged)
}
}
}
return nil
}
func ensureRelationTargets(contentTypes contenttype.Repository, ownerKey string, fields []contenttype.Field) error {
for _, field := range contenttype.RelationFields(fields) {
target := field.Relation.ContentType
if target == ownerKey {
if field.IsExclusiveRelation() {
return contenttype.ErrInvalidField
}
continue
}
_, err := contentTypes.GetByKey(target)
if errors.Is(err, contenttype.ErrContentTypeNotFound) {
return contenttype.ErrInvalidField
}
if err != nil {
return err
}
}
return nil
}
func relationShapeChanged(previous []contenttype.Field, next []contenttype.Field) bool {
nextByKey := make(map[string]contenttype.Field, len(next))
for _, field := range next {
nextByKey[field.Key] = field
}
for _, field := range contenttype.RelationFields(previous) {
if replacement, kept := nextByKey[field.Key]; kept && !contenttype.SameRelation(field, replacement) {
return true
}
}
return false
}
@@ -11,15 +11,29 @@ type TypedEntry struct {
entry.Entry
ContentTypeKey string
Media map[string]EntryMedia
Relations map[string]EntryRelations
}
func typedEntry(owner contenttype.ContentType, record entry.Entry, resolver *mediaResolver) (TypedEntry, error) {
type entryResolvers struct {
media *mediaResolver
relations *relationResolver
}
func newEntryResolvers(images image.Repository, contentTypes contenttype.Repository, entries entry.Repository) *entryResolvers {
return &entryResolvers{media: newMediaResolver(images), relations: newRelationResolver(contentTypes, entries)}
}
func typedEntry(owner contenttype.ContentType, record entry.Entry, resolvers *entryResolvers) (TypedEntry, error) {
record.Data = entry.Project(owner.Fields, record.Data)
media, err := resolver.resolve(owner, record)
media, err := resolvers.media.resolve(owner, record)
if err != nil {
return TypedEntry{}, err
}
return TypedEntry{Entry: record, ContentTypeKey: owner.Key, Media: media}, nil
relations, err := resolvers.relations.resolve(owner, record)
if err != nil {
return TypedEntry{}, err
}
return TypedEntry{Entry: record, ContentTypeKey: owner.Key, Media: media, Relations: relations}, nil
}
func ensureMediaExists(images image.Repository, owner contenttype.ContentType, data map[string]any, stored map[string]any) error {
+371
View File
@@ -0,0 +1,371 @@
import { mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
import { basename, dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import {
API_GROUPS,
ERROR_ROWS,
PUBLIC_AUTH_ROWS,
SESSION_GROUPS,
endpointExamples,
type ApiEndpoint,
type ApiField,
} from '../web/src/data/apiCatalogue'
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const outDir = join(root, 'internal/infrastructure/llmdocs/generated')
const pagesDir = join(outDir, 'llms')
const VERSION = '{{VERSION}}'
const BASE_URL = '{{BASE_URL}}'
interface Page {
name: string
title: string
summary: string
body: () => string
}
const read = (relative: string) => readFileSync(join(root, relative), 'utf8')
function section(markdown: string, heading: string) {
const lines = markdown.split('\n')
const start = lines.findIndex((line) => line.trim() === heading)
if (start === -1) throw new Error(`heading not found: ${heading}`)
const level = heading.match(/^#+/)![0].length
const end = lines.findIndex(
(line, index) => index > start && /^#+ /.test(line) && line.match(/^#+/)![0].length <= level,
)
return lines.slice(start, end === -1 ? undefined : end).join('\n')
}
const docFiles = (directory: string) =>
readdirSync(join(root, directory))
.filter((file) => file.endsWith('.md'))
.sort()
.map((file) => `${directory}/${file}`)
const fieldTable = (fields: ApiField[]) =>
[
'| Name | Type | Required | Rule |',
'| --- | --- | --- | --- |',
...fields.map(
(field) =>
`| \`${field.name}\` | ${field.type} | ${field.required ? 'yes' : 'no'} | ${field.rule.replaceAll('|', '\\|')} |`,
),
].join('\n')
function endpointMarkdown(item: ApiEndpoint) {
const examples = endpointExamples(item, BASE_URL)
const parts = [
`### ${item.method} ${item.path}`,
`Access: ${item.access}. Success status: ${item.status}.${item.rateLimited ? ' Rate limited.' : ''}`,
item.description,
]
if (item.query.length > 0) parts.push(`Query parameters:\n\n${fieldTable(item.query)}`)
if (item.body.length > 0) {
const kind = item.bodyKind === 'multipart' ? 'multipart/form-data' : 'JSON'
parts.push(`Body (${kind}):\n\n${fieldTable(item.body)}`)
}
parts.push(`Example:\n\n\`\`\`sh\n${examples.curl}\n\`\`\``)
parts.push(`Response:\n\n\`\`\`\n${item.response}\n\`\`\``)
if (item.errors.length > 0) {
parts.push(
`Errors:\n\n${item.errors.map((error) => `- ${error.status}: ${error.caption}`).join('\n')}`,
)
}
return parts.join('\n\n')
}
function apiReference() {
const parts = [
'# API reference',
`Generated from the route catalogue of RenewCMS ${VERSION}. Base URL: ${BASE_URL}. Every path starts with /v1. Send \`Authorization: Bearer rcms_...\` on every route except the public ones.`,
]
for (const group of API_GROUPS) {
parts.push(`## ${group.title}`, group.description)
parts.push(...group.endpoints.map(endpointMarkdown))
}
parts.push(
'## Session-only routes',
'A key sent to these routes answers 403 "This action needs a real session.", except the sign-in routes, which ignore a key.',
)
for (const group of SESSION_GROUPS) {
parts.push(
`### ${group.title}`,
group.rows.map((row) => `- ${row.method} ${row.path}: ${row.description}`).join('\n'),
)
}
parts.push(
'## Public routes outside the article reads',
PUBLIC_AUTH_ROWS.map((row) => `- ${row.method} ${row.path}: ${row.description}`).join('\n'),
)
parts.push(
'## Errors',
ERROR_ROWS.map(
(row) =>
`- ${row.status} ${row.meaning}: ${row.messages.map((message) => `"${message}"`).join(', ')}${row.note ? ` ${row.note}` : ''}`,
).join('\n'),
)
return parts.join('\n\n')
}
const API_PAGE_SUMMARIES: Record<string, string> = {
articles: 'Article reads: pagination, search, counts, the format parameter, SEO status.',
'api-keys': 'Creating, listing and revoking API keys, and where a key is accepted.',
}
const pages: Page[] = [
{
name: 'api-reference',
title: 'API reference',
summary: 'Every key-callable route with parameters, bodies, curl examples, responses and errors.',
body: apiReference,
},
{
name: 'api',
title: 'API overview',
summary: 'Base URL, authentication, API key limits, activity log.',
body: () => read('docs/api.md'),
},
...docFiles('docs/api').map((file) => ({
name: basename(file, '.md'),
title: read(file).match(/^# (.+)$/m)?.[1] ?? basename(file, '.md'),
summary: API_PAGE_SUMMARIES[basename(file, '.md')] ?? '',
body: () => read(file),
})),
...docFiles('docs/llm').map((file) => ({
name: basename(file, '.md'),
title: read(file).match(/^# (.+)$/m)?.[1] ?? basename(file, '.md'),
summary: read(file).match(/^> (.+)$/m)?.[1] ?? '',
body: () => read(file).replace(/^> .+\n+/m, ''),
})),
{
name: 'configuration',
title: 'Configuration',
summary: 'Environment variables of the server.',
body: () => `# Configuration\n\n${section(read('docs/configuration.md'), '## Variables')}`,
},
]
const pageNames = new Map(pages.map((page) => [page.name, page]))
function rewriteLinks(markdown: string) {
return markdown.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (whole, text: string, target: string) => {
if (/^(https?:|mailto:|#|\{\{)/.test(target)) return whole
const [file, anchor] = target.split('#')
const page = pageNames.get(basename(file, '.md'))
if (!page || !file.endsWith('.md')) return text
return `[${text}](${BASE_URL}/llms/${page.name}.md${anchor ? `#${anchor}` : ''})`
})
}
const rendered = pages.map((page) => ({ page, text: rewriteLinks(page.body()).trim() }))
const index = [
'# RenewCMS',
`> A small self-hosted CMS. A JSON API under /v1 manages articles, media and sites; articles and sitemaps are readable without credentials. Version ${VERSION}, served by ${BASE_URL}.`,
'Authenticate with an API key: `Authorization: Bearer rcms_...`. A key acts as its creator, 120 requests per minute. Some routes need a browser session and answer 403 to a key; see the gotchas page.',
'## Docs',
rendered
.map(({ page }) => `- [${page.title}](${BASE_URL}/llms/${page.name}.md): ${page.summary}`)
.join('\n'),
'## Machine-readable',
[
`- [llms-full.txt](${BASE_URL}/llms-full.txt): all of the pages above in one file`,
`- [openapi.json](${BASE_URL}/openapi.json): OpenAPI 3.1 description of the routes in the API reference`,
].join('\n'),
].join('\n\n')
const full = [
`# RenewCMS documentation\n\nVersion ${VERSION}. Served by ${BASE_URL}.`,
...rendered.map(({ text }) => text),
].join('\n\n---\n\n')
const SCALARS: Record<string, object> = {
string: { type: 'string' },
number: { type: 'number' },
boolean: { type: 'boolean' },
null: { type: 'null' },
file: { type: 'string', format: 'binary' },
}
function schemaOf(type: string): object {
const alternatives = type.split('|').map((part) => part.trim())
if (alternatives.length > 1) return { anyOf: alternatives.map(schemaOf) }
if (type.endsWith('[]')) return { type: 'array', items: schemaOf(type.slice(0, -2)) }
return SCALARS[type] ?? {}
}
const objectSchema = (fields: ApiField[]) => ({
type: 'object',
properties: Object.fromEntries(
fields.map((field) => [field.name, { ...schemaOf(field.type), description: field.rule }]),
),
required: fields.filter((field) => field.required).map((field) => field.name),
})
function parseExample(response: string) {
try {
return JSON.parse(response)
} catch {
return undefined
}
}
type Schema = Record<string, unknown>
function mergeSchemas(schemas: Schema[]): Schema {
const unique = [...new Map(schemas.map((schema) => [JSON.stringify(schema), schema])).values()]
if (unique.length === 1) return unique[0]
const objects = unique.filter((schema) => schema.type === 'object')
if (objects.length > 1 && objects.length === unique.length) {
const keys = [...new Set(objects.flatMap((schema) => Object.keys(schema.properties as Schema)))]
return {
type: 'object',
properties: Object.fromEntries(
keys.map((key) => [
key,
mergeSchemas(
objects
.map((schema) => (schema.properties as Record<string, Schema>)[key])
.filter((schema) => schema !== undefined),
),
]),
),
required: keys.filter((key) =>
objects.every((schema) => key in (schema.properties as Schema)),
),
}
}
return { anyOf: unique }
}
function inferSchema(value: unknown): Schema {
if (value === null) return { type: 'null' }
if (Array.isArray(value)) {
return value.length === 0
? { type: 'array', items: {} }
: { type: 'array', items: mergeSchemas(value.map(inferSchema)) }
}
if (typeof value === 'object') {
const entries = Object.entries(value as Record<string, unknown>)
return {
type: 'object',
properties: Object.fromEntries(entries.map(([key, child]) => [key, inferSchema(child)])),
required: entries.map(([key]) => key),
}
}
if (typeof value === 'number') return { type: Number.isInteger(value) ? 'integer' : 'number' }
return { type: typeof value }
}
function operation(item: ApiEndpoint) {
const pathParameters = [...item.path.matchAll(/\{(\w+)\}/g)].map((match) => ({
name: match[1],
in: 'path',
required: true,
schema: match[1] === 'id' ? { type: 'integer', minimum: 0 } : { type: 'string' },
}))
const queryParameters = item.query.map((field) => ({
name: field.name,
in: 'query',
required: field.required,
description: field.rule,
schema: schemaOf(field.type),
}))
const example = parseExample(item.response)
const responses: Record<string, object> = {
[String(item.status)]:
item.status === 204
? { description: 'No content' }
: {
description: 'Success',
content: {
'application/json': {
schema: example === undefined ? {} : inferSchema(example),
...(example === undefined ? {} : { example }),
},
},
},
}
for (const error of item.errors) {
const key = String(error.status)
const previous = (responses[key] as { description?: string } | undefined)?.description
responses[key] = {
description: previous ? `${previous} / ${error.caption}` : error.caption,
content: { 'text/plain': { schema: { type: 'string' } } },
}
}
const result: Record<string, unknown> = {
operationId: item.id,
summary: item.description,
'x-access': item.access,
parameters: [...pathParameters, ...queryParameters],
responses,
}
if (item.access !== 'Public') result.security = [{ bearerAuth: [] }, { cookieAuth: [] }]
if (item.bodyKind === 'json') {
const media = {
schema: objectSchema(item.body),
...(item.bodySample ? { example: item.bodySample } : {}),
}
result.requestBody = { required: true, content: { 'application/json': media } }
}
if (item.bodyKind === 'multipart') {
result.requestBody = {
required: true,
content: { 'multipart/form-data': { schema: objectSchema(item.body) } },
}
}
return result
}
const paths: Record<string, Record<string, unknown>> = {}
for (const group of API_GROUPS) {
for (const item of group.endpoints) {
paths[item.path] ??= {}
paths[item.path][item.method.toLowerCase()] = operation(item)
}
}
for (const group of SESSION_GROUPS) {
for (const row of group.rows) {
paths[row.path] ??= {}
paths[row.path][row.method.toLowerCase()] = {
summary: row.description,
'x-session-only': row.answers403,
security: [{ cookieAuth: [] }],
responses: { '200': { description: 'Success' } },
}
}
}
for (const row of PUBLIC_AUTH_ROWS) {
paths[row.path] ??= {}
paths[row.path][row.method.toLowerCase()] = {
summary: row.description,
responses: { '200': { description: 'Success' } },
}
}
const openapi = {
openapi: '3.1.0',
info: {
title: 'RenewCMS API',
version: VERSION,
description: 'Generated from the route catalogue. Routes listed with x-session-only answer 403 to an API key.',
},
servers: [{ url: BASE_URL }],
paths,
components: {
securitySchemes: {
bearerAuth: { type: 'http', scheme: 'bearer', description: 'An API key starting with rcms_' },
cookieAuth: { type: 'apiKey', in: 'cookie', name: 'jwt' },
},
},
}
rmSync(pagesDir, { recursive: true, force: true })
mkdirSync(pagesDir, { recursive: true })
for (const { page, text } of rendered) writeFileSync(join(pagesDir, `${page.name}.md`), `${text}\n`)
writeFileSync(join(outDir, 'llms.txt'), `${index}\n`)
writeFileSync(join(outDir, 'llms-full.txt'), `${full}\n`)
writeFileSync(join(outDir, 'openapi.json'), `${JSON.stringify(openapi, null, 2)}\n`)
+120
View File
@@ -0,0 +1,120 @@
package test
import (
"RenewCMS/api"
"RenewCMS/internal/infrastructure/config"
"net/http"
"os"
"regexp"
"sort"
"strings"
"testing"
"github.com/go-chi/chi/v5"
)
var catalogueRoutePatterns = []*regexp.Regexp{
regexp.MustCompile(`\w+\(\s*'[^']+',\s*'([A-Z]+)',\s*'([^']+)'`),
regexp.MustCompile(`row\(\s*'([A-Z]+)',\s*'([^']+)'`),
regexp.MustCompile(`method: '([A-Z]+)',\s*path: '([^']+)'`),
}
func catalogueRoutes(t *testing.T) map[string]bool {
t.Helper()
raw, err := os.ReadFile("../web/src/data/apiCatalogue.ts")
if err != nil {
t.Fatal(err)
}
routes := map[string]bool{}
for _, pattern := range catalogueRoutePatterns {
for _, m := range pattern.FindAllStringSubmatch(string(raw), -1) {
routes[m[1]+" "+strings.TrimSuffix(m[2], "/")] = true
}
}
return routes
}
func routerRoutes(t *testing.T) map[string]bool {
t.Helper()
router := api.InitBackendRoutes(&api.UseCases{}, config.Settings{})
routes := map[string]bool{}
err := chi.Walk(router, func(method, route string, _ http.Handler, _ ...func(http.Handler) http.Handler) error {
route = strings.ReplaceAll(route, "/*", "")
routes[method+" /v1"+strings.TrimSuffix(route, "/")] = true
return nil
})
if err != nil {
t.Fatal(err)
}
return routes
}
var routesNotYetInTheCatalogue = []string{
"DELETE /v1/content-type/{key}",
"DELETE /v1/content-type/{key}/entry/{id}",
"DELETE /v1/image-variants/{name}",
"DELETE /v1/media/{id}/variants/{name}",
"GET /v1/builtin-type",
"GET /v1/builtin-type/{key}",
"GET /v1/content-type",
"GET /v1/content-type/{key}",
"GET /v1/content-type/{key}/entry",
"GET /v1/content-type/{key}/entry/{id}",
"GET /v1/image-variants",
"GET /v1/image-variants/cache",
"GET /v1/media/{id}/variants",
"GET /v1/user/lookup",
"PATCH /v1/image-variants/{name}",
"POST /v1/content-type",
"POST /v1/content-type/{key}/entry",
"POST /v1/image-variants",
"POST /v1/image-variants/cache/purge",
"POST /v1/image-variants/{name}/purge",
"POST /v1/media/{id}/variants",
"POST /v1/media/{id}/variants/{name}",
"PUT /v1/content-type/{key}",
"PUT /v1/content-type/{key}/entry/{id}",
"PUT /v1/image-variants/{name}",
}
func TestRouterRoutesAreInTheCatalogue(t *testing.T) {
documented := catalogueRoutes(t)
exempt := map[string]bool{}
for _, route := range routesNotYetInTheCatalogue {
exempt[route] = true
}
actual := routerRoutes(t)
var missing, stale []string
for route := range actual {
if !documented[route] && !exempt[route] {
missing = append(missing, route)
}
}
for route := range exempt {
if documented[route] || !actual[route] {
stale = append(stale, route)
}
}
sort.Strings(missing)
sort.Strings(stale)
if len(missing) > 0 {
t.Errorf("routes missing from web/src/data/apiCatalogue.ts:\n%s", strings.Join(missing, "\n"))
}
if len(stale) > 0 {
t.Errorf("routes to remove from routesNotYetInTheCatalogue:\n%s", strings.Join(stale, "\n"))
}
}
func TestCatalogueRoutesExistInTheRouter(t *testing.T) {
actual := routerRoutes(t)
var unknown []string
for route := range catalogueRoutes(t) {
if strings.Contains(route, " /v1") && !actual[route] {
unknown = append(unknown, route)
}
}
sort.Strings(unknown)
if len(unknown) > 0 {
t.Errorf("catalogue routes the router does not serve:\n%s", strings.Join(unknown, "\n"))
}
}
@@ -35,7 +35,7 @@ const supportRecipeKey = "recipe"
var supportContentTypeKeys = []string{"created_at", "fields", "icon", "id", "key", "name", "updated_at"}
var supportFieldKeys = []string{"default", "key", "label", "max", "min", "options", "required", "type", "unique"}
var supportFieldKeys = []string{"default", "key", "label", "max", "min", "options", "relation", "required", "type", "unique"}
func newSupportEnv(t *testing.T) *contentTypeEnv {
t.Helper()
+2 -2
View File
@@ -12,8 +12,8 @@ import (
var (
contentTypeKeys = []string{"created_at", "fields", "icon", "id", "key", "name", "updated_at"}
fieldKeys = []string{"default", "key", "label", "max", "min", "options", "required", "type", "unique"}
entryKeys = []string{"content_type", "created_at", "created_by", "data", "id", "media", "updated_at", "updated_by"}
fieldKeys = []string{"default", "key", "label", "max", "min", "options", "relation", "required", "type", "unique"}
entryKeys = []string{"content_type", "created_at", "created_by", "data", "id", "media", "relations", "updated_at", "updated_by"}
)
func TestCreatingAContentType(t *testing.T) {
+1 -1
View File
@@ -628,7 +628,7 @@ func TestContentTypeStoredFormat(t *testing.T) {
keys = append(keys, key)
}
sort.Strings(keys)
expected := []string{"default", "key", "label", "max", "min", "options", "required", "type", "unique"}
expected := []string{"default", "key", "label", "max", "min", "options", "relation", "required", "type", "unique"}
if !reflect.DeepEqual(keys, expected) {
t.Errorf("stored keys %v", keys)
}
+76
View File
@@ -0,0 +1,76 @@
package test
import (
"RenewCMS/api/handlers/llms"
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/fstest"
"github.com/go-chi/chi/v5"
)
func llmsRouter(docs fstest.MapFS) http.Handler {
r := chi.NewRouter()
llms.NewHandler(docs, "v9.9.9", "https://cms.example/").Register(r)
return r
}
func llmsGet(handler http.Handler, target string) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, target, nil))
return rec
}
func TestLlmsServesGeneratedDocsWithVersionAndBaseURL(t *testing.T) {
handler := llmsRouter(fstest.MapFS{
"llms.txt": {Data: []byte("# RenewCMS {{VERSION}}\n{{BASE_URL}}/llms-full.txt")},
"llms-full.txt": {Data: []byte("full {{VERSION}}")},
"openapi.json": {Data: []byte(`{"version":"{{VERSION}}","servers":[{"url":"{{BASE_URL}}"}]}`)},
"llms/gotchas.md": {Data: []byte("# Gotchas {{VERSION}}")},
"llms/private.txt": {Data: []byte("not a page")},
})
cases := []struct {
target string
contentType string
body string
}{
{"/llms.txt", "text/plain; charset=utf-8", "# RenewCMS v9.9.9\nhttps://cms.example/llms-full.txt"},
{"/llms-full.txt", "text/plain; charset=utf-8", "full v9.9.9"},
{"/openapi.json", "application/json", `{"version":"v9.9.9","servers":[{"url":"https://cms.example"}]}`},
{"/llms/gotchas.md", "text/markdown; charset=utf-8", "# Gotchas v9.9.9"},
}
for _, tc := range cases {
rec := llmsGet(handler, tc.target)
if rec.Code != http.StatusOK {
t.Fatalf("%s answered %d", tc.target, rec.Code)
}
if got := rec.Header().Get("Content-Type"); got != tc.contentType {
t.Errorf("%s content type %q, want %q", tc.target, got, tc.contentType)
}
if rec.Body.String() != tc.body {
t.Errorf("%s body %q, want %q", tc.target, rec.Body.String(), tc.body)
}
}
}
func TestLlmsAnswers404WhenNothingWasGenerated(t *testing.T) {
handler := llmsRouter(fstest.MapFS{})
for _, target := range []string{"/llms.txt", "/llms-full.txt", "/openapi.json", "/llms/gotchas.md", "/llms/private.txt", "/llms/..%2Fllms.txt"} {
rec := llmsGet(handler, target)
if rec.Code != http.StatusNotFound {
t.Errorf("%s answered %d, want 404", target, rec.Code)
}
if !strings.Contains(rec.Body.String(), "task build:llms") {
t.Errorf("%s body %q does not name the task", target, rec.Body.String())
}
}
}
func TestLlmsOnlyServesMarkdownPages(t *testing.T) {
handler := llmsRouter(fstest.MapFS{"llms/private.txt": {Data: []byte("not a page")}})
if rec := llmsGet(handler, "/llms/private.txt"); rec.Code != http.StatusNotFound {
t.Fatalf("answered %d, want 404", rec.Code)
}
}
+189
View File
@@ -0,0 +1,189 @@
package test
import (
"RenewCMS/internal/infrastructure/mcpserver"
"context"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"sync"
"testing"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
type recordedCall struct {
method string
target string
auth string
body string
ctype string
}
type mcpFixture struct {
session *mcp.ClientSession
mu sync.Mutex
calls []recordedCall
}
func (f *mcpFixture) last() recordedCall {
f.mu.Lock()
defer f.mu.Unlock()
return f.calls[len(f.calls)-1]
}
func newMCPFixture(t *testing.T, allowDestructive bool, respond func(w http.ResponseWriter, r *http.Request)) *mcpFixture {
t.Helper()
f := &mcpFixture{}
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, _ := io.ReadAll(r.Body)
f.mu.Lock()
f.calls = append(f.calls, recordedCall{r.Method, r.URL.RequestURI(), r.Header.Get("Authorization"), string(raw), r.Header.Get("Content-Type")})
f.mu.Unlock()
respond(w, r)
}))
t.Cleanup(api.Close)
server := mcpserver.New(mcpserver.NewClient(api.URL+"/", "rcms_key", nil), mcpserver.Options{Version: "test", AllowDestructive: allowDestructive})
ctx := context.Background()
serverSide, clientSide := mcp.NewInMemoryTransports()
if _, err := server.Connect(ctx, serverSide, nil); err != nil {
t.Fatal(err)
}
session, err := mcp.NewClient(&mcp.Implementation{Name: "test", Version: "0"}, nil).Connect(ctx, clientSide, nil)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = session.Close() })
f.session = session
return f
}
func (f *mcpFixture) callTool(t *testing.T, name string, args map[string]any) *mcp.CallToolResult {
t.Helper()
res, err := f.session.CallTool(context.Background(), &mcp.CallToolParams{Name: name, Arguments: args})
if err != nil {
t.Fatalf("%s: %v", name, err)
}
return res
}
func toolText(res *mcp.CallToolResult) string {
return res.Content[0].(*mcp.TextContent).Text
}
func echoStatus(status int, body string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(status)
_, _ = io.WriteString(w, body)
}
}
func TestMCPToolsMapToTheAPIWithTheKey(t *testing.T) {
f := newMCPFixture(t, false, echoStatus(200, `{"ok":true}`))
cases := []struct {
tool string
args map[string]any
method string
target string
body string
}{
{"list_articles", map[string]any{"page": 2, "size": 5, "status": "draft", "q": "tile"}, "GET", "/v1/article/?page=2&q=tile&size=5&status=draft", ""},
{"get_article", map[string]any{"id": 7, "format": "html"}, "GET", "/v1/article/7?format=html", ""},
{"create_article", map[string]any{"title": "Grout tips", "body": "<p>x</p>"}, "POST", "/v1/article/", `{"body":"<p>x</p>","title":"Grout tips"}`},
{"update_article_body", map[string]any{"id": 7, "body": "<p>y</p>"}, "PATCH", "/v1/article/7", `{"body":"<p>y</p>"}`},
{"publish_article", map[string]any{"id": 7}, "PATCH", "/v1/article/7/publish", ""},
{"check_seo", map[string]any{"id": 7}, "POST", "/v1/article/7/seo/check", `{}`},
{"list_media", map[string]any{"filter": "unused"}, "GET", "/v1/media/?filter=unused", ""},
{"list_sites", map[string]any{}, "GET", "/v1/site/", ""},
{"get_sitemap", map[string]any{"key": "renew-blog", "size": 25}, "GET", "/v1/site/renew-blog/sitemap?size=25", ""},
}
for _, tc := range cases {
res := f.callTool(t, tc.tool, tc.args)
if res.IsError || toolText(res) != `{"ok":true}` {
t.Fatalf("%s: error=%v text=%q", tc.tool, res.IsError, toolText(res))
}
call := f.last()
if call.method != tc.method || call.target != tc.target || !sameJSONBody(call.body, tc.body) || call.auth != "Bearer rcms_key" {
t.Errorf("%s sent %q want %q", tc.tool, call.body, tc.body)
}
}
}
func TestMCPReportsAPIErrorsAsToolErrors(t *testing.T) {
f := newMCPFixture(t, false, echoStatus(403, "This action needs a real session."))
res := f.callTool(t, "list_sites", map[string]any{})
if !res.IsError || toolText(res) != "HTTP 403: This action needs a real session." {
t.Fatalf("error=%v text=%q", res.IsError, toolText(res))
}
}
func TestMCPUploadsMultipartFromBase64(t *testing.T) {
f := newMCPFixture(t, false, echoStatus(201, `{"id":1}`))
res := f.callTool(t, "upload_media", map[string]any{"base64": base64.StdEncoding.EncodeToString([]byte("PNGDATA")), "filename": "wall.png"})
if res.IsError {
t.Fatal(toolText(res))
}
call := f.last()
if !strings.HasPrefix(call.ctype, "multipart/form-data") || !strings.Contains(call.body, `name="file"; filename="wall.png"`) || !strings.Contains(call.body, "PNGDATA") {
t.Errorf("sent %+v", call)
}
if res := f.callTool(t, "upload_media", map[string]any{}); !res.IsError {
t.Error("an upload without content must fail")
}
}
func TestMCPDestructiveToolsNeedTheFlag(t *testing.T) {
names := func(f *mcpFixture) map[string]bool {
found := map[string]bool{}
for tool, err := range f.session.Tools(context.Background(), nil) {
if err != nil {
t.Fatal(err)
}
found[tool.Name] = true
}
return found
}
safe := names(newMCPFixture(t, false, echoStatus(200, "")))
if safe["delete_article"] || safe["delete_media"] || !safe["publish_article"] || len(safe) != 10 {
t.Errorf("default tools: %v", safe)
}
f := newMCPFixture(t, true, echoStatus(204, ""))
if all := names(f); !all["delete_article"] || !all["delete_media"] {
t.Errorf("flagged tools: %v", all)
}
if res := f.callTool(t, "delete_article", map[string]any{"id": 3}); res.IsError || toolText(res) != "HTTP 204" || f.last().method != "DELETE" {
t.Errorf("delete: %q %+v", toolText(res), f.last())
}
}
func TestMCPServesTheInstanceDocumentationAsAResource(t *testing.T) {
f := newMCPFixture(t, false, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/llms-full.txt" {
w.WriteHeader(404)
return
}
_, _ = io.WriteString(w, "# RenewCMS documentation")
})
res, err := f.session.ReadResource(context.Background(), &mcp.ReadResourceParams{URI: "renewcms://docs/llms-full.txt"})
if err != nil {
t.Fatal(err)
}
if res.Contents[0].Text != "# RenewCMS documentation" {
t.Errorf("got %q", res.Contents[0].Text)
}
}
func sameJSONBody(got string, want string) bool {
if got == want {
return true
}
var a, b any
if json.Unmarshal([]byte(got), &a) != nil || json.Unmarshal([]byte(want), &b) != nil {
return false
}
return reflect.DeepEqual(a, b)
}
@@ -0,0 +1,66 @@
package test
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"testing"
)
func TestRelationFieldMediaIDBounds(t *testing.T) {
cases := []struct {
name string
value any
id uint32
ok bool
}{
{"uint32 one", uint32(1), 1, true},
{"uint32 zero", uint32(0), 0, false},
{"int one", 1, 1, true},
{"int zero", 0, 0, false},
{"int negative", -4, 0, false},
{"int64 max uint32", int64(4294967295), 4294967295, true},
{"int64 over uint32", int64(4294967296), 0, false},
{"int64 zero", int64(0), 0, false},
{"float whole", float64(7), 7, true},
{"float fraction", 7.5, 0, false},
{"float zero", float64(0), 0, false},
{"float max uint32", float64(4294967295), 4294967295, true},
{"float over uint32", float64(4294967296), 0, false},
{"string", "7", 0, false},
}
for _, c := range cases {
id, ok := contenttype.MediaID(c.value)
if ok != c.ok || id != c.id {
t.Errorf("%s: got (%d, %v), want (%d, %v)", c.name, id, ok, c.id, c.ok)
}
}
}
func TestRelationFieldQueryDisplayText(t *testing.T) {
text := []contenttype.Field{{Key: "name", Type: contenttype.TypeText}}
number := []contenttype.Field{{Key: "n", Type: contenttype.TypeNumber}}
if entry.MatchesQuery(nil, map[string]any{"name": "x"}, "x") {
t.Error("no fields must never match")
}
if !entry.MatchesQuery(text, map[string]any{"name": "Grand Hall"}, "grand") {
t.Error("case-insensitive text match expected")
}
if entry.MatchesQuery(text, map[string]any{}, "grand") {
t.Error("missing value must not match")
}
if !entry.MatchesQuery(text, map[string]any{}, "") {
t.Error("empty query matches an empty display text")
}
if !entry.MatchesQuery(number, map[string]any{"n": 3.5}, "3.5") {
t.Error("float must render without exponent or padding")
}
if !entry.MatchesQuery(number, map[string]any{"n": float64(42)}, "42") {
t.Error("whole float must render without decimals")
}
if entry.MatchesQuery(number, map[string]any{"n": float64(42)}, "42.0") {
t.Error("whole float must not render a decimal part")
}
if !entry.MatchesQuery(number, map[string]any{"n": true}, "true") {
t.Error("other kinds fall back to default formatting")
}
}
+539
View File
@@ -0,0 +1,539 @@
package test
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/internal/domain/entry"
"encoding/json"
"net/http"
"net/http/httptest"
"reflect"
"strconv"
"strings"
"testing"
)
type relationEnv struct {
*contentTypeEnv
}
func relationField(key string, label string, target string, kind string, required bool) map[string]any {
return map[string]any{"key": key, "label": label, "type": "relation", "required": required, "unique": false, "default": nil, "min": nil, "max": nil, "options": []string{}, "relation": map[string]any{"content_type": target, "kind": kind}}
}
func eventRelationFields(venueRequired bool, speakersRequired bool) []map[string]any {
return []map[string]any{
{"key": "title", "label": "Title", "type": "text", "required": true},
relationField("venue", "Venue", "venue", "one_to_many", venueRequired),
relationField("speakers", "Speakers", "speaker", "many_to_many", speakersRequired),
}
}
func newRelationEnv(t *testing.T, venueRequired bool, speakersRequired bool) *relationEnv {
t.Helper()
env := &relationEnv{newContentTypeEnv(t)}
env.createType(t, "venue", []map[string]any{{"key": "title", "label": "Title", "type": "text", "required": true}, {"key": "city", "label": "City", "type": "text"}})
env.createType(t, "speaker", []map[string]any{{"key": "name", "label": "Name", "type": "text", "required": true}})
env.createType(t, "event", eventRelationFields(venueRequired, speakersRequired))
env.seed(t, "venue", 3, "title", "Rue Verte hall")
env.seed(t, "venue", 4, "title", "Rue Verte yard")
env.seed(t, "speaker", 11, "name", "Ines Duarte")
env.seed(t, "speaker", 12, "name", "Jonas Pereira")
env.entries.nextID = 100
return env
}
func (e *relationEnv) seed(t *testing.T, typeKey string, id uint32, field string, value any) {
t.Helper()
e.seedData(t, typeKey, id, map[string]any{field: value})
}
func (e *relationEnv) seedData(t *testing.T, typeKey string, id uint32, data map[string]any) {
t.Helper()
owner, err := e.types.GetByKey(typeKey)
if err != nil {
t.Fatalf("seed type %s: %v", typeKey, err)
}
e.entries.entries[id] = entry.Entry{ID: id, ContentTypeID: owner.ID, Data: data, CreatedBy: ctMemberId, UpdatedBy: ctMemberId, CreatedAt: e.clock, UpdatedAt: e.clock}
}
func (e *relationEnv) member(t *testing.T, method string, path string, body string) *httptest.ResponseRecorder {
t.Helper()
return e.as(t, ctMemberId, method, path, body)
}
func (e *relationEnv) postEvent(t *testing.T, data string) *httptest.ResponseRecorder {
t.Helper()
return e.createEntry(t, "event", ctMemberId, data)
}
func (e *relationEnv) putEvent(t *testing.T, id uint32, data string) *httptest.ResponseRecorder {
t.Helper()
return e.member(t, http.MethodPut, "/v1/content-type/event/entry/"+strconv.Itoa(int(id)), `{"data": `+data+`}`)
}
func (e *relationEnv) countEntries(typeKey string) int {
owner, _ := e.types.GetByKey(typeKey)
count, _ := e.entries.CountByContentType(owner.ID)
return count
}
func hall(id float64, key string, value string, typeKey string, fieldType string) map[string]any {
return map[string]any{"id": id, "content_type": typeKey, "first_field": map[string]any{"key": key, "type": fieldType, "value": value}}
}
func TestRelationFieldTypeContentTypes(t *testing.T) {
t.Run("Creating a content type with a relation field", func(t *testing.T) {
env := newContentTypeEnv(t)
fields := []map[string]any{{"key": "title", "label": "Title", "type": "text", "required": true}, relationField("venue", "Venue", "venue", "one_to_many", false)}
rec := env.admin(t, http.MethodPost, "/v1/content-type", typeBody("venue", "Venue", fields))
if rec.Code != http.StatusCreated {
t.Fatalf("status %d %s", rec.Code, rec.Body.String())
}
stored := decodeContentObject(t, rec)["fields"].([]any)
if stored[0].(map[string]any)["relation"] != nil || !reflect.DeepEqual(objectKeys(stored[1].(map[string]any)), fieldKeys) {
t.Errorf("fields %v", stored)
}
if !reflect.DeepEqual(stored[1].(map[string]any)["relation"], map[string]any{"content_type": "venue", "kind": "one_to_many"}) {
t.Errorf("relation %v", stored[1])
}
})
t.Run("A relation field with a bad definition is refused", func(t *testing.T) {
defects := map[string]func(map[string]any){
"relation null": func(f map[string]any) { f["relation"] = nil },
"content_type nope": func(f map[string]any) { f["relation"] = map[string]any{"content_type": "nope", "kind": "one_to_many"} },
"content_type empty": func(f map[string]any) { f["relation"] = map[string]any{"content_type": "", "kind": "one_to_many"} },
"content_type missing": func(f map[string]any) { f["relation"] = map[string]any{"kind": "one_to_many"} },
"kind many_to_one": func(f map[string]any) {
f["relation"] = map[string]any{"content_type": "speaker", "kind": "many_to_one"}
},
"kind missing": func(f map[string]any) { f["relation"] = map[string]any{"content_type": "speaker"} },
"a relation object on text": func(f map[string]any) { f["type"] = "text" },
"unique true": func(f map[string]any) { f["unique"] = true },
"default 3": func(f map[string]any) { f["default"] = 3 },
"min 1": func(f map[string]any) { f["min"] = 1 },
"max 5": func(f map[string]any) { f["max"] = 5 },
"options a": func(f map[string]any) { f["options"] = []string{"a"} },
"a one_to_one self relation": func(f map[string]any) { f["relation"] = map[string]any{"content_type": "talk", "kind": "one_to_one"} },
"an invalid field key": func(f map[string]any) { f["key"] = "Bad Key" },
}
for name, defect := range defects {
t.Run(name, func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "speaker", []map[string]any{{"key": "name", "label": "Name", "type": "text"}})
field := relationField("link", "Link", "speaker", "one_to_many", false)
defect(field)
rec := env.admin(t, http.MethodPost, "/v1/content-type", typeBody("talk", "Talk", []map[string]any{field}))
expectStatusAndBody(t, rec, http.StatusUnprocessableEntity, apperr.InvalidFieldErrorMessage)
if _, err := env.types.GetByKey("talk"); err == nil {
t.Error("talk should not be stored")
}
})
}
})
t.Run("A self relation is allowed for one_to_many and many_to_many", func(t *testing.T) {
env := newContentTypeEnv(t)
for key, kind := range map[string]string{"selfmany": "one_to_many", "selfpool": "many_to_many"} {
fields := []map[string]any{{"key": "title", "label": "Title", "type": "text"}, relationField("parent", "Parent", key, kind, false)}
rec := env.admin(t, http.MethodPost, "/v1/content-type", typeBody(key, "Self", fields))
if rec.Code != http.StatusCreated {
t.Errorf("%s: %d %s", kind, rec.Code, rec.Body.String())
}
}
})
t.Run("The shape of a saved relation never changes", func(t *testing.T) {
changes := map[string]func(fields []map[string]any){
"kind to many_to_many": func(f []map[string]any) {
f[1]["relation"] = map[string]any{"content_type": "venue", "kind": "many_to_many"}
},
"target to speaker": func(f []map[string]any) {
f[1]["relation"] = map[string]any{"content_type": "speaker", "kind": "one_to_many"}
},
"turned into text": func(f []map[string]any) {
f[1]["type"] = "text"
f[1]["relation"] = nil
},
}
for name, change := range changes {
t.Run(name, func(t *testing.T) {
env := newRelationEnv(t, false, false)
fields := eventRelationFields(false, false)
change(fields)
rec := env.admin(t, http.MethodPut, "/v1/content-type/event", typeBody("event", "Event", fields))
expectStatusAndBody(t, rec, http.StatusUnprocessableEntity, apperr.InvalidFieldErrorMessage)
stored, _ := env.types.GetByKey("event")
if stored.Fields[1].Relation == nil || stored.Fields[1].Relation.ContentType != "venue" {
t.Errorf("schema changed: %v", stored.Fields[1])
}
})
}
})
t.Run("Adding a relation field to a type that has entries", func(t *testing.T) {
for _, example := range []struct {
required bool
status int
message string
}{{true, http.StatusConflict, apperr.SchemaIncompatibleErrorMessage}, {false, http.StatusOK, ""}} {
t.Run(strconv.FormatBool(example.required), func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "venue", []map[string]any{{"key": "title", "label": "Title", "type": "text"}})
env.createType(t, "event", []map[string]any{{"key": "title", "label": "Title", "type": "text"}})
for range 12 {
env.createEntry(t, "event", ctMemberId, `{"title":"A"}`)
}
fields := []map[string]any{{"key": "title", "label": "Title", "type": "text"}, relationField("venue", "Venue", "venue", "one_to_many", example.required)}
rec := env.admin(t, http.MethodPut, "/v1/content-type/event", typeBody("event", "Event", fields))
expectStatusAndBody(t, rec, example.status, example.message)
})
}
})
t.Run("Deleting a type that another type points at", func(t *testing.T) {
env := newRelationEnv(t, false, false)
env.entries.entries = map[uint32]entry.Entry{}
rec := env.admin(t, http.MethodDelete, "/v1/content-type/venue", "")
expectStatusAndBody(t, rec, http.StatusConflict, apperr.ContentTypeReferencedErrorMessage)
if _, err := env.types.GetByKey("venue"); err != nil {
t.Error("venue should still exist")
}
fields := []map[string]any{{"key": "title", "label": "Title", "type": "text", "required": true}, relationField("speakers", "Speakers", "speaker", "many_to_many", false)}
env.admin(t, http.MethodPut, "/v1/content-type/event", typeBody("event", "Event", fields))
expectStatusAndBody(t, env.admin(t, http.MethodDelete, "/v1/content-type/venue", ""), http.StatusNoContent, "")
})
}
func TestRelationFieldTypeEntries(t *testing.T) {
t.Run("Creating an entry with a single target", func(t *testing.T) {
env := newRelationEnv(t, false, false)
rec := env.postEvent(t, `{"title":"Lime plaster workshop","venue":3}`)
if rec.Code != http.StatusCreated {
t.Fatalf("status %d %s", rec.Code, rec.Body.String())
}
body := decodeContentObject(t, rec)
want := map[string]any{"venue": hall(3, "title", "Rue Verte hall", "venue", "text")}
if !reflect.DeepEqual(objectKeys(body), entryKeys) || body["data"].(map[string]any)["venue"] != float64(3) || !reflect.DeepEqual(body["relations"], want) {
t.Errorf("body %s", rec.Body.String())
}
})
t.Run("Creating an entry with many targets", func(t *testing.T) {
env := newRelationEnv(t, false, false)
rec := env.postEvent(t, `{"title":"A","speakers":[12,11]}`)
body := decodeContentObject(t, rec)
want := []any{hall(12, "name", "Jonas Pereira", "speaker", "text"), hall(11, "name", "Ines Duarte", "speaker", "text")}
if rec.Code != http.StatusCreated || !reflect.DeepEqual(body["relations"].(map[string]any)["speakers"], want) || !reflect.DeepEqual(body["data"].(map[string]any)["speakers"], []any{float64(12), float64(11)}) {
t.Errorf("body %s", rec.Body.String())
}
})
t.Run("Empty optional relations", func(t *testing.T) {
for _, example := range []struct{ data, key string }{{`{"title":"A","venue":null}`, "venue"}, {`{"title":"A"}`, "venue"}, {`{"title":"A","speakers":[]}`, "speakers"}} {
t.Run(example.data, func(t *testing.T) {
env := newRelationEnv(t, false, false)
rec := env.postEvent(t, example.data)
body := decodeContentObject(t, rec)
if rec.Code != http.StatusCreated || !reflect.DeepEqual(body["relations"], map[string]any{}) {
t.Errorf("body %s", rec.Body.String())
}
})
}
})
t.Run("Values that break a relation are refused and store nothing", func(t *testing.T) {
fiftyOne := make([]string, 51)
for index := range fiftyOne {
fiftyOne[index] = strconv.Itoa(index + 1)
}
for _, example := range []struct {
required bool
data string
message string
}{
{true, `{"title":"A"}`, "invalid_entry: venue: required"},
{true, `{"title":"A","venue":null}`, "invalid_entry: venue: required"},
{false, `{"title":"A","venue":999}`, "invalid_entry: venue: type"},
{false, `{"title":"A","venue":"3"}`, "invalid_entry: venue: type"},
{false, `{"title":"A","venue":0}`, "invalid_entry: venue: type"},
{false, `{"title":"A","venue":3.5}`, "invalid_entry: venue: type"},
{false, `{"title":"A","venue":[3]}`, "invalid_entry: venue: type"},
{false, `{"title":"A","speakers":11}`, "invalid_entry: speakers: type"},
{false, `{"title":"A","speakers":[11,11]}`, "invalid_entry: speakers: type"},
{false, `{"title":"A","speakers":[11,999]}`, "invalid_entry: speakers: type"},
{false, `{"title":"A","speakers":[3]}`, "invalid_entry: speakers: type"},
{false, `{"title":"A","speakers":[` + strings.Join(fiftyOne, ",") + `]}`, "invalid_entry: speakers: type"},
} {
t.Run(example.data[:min(len(example.data), 40)], func(t *testing.T) {
env := newRelationEnv(t, example.required, false)
rec := env.postEvent(t, example.data)
expectStatusAndBody(t, rec, http.StatusUnprocessableEntity, example.message)
if env.countEntries("event") != 0 {
t.Error("an entry was stored")
}
})
}
})
t.Run("A required many relation is never empty", func(t *testing.T) {
env := newRelationEnv(t, false, true)
expectStatusAndBody(t, env.postEvent(t, `{"title":"A","speakers":[]}`), http.StatusUnprocessableEntity, "invalid_entry: speakers: required")
expectStatusAndBody(t, env.postEvent(t, `{"title":"A"}`), http.StatusUnprocessableEntity, "invalid_entry: speakers: required")
})
t.Run("One to one keeps targets exclusive", func(t *testing.T) {
env := newRelationEnv(t, false, false)
env.createType(t, "talk", []map[string]any{{"key": "title", "label": "Title", "type": "text"}, relationField("room", "Room", "venue", "one_to_one", false)})
env.seedData(t, "talk", 50, map[string]any{"title": "Holder", "room": float64(3)})
post := func() *httptest.ResponseRecorder {
return env.createEntry(t, "talk", ctMemberId, `{"title":"B","room":3}`)
}
expectStatusAndBody(t, post(), http.StatusConflict, "invalid_entry: room: unique")
if env.countEntries("talk") != 1 {
t.Error("a talk was stored")
}
unchanged := env.member(t, http.MethodPut, "/v1/content-type/talk/entry/50", `{"data":{"title":"Holder","room":3}}`)
if unchanged.Code != http.StatusOK {
t.Errorf("unchanged holder: %d %s", unchanged.Code, unchanged.Body.String())
}
env.member(t, http.MethodDelete, "/v1/content-type/talk/entry/50", "")
if rec := post(); rec.Code != http.StatusCreated {
t.Errorf("after delete: %d %s", rec.Code, rec.Body.String())
}
})
t.Run("Replacing and clearing targets", func(t *testing.T) {
env := newRelationEnv(t, false, false)
env.seedData(t, "event", 5, map[string]any{"title": "E", "venue": float64(3), "speakers": []any{float64(11)}})
rec := env.putEvent(t, 5, `{"title":"E","venue":4,"speakers":[11,12]}`)
body := decodeContentObject(t, rec)
relations := body["relations"].(map[string]any)
if rec.Code != http.StatusOK || relations["venue"].(map[string]any)["id"] != float64(4) || len(relations["speakers"].([]any)) != 2 || body["data"].(map[string]any)["venue"] != float64(4) {
t.Errorf("body %s", rec.Body.String())
}
cleared := decodeContentObject(t, env.putEvent(t, 5, `{"title":"E","venue":null,"speakers":[]}`))
if !reflect.DeepEqual(cleared["relations"], map[string]any{}) {
t.Errorf("cleared %v", cleared)
}
})
t.Run("A target deleted after the entry was saved", func(t *testing.T) {
env := newRelationEnv(t, false, false)
env.seedData(t, "event", 5, map[string]any{"title": "E", "venue": float64(3), "speakers": []any{float64(11), float64(12)}})
before := env.entries.entries[5]
expectStatusAndBody(t, env.member(t, http.MethodDelete, "/v1/content-type/venue/entry/3", ""), http.StatusNoContent, "")
expectStatusAndBody(t, env.member(t, http.MethodDelete, "/v1/content-type/speaker/entry/12", ""), http.StatusNoContent, "")
rec := env.member(t, http.MethodGet, "/v1/content-type/event/entry/5", "")
body := decodeContentObject(t, rec)
relations := body["relations"].(map[string]any)
wantSpeakers := []any{hall(11, "name", "Ines Duarte", "speaker", "text"), map[string]any{"id": float64(12), "missing": true}}
if !reflect.DeepEqual(relations["venue"], map[string]any{"id": float64(3), "missing": true}) || !reflect.DeepEqual(relations["speakers"], wantSpeakers) {
t.Errorf("relations %v", relations)
}
if !reflect.DeepEqual(body["data"].(map[string]any)["speakers"], []any{float64(11), float64(12)}) || !reflect.DeepEqual(env.entries.entries[5], before) {
t.Errorf("entry modified: %v", env.entries.entries[5])
}
})
t.Run("Unchanged and changed ids when the target is gone", func(t *testing.T) {
for _, example := range []struct {
value string
status int
message string
}{{"3", 200, ""}, {"999", 422, "invalid_entry: venue: type"}, {"4", 200, ""}, {"null", 200, ""}} {
t.Run(example.value, func(t *testing.T) {
env := newRelationEnv(t, false, false)
env.seedData(t, "event", 5, map[string]any{"title": "E", "venue": float64(3)})
delete(env.entries.entries, 3)
rec := env.putEvent(t, 5, `{"title":"E","venue":`+example.value+`}`)
expectStatusAndBody(t, rec, example.status, example.message)
})
}
})
t.Run("A required relation with a missing target can't be saved as is", func(t *testing.T) {
for _, example := range []struct {
value string
status int
message string
unchanged bool
}{{"3", 422, "invalid_entry: venue: required", true}, {"null", 422, "invalid_entry: venue: required", true}, {"4", 200, "", false}} {
t.Run(example.value, func(t *testing.T) {
env := newRelationEnv(t, true, false)
env.seedData(t, "event", 5, map[string]any{"title": "E", "venue": float64(3)})
delete(env.entries.entries, 3)
before := env.entries.entries[5]
rec := env.putEvent(t, 5, `{"title":"E","venue":`+example.value+`}`)
expectStatusAndBody(t, rec, example.status, example.message)
if example.unchanged && !reflect.DeepEqual(env.entries.entries[5], before) {
t.Error("the stored entry changed")
}
})
}
})
t.Run("A create always treats the id as changed", func(t *testing.T) {
env := newRelationEnv(t, false, false)
delete(env.entries.entries, 3)
expectStatusAndBody(t, env.postEvent(t, `{"title":"A","venue":3}`), http.StatusUnprocessableEntity, "invalid_entry: venue: type")
})
t.Run("Two broken fields name only one", func(t *testing.T) {
env := newRelationEnv(t, false, false)
expectStatusAndBody(t, env.postEvent(t, `{"title":"","venue":999}`), http.StatusUnprocessableEntity, "invalid_entry: venue: type")
expectStatusAndBody(t, env.postEvent(t, `{"venue":999}`), http.StatusUnprocessableEntity, "invalid_entry: title: required")
})
t.Run("Entry list responses carry relations per item", func(t *testing.T) {
env := newRelationEnv(t, false, false)
env.seedData(t, "event", 5, map[string]any{"title": "One", "venue": float64(3), "speakers": []any{float64(11), float64(12)}})
env.seedData(t, "event", 6, map[string]any{"title": "Two", "venue": float64(99)})
env.seedData(t, "event", 7, map[string]any{"title": "Three"})
rec := env.member(t, http.MethodGet, "/v1/content-type/event/entry?sort=id:asc", "")
var page struct {
Items []map[string]any `json:"items"`
Total int `json:"total"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &page); err != nil || page.Total != 3 || len(page.Items) != 3 {
t.Fatalf("page %s", rec.Body.String())
}
for _, item := range page.Items {
if !reflect.DeepEqual(objectKeys(item), entryKeys) {
t.Errorf("keys %v", objectKeys(item))
}
}
if len(page.Items[0]["relations"].(map[string]any)) != 2 || page.Items[1]["relations"].(map[string]any)["venue"].(map[string]any)["missing"] != true || len(page.Items[2]["relations"].(map[string]any)) != 0 {
t.Errorf("relations %s", rec.Body.String())
}
})
t.Run("A type without a relation field returns empty relations and makes no target call", func(t *testing.T) {
env := newRelationEnv(t, false, false)
before := env.entries.getCalls
rec := env.member(t, http.MethodGet, "/v1/content-type/venue/entry/3", "")
body := decodeContentObject(t, rec)
if !reflect.DeepEqual(body["relations"], map[string]any{}) || env.entries.getCalls-before != 1 {
t.Errorf("body %s calls %d", rec.Body.String(), env.entries.getCalls-before)
}
})
t.Run("Many entries pointing at one target fetch it once", func(t *testing.T) {
env := newRelationEnv(t, false, false)
for id := uint32(200); id < 300; id++ {
env.seedData(t, "event", id, map[string]any{"title": "Event", "venue": float64(3)})
}
before := env.entries.getCalls
rec := env.member(t, http.MethodGet, "/v1/content-type/event/entry?size=100", "")
var page struct {
Items []map[string]any `json:"items"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &page); err != nil || len(page.Items) != 100 {
t.Fatalf("status %d items %d", rec.Code, len(page.Items))
}
if calls := env.entries.getCalls - before; calls > 1 {
t.Errorf("get calls %d", calls)
}
})
t.Run("Searching the entries of a type", func(t *testing.T) {
for _, example := range []struct {
q string
total int
}{{"rue", 3}, {"RUE%20VERTE", 2}, {"yard", 1}, {"nothing", 0}, {"", 3}, {"%20%20", 3}} {
t.Run(example.q, func(t *testing.T) {
env := newRelationEnv(t, false, false)
env.seed(t, "venue", 5, "title", "Rue du Port studio")
rec := env.member(t, http.MethodGet, "/v1/content-type/venue/entry?q="+example.q, "")
var page struct {
Total int `json:"total"`
}
json.Unmarshal(rec.Body.Bytes(), &page)
if rec.Code != http.StatusOK || page.Total != example.total {
t.Errorf("total %d: %s", page.Total, rec.Body.String())
}
})
}
})
t.Run("Search is paginated after filtering", func(t *testing.T) {
env := newRelationEnv(t, false, false)
for id := uint32(20); id < 50; id++ {
env.seed(t, "venue", id, "title", "Rue "+strconv.Itoa(int(id)))
}
rec := env.member(t, http.MethodGet, "/v1/content-type/venue/entry?q=rue&page=2&size=5&sort=id:asc", "")
var page struct {
Items []map[string]any `json:"items"`
Total int `json:"total"`
Page int `json:"page"`
Size int `json:"size"`
}
json.Unmarshal(rec.Body.Bytes(), &page)
if page.Total != 32 || page.Page != 2 || page.Size != 5 || len(page.Items) != 5 || page.Items[0]["id"] != float64(20+3) {
t.Errorf("page %+v", page)
}
})
t.Run("Deleting an entry that is referenced", func(t *testing.T) {
env := newRelationEnv(t, false, false)
env.seedData(t, "event", 5, map[string]any{"title": "E", "venue": float64(3)})
before := env.entries.entries[5]
expectStatusAndBody(t, env.member(t, http.MethodDelete, "/v1/content-type/venue/entry/3", ""), http.StatusNoContent, "")
if !reflect.DeepEqual(env.entries.entries[5], before) {
t.Error("the referencing entry changed")
}
})
t.Run("The target type, entries and API are unchanged", func(t *testing.T) {
env := newRelationEnv(t, false, false)
typeRec := env.member(t, http.MethodGet, "/v1/content-type/venue", "")
entryRec := env.member(t, http.MethodGet, "/v1/content-type/venue/entry/3", "")
if strings.Contains(typeRec.Body.String(), "Events") || len(decodeContentObject(t, typeRec)["fields"].([]any)) != 2 || strings.Contains(entryRec.Body.String(), "Events") {
t.Errorf("inverse leaked: %s %s", typeRec.Body.String(), entryRec.Body.String())
}
})
}
+253
View File
@@ -0,0 +1,253 @@
package test
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/infrastructure/useCases"
"errors"
"testing"
"time"
)
func relationSchema(t *testing.T, kind contenttype.RelationKind, required bool) []contenttype.Field {
t.Helper()
fields, err := contenttype.ValidateFields([]contenttype.Field{
{Key: "title", Label: "Title", Type: contenttype.TypeText, Required: true},
{Key: "link", Label: "Link", Type: contenttype.TypeRelation, Required: required, Relation: &contenttype.Relation{ContentType: "venue", Kind: kind}},
})
if err != nil {
t.Fatalf("schema: %v", err)
}
return fields
}
func TestRelationFieldDomain(t *testing.T) {
t.Run("contenttype.ValidateFields refuses what a relation field can't have", func(t *testing.T) {
valid := contenttype.Relation{ContentType: "venue", Kind: contenttype.RelationOneToMany}
refused := map[string]contenttype.Field{
"no relation": {},
"no target": {Relation: &contenttype.Relation{Kind: contenttype.RelationOneToMany}},
"bad kind": {Relation: &contenttype.Relation{ContentType: "venue", Kind: "many_to_one"}},
"unique": {Unique: true, Relation: &valid},
"default": {Default: float64(3), Relation: &valid},
"min": {Min: float64(1), Relation: &valid},
"max": {Max: float64(5), Relation: &valid},
"options": {Options: []string{"a"}, Relation: &valid},
}
for name, base := range refused {
base.Key, base.Label, base.Type = "link", "Link", contenttype.TypeRelation
if _, err := contenttype.ValidateFields([]contenttype.Field{base}); !errors.Is(err, contenttype.ErrInvalidField) {
t.Errorf("%s: %v", name, err)
}
}
onText := contenttype.Field{Key: "link", Label: "Link", Type: contenttype.TypeText, Relation: &valid}
if _, err := contenttype.ValidateFields([]contenttype.Field{onText}); !errors.Is(err, contenttype.ErrInvalidField) {
t.Errorf("relation on text: %v", err)
}
})
t.Run("entry.Validate applies required and type to a relation field", func(t *testing.T) {
single := relationSchema(t, contenttype.RelationOneToMany, true)
expectFieldError(t, entry.Validate(single, map[string]any{"title": "A"}), "link", entry.RuleRequired)
expectFieldError(t, entry.Validate(single, map[string]any{"title": "A", "link": nil}), "link", entry.RuleRequired)
expectFieldError(t, entry.Validate(single, map[string]any{"title": "A", "link": "3"}), "link", contenttype.RuleType)
expectFieldError(t, entry.Validate(single, map[string]any{"title": "A", "link": float64(0)}), "link", contenttype.RuleType)
expectFieldError(t, entry.Validate(single, map[string]any{"title": "A", "link": []any{float64(3)}}), "link", contenttype.RuleType)
if err := entry.Validate(single, map[string]any{"title": "A", "link": float64(3)}); err != nil {
t.Errorf("valid single: %v", err)
}
many := relationSchema(t, contenttype.RelationManyToMany, true)
expectFieldError(t, entry.Validate(many, map[string]any{"title": "A", "link": []any{}}), "link", entry.RuleRequired)
expectFieldError(t, entry.Validate(many, map[string]any{"title": "A", "link": float64(3)}), "link", contenttype.RuleType)
expectFieldError(t, entry.Validate(many, map[string]any{"title": "A", "link": []any{float64(3), float64(3)}}), "link", contenttype.RuleType)
if err := entry.Validate(many, map[string]any{"title": "A", "link": []any{float64(4), float64(3)}}); err != nil {
t.Errorf("valid many: %v", err)
}
if err := entry.Validate(relationSchema(t, contenttype.RelationManyToMany, false), map[string]any{"title": "A", "link": []any{}}); err != nil {
t.Errorf("empty optional many: %v", err)
}
})
}
type relationUseCaseEnv struct {
types *mockContentTypeRepo
entries *mockEntryRepo
now func() time.Time
}
func newRelationUseCaseEnv(t *testing.T, kind contenttype.RelationKind) *relationUseCaseEnv {
t.Helper()
env := &relationUseCaseEnv{types: newMockContentTypeRepo(), entries: newMockEntryRepo(), now: func() time.Time { return time.Date(2026, 10, 5, 9, 0, 0, 0, time.UTC) }}
venue, _ := env.types.Create(contenttype.ContentType{Key: "venue", Name: "Venue", Fields: []contenttype.Field{{Key: "title", Type: contenttype.TypeText}}})
env.entries.entries[3] = entry.Entry{ID: 3, ContentTypeID: venue.ID, Data: map[string]any{"title": "Hall"}}
env.types.Create(contenttype.ContentType{Key: "event", Name: "Event", Fields: relationSchema(t, kind, false)})
return env
}
func TestRelationFieldUseCases(t *testing.T) {
t.Run("CreateEntry and UpdateEntry refuse a missing target and perform no write", func(t *testing.T) {
env := newRelationUseCaseEnv(t, contenttype.RelationOneToMany)
images := newMockImageRepo()
create := useCases.NewCreateEntryUseCase(env.types, env.entries, images, env.now)
update := useCases.NewUpdateEntryUseCase(env.types, env.entries, images, env.now)
_, err := create.Create(useCases.CreateEntryCommand{ContentTypeKey: "event", Data: map[string]any{"title": "A", "link": float64(999)}, UserID: 1})
expectFieldError(t, err, "link", contenttype.RuleType)
stored, err := create.Create(useCases.CreateEntryCommand{ContentTypeKey: "event", Data: map[string]any{"title": "A", "link": float64(3)}, UserID: 1})
if err != nil || env.entries.createCalls != 1 {
t.Fatalf("create: %v", err)
}
_, err = update.Update(useCases.UpdateEntryCommand{ContentTypeKey: "event", ID: stored.ID, Data: map[string]any{"title": "A", "link": float64(999)}, UserID: 1})
expectFieldError(t, err, "link", contenttype.RuleType)
if env.entries.updateCalls != 0 || env.entries.createCalls != 1 {
t.Errorf("writes: %d %d", env.entries.updateCalls, env.entries.createCalls)
}
})
t.Run("UpdateContentType returns the sentinels for a new required relation and a changed shape", func(t *testing.T) {
env := newRelationUseCaseEnv(t, contenttype.RelationOneToMany)
env.entries.entries[9] = entry.Entry{ID: 9, ContentTypeID: 2, Data: map[string]any{"title": "A"}}
update := useCases.NewUpdateContentTypeUseCase(env.types, env.entries, env.now)
required := relationSchema(t, contenttype.RelationOneToMany, true)
changed := relationSchema(t, contenttype.RelationManyToMany, false)
_, err := update.Update(useCases.UpdateContentTypeCommand{Key: "event", Name: "Event", Fields: required})
if !errors.Is(err, contenttype.ErrSchemaIncompatible) {
t.Errorf("required: %v", err)
}
_, err = update.Update(useCases.UpdateContentTypeCommand{Key: "event", Name: "Event", Fields: changed})
if !errors.Is(err, contenttype.ErrInvalidField) {
t.Errorf("shape: %v", err)
}
})
t.Run("DeleteContentType returns ErrReferenced for a target type", func(t *testing.T) {
env := newRelationUseCaseEnv(t, contenttype.RelationOneToMany)
remove := useCases.NewDeleteContentTypeUseCase(env.types, env.entries)
if err := remove.Delete("venue"); !errors.Is(err, contenttype.ErrReferenced) {
t.Errorf("venue: %v", err)
}
if err := remove.Delete("event"); err != nil {
t.Errorf("event: %v", err)
}
})
t.Run("A relation lookup failure surfaces as an error", func(t *testing.T) {
env := newRelationUseCaseEnv(t, contenttype.RelationOneToMany)
env.entries.failGetOn = 1
get := useCases.NewGetEntryUseCase(env.types, env.entries, newMockImageRepo())
env.entries.entries[9] = entry.Entry{ID: 9, ContentTypeID: 2, Data: map[string]any{"title": "A", "link": float64(3)}}
env.entries.failGetOn = 2
if _, err := get.Get("event", 9); !errors.Is(err, errRepositoryFailure) {
t.Errorf("err %v", err)
}
})
}
type relationCountingTypeRepo struct {
*mockContentTypeRepo
getByKeyCalls int
failOnCall int
}
func (r *relationCountingTypeRepo) GetByKey(key string) (contenttype.ContentType, error) {
r.getByKeyCalls++
if r.failOnCall == r.getByKeyCalls {
return contenttype.ContentType{}, errRepositoryFailure
}
return r.mockContentTypeRepo.GetByKey(key)
}
func TestRelationFieldUseCaseEdges(t *testing.T) {
t.Run("types without relation fields never consult the target repositories", func(t *testing.T) {
types := &relationCountingTypeRepo{mockContentTypeRepo: newMockContentTypeRepo()}
entries := newMockEntryRepo()
types.Create(contenttype.ContentType{Key: "plain", Name: "Plain", Fields: []contenttype.Field{{Key: "title", Type: contenttype.TypeText}}})
now := func() time.Time { return time.Date(2026, 10, 5, 9, 0, 0, 0, time.UTC) }
images := newMockImageRepo()
created, err := useCases.NewCreateEntryUseCase(types, entries, images, now).Create(useCases.CreateEntryCommand{ContentTypeKey: "plain", Data: map[string]any{"title": "A"}, UserID: 1})
if err != nil || len(created.Relations) != 0 {
t.Fatalf("create: %v %v", err, created.Relations)
}
if types.getByKeyCalls != 1 || entries.getCalls != 0 {
t.Errorf("create calls: types %d entries %d", types.getByKeyCalls, entries.getCalls)
}
types.getByKeyCalls = 0
entries.getCalls = 0
if _, err := useCases.NewGetEntryUseCase(types, entries, images).Get("plain", created.ID); err != nil {
t.Fatalf("get: %v", err)
}
if types.getByKeyCalls != 1 || entries.getCalls != 1 {
t.Errorf("get calls: types %d entries %d", types.getByKeyCalls, entries.getCalls)
}
types.getByKeyCalls = 0
entries.getCalls = 0
updated, err := useCases.NewUpdateEntryUseCase(types, entries, images, now).Update(useCases.UpdateEntryCommand{ContentTypeKey: "plain", ID: created.ID, Data: map[string]any{"title": "B"}, UserID: 1})
if err != nil || len(updated.Relations) != 0 {
t.Fatalf("update: %v", err)
}
if types.getByKeyCalls != 1 || entries.getCalls != 1 {
t.Errorf("update calls: types %d entries %d", types.getByKeyCalls, entries.getCalls)
}
types.getByKeyCalls = 0
entries.getCalls = 0
if _, err := useCases.NewListEntriesUseCase(types, entries, images).ListPage(useCases.ListEntriesCommand{ContentTypeKey: "plain", Page: 1, Size: 10, Sort: entry.DefaultSort()}); err != nil {
t.Fatalf("list: %v", err)
}
if types.getByKeyCalls != 1 || entries.getCalls != 0 {
t.Errorf("list calls: types %d entries %d", types.getByKeyCalls, entries.getCalls)
}
})
t.Run("UpdateContentType surfaces a repository failure while checking relation targets", func(t *testing.T) {
env := newRelationUseCaseEnv(t, contenttype.RelationOneToMany)
types := &relationCountingTypeRepo{mockContentTypeRepo: env.types, failOnCall: 2}
update := useCases.NewUpdateContentTypeUseCase(types, env.entries, env.now)
_, err := update.Update(useCases.UpdateContentTypeCommand{Key: "event", Name: "Event", Fields: relationSchema(t, contenttype.RelationOneToMany, false)})
if !errors.Is(err, errRepositoryFailure) {
t.Errorf("err %v", err)
}
})
t.Run("UpdateContentType allows a field type change while no entry is stored", func(t *testing.T) {
env := newRelationUseCaseEnv(t, contenttype.RelationOneToMany)
update := useCases.NewUpdateContentTypeUseCase(env.types, env.entries, env.now)
fields := []contenttype.Field{{Key: "title", Label: "Title", Type: contenttype.TypeNumber}}
if _, err := update.Update(useCases.UpdateContentTypeCommand{Key: "event", Name: "Event", Fields: fields}); err != nil {
t.Errorf("err %v", err)
}
})
t.Run("DeleteContentType ignores a self reference", func(t *testing.T) {
env := newRelationUseCaseEnv(t, contenttype.RelationOneToMany)
env.types.Create(contenttype.ContentType{Key: "node", Name: "Node", Fields: []contenttype.Field{{Key: "parent", Type: contenttype.TypeRelation, Relation: &contenttype.Relation{ContentType: "node", Kind: contenttype.RelationOneToMany}}}})
if err := useCases.NewDeleteContentTypeUseCase(env.types, env.entries).Delete("node"); err != nil {
t.Errorf("err %v", err)
}
})
}
func TestRelationFieldIDLimit(t *testing.T) {
many := relationSchema(t, contenttype.RelationManyToMany, false)
build := func(count int) map[string]any {
ids := make([]any, 0, count)
for i := 1; i <= count; i++ {
ids = append(ids, float64(i))
}
return map[string]any{"title": "A", "link": ids}
}
if err := entry.Validate(many, build(contenttype.MaxRelationIDs)); err != nil {
t.Errorf("at limit: %v", err)
}
expectFieldError(t, entry.Validate(many, build(contenttype.MaxRelationIDs+1)), "link", contenttype.RuleType)
}
@@ -0,0 +1,48 @@
package test
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/infrastructure/useCases"
"testing"
"time"
)
func TestRelationFieldListQueryClampsPaging(t *testing.T) {
env := newRelationUseCaseEnv(t, contenttype.RelationOneToMany)
env.entries.entries[4] = entry.Entry{ID: 4, ContentTypeID: 1, Data: map[string]any{"title": "Arena"}}
list := useCases.NewListEntriesUseCase(env.types, env.entries, newMockImageRepo())
cases := []struct {
name string
page int
size int
items int
}{
{"page below one acts as page one", 0, 10, 2},
{"negative page acts as page one", -3, 1, 1},
{"negative size yields an empty page", 1, -1, 0},
}
for _, example := range cases {
t.Run(example.name, func(t *testing.T) {
page, err := list.ListPage(useCases.ListEntriesCommand{ContentTypeKey: "venue", Page: example.page, Size: example.size, Sort: entry.DefaultSort(), Query: "a"})
if err != nil {
t.Fatalf("err %v", err)
}
if len(page.Items) != example.items || page.Total != 2 {
t.Errorf("items %d total %d", len(page.Items), page.Total)
}
})
}
}
func TestRelationFieldTargetWithoutFieldsIsMissing(t *testing.T) {
env := newRelationUseCaseEnv(t, contenttype.RelationOneToMany)
venue, _ := env.types.GetByKey("venue")
venue.Fields = nil
env.types.types[venue.ID] = venue
create := useCases.NewCreateEntryUseCase(env.types, env.entries, newMockImageRepo(), func() time.Time { return time.Date(2026, 10, 5, 9, 0, 0, 0, time.UTC) })
_, err := create.Create(useCases.CreateEntryCommand{ContentTypeKey: "event", Data: map[string]any{"title": "A", "link": float64(3)}, UserID: 1})
expectFieldError(t, err, "link", contenttype.RuleType)
}
+4
View File
@@ -29,6 +29,7 @@ const props = defineProps<{
field: BuilderField
errors: FieldErrors
compact: boolean
ownerName?: string
}>()
const uid = () => props.field.uid
@@ -40,12 +41,15 @@ const uid = () => props.field.uid
:errors="errors"
:disabled="saving"
:compact="compact"
:owner-name="ownerName"
:focus-token="focusToken"
@label="actions.setLabel(uid(), $event)"
@key="actions.setFieldKey(uid(), $event)"
@unlock="actions.unlockFieldKey(uid())"
@reset="actions.resetFieldKey(uid())"
@type="actions.setFieldType(uid(), $event)"
@relation-type="actions.patchField(uid(), { relationType: $event }, 'relation')"
@relation-kind="actions.patchField(uid(), { relationKind: $event })"
@required="actions.patchField(uid(), { required: $event })"
@unique="actions.patchField(uid(), { unique: $event })"
@limit="(which, value) => actions.setLimit(uid(), which, value)"
+15
View File
@@ -11,6 +11,7 @@ const props = defineProps<{
name: string
keyValue: string
total: number
referrer: string
pending: boolean
offline: boolean
}>()
@@ -43,6 +44,20 @@ const notice = computed(() => {
),
}
}
if (props.stage === 'referenced') {
return {
title: t("You can't delete {0} yet", [props.name]),
description: props.referrer
? t('{0} has a field that points to {1}. Remove that field first.', [
props.referrer,
props.name,
])
: t(
'Another content type has a field that points to {0}. Remove that field first.',
[props.name],
),
}
}
if (props.stage === 'failed') {
return {
title: t("Couldn't delete the content type"),
+27 -1
View File
@@ -11,7 +11,9 @@ import {
thumbnailColumn,
} from '@/lib/entryCells'
import { t } from '@/i18n'
import { fieldTypeSpec } from '@/lib/fieldTypes'
import { mediaOf } from '@/lib/mediaField'
import { summariesOf } from '@/lib/relationField'
import { entryPath } from '@/lib/routePaths'
import { computed } from 'vue'
@@ -26,11 +28,21 @@ const props = defineProps<{
const shown = computed(() => cardFields(props.fields))
const lead = computed(() => thumbnailColumn(props.columns))
const relationColumns = computed(() =>
props.columns.filter(
(field) => field !== shown.value.first && fieldTypeSpec(field.type).cell === 'relation',
),
)
function textOf(field: BuiltinField | undefined, entry: ContentEntry) {
return field
? plainCellText(
describeCell(field, entry.data[field.key], mediaOf(entry, field.key) ?? undefined),
describeCell(
field,
entry.data[field.key],
mediaOf(entry, field.key) ?? undefined,
summariesOf(entry, field.key),
),
)
: ''
}
@@ -80,6 +92,20 @@ function nameOf(entry: ContentEntry) {
<span class="truncate text-md/5.25 font-medium text-highlighted">{{
titleOf(entry)
}}</span>
<span
v-for="field in relationColumns"
:key="field.key"
data-testid="entry-card-relation"
class="flex flex-wrap items-center gap-1.5"
>
<span class="text-xs text-muted">{{ field.label }}</span>
<FieldCell
:field="field"
:value="entry.data[field.key]"
:relations="summariesOf(entry, field.key)"
compact
/>
</span>
<span class="flex items-center gap-2 text-xs text-muted">
<template v-if="shown.second && !secondIsChoice">
<span class="shrink-0">{{ textOf(shown.second, entry) }}</span>
+2
View File
@@ -111,6 +111,8 @@ function backToList() {
:fields="page.fields.value"
:values="page.form.values.value"
:images="page.form.images.value"
:relations="page.form.relations.value"
:type-name="page.typeName.value"
:issues="page.form.issues.value"
:first-issue="page.form.firstIssue.value"
:focus-token="page.focusToken.value"
+27 -1
View File
@@ -4,10 +4,12 @@ import BuilderBadge from '@/components/BuilderBadge.vue'
import DirectoryField from '@/components/DirectoryField.vue'
import EntryControl from '@/components/EntryControl.vue'
import MediaFieldControl from '@/components/MediaFieldControl.vue'
import RelationField from '@/components/RelationField.vue'
import type { BuiltinField } from '@/lib/contentTypes'
import type { FieldIssue } from '@/lib/entryForm'
import { fieldTypeSpec } from '@/lib/fieldTypes'
import { isMediaId, type MediaSummary } from '@/lib/mediaField'
import { holdsManyRelations, type RelationSummary } from '@/lib/relationField'
const props = defineProps<{
field: BuiltinField
@@ -16,14 +18,24 @@ const props = defineProps<{
isDefault: boolean
disabled: boolean
image?: MediaSummary | null
relations?: RelationSummary[]
typeName: string
}>()
const emit = defineEmits<{ update: [key: string, value: unknown, image?: MediaSummary | null] }>()
const emit = defineEmits<{
update: [
key: string,
value: unknown,
image?: MediaSummary | null,
relations?: RelationSummary[],
]
}>()
const editor = computed(() => fieldTypeSpec(props.field.type).editor)
const counter = computed(() => editor.value.counter(props.field, props.value))
const help = computed(() => editor.value.help(props.field))
const isMedia = computed(() => editor.value.control === 'media')
const isRelation = computed(() => editor.value.control === 'relation')
const mediaId = computed(() => (isMediaId(props.value) ? props.value : null))
</script>
@@ -40,6 +52,20 @@ const mediaId = computed(() => (isMediaId(props.value) ? props.value : null))
:error="issue?.message"
@change="(id, picked) => emit('update', field.key, id, picked)"
/>
<RelationField
v-else-if="isRelation"
:label="field.label"
:name="field.key"
:required="field.required"
:many="holdsManyRelations(field)"
:target="field.relation?.content_type ?? ''"
:type-name="typeName"
:value="value"
:summaries="relations"
:disabled="disabled"
:error="issue?.message"
@change="(next, summaries) => emit('update', field.key, next, undefined, summaries)"
/>
<DirectoryField
v-else
:label="field.label"
+14 -2
View File
@@ -6,6 +6,7 @@ import EntryField from '@/components/EntryField.vue'
import type { BuiltinField } from '@/lib/contentTypes'
import type { EntryIssues, EntryValues } from '@/lib/entryForm'
import type { MediaMap, MediaSummary } from '@/lib/mediaField'
import type { RelationSummaries, RelationSummary } from '@/lib/relationField'
import { groupFields } from '@/lib/entryLayout'
const FOCUSABLE =
@@ -15,6 +16,8 @@ const props = defineProps<{
fields: BuiltinField[]
values: EntryValues
images: MediaMap
relations: RelationSummaries
typeName: string
issues: EntryIssues
firstIssue: string | null
focusToken: number
@@ -28,7 +31,12 @@ const props = defineProps<{
}>()
const emit = defineEmits<{
update: [key: string, value: unknown, image?: MediaSummary | null]
update: [
key: string,
value: unknown,
image?: MediaSummary | null,
relations?: RelationSummary[],
]
submit: []
}>()
@@ -73,10 +81,14 @@ watch(() => props.focusToken, focusFirstIssue)
:field="field"
:value="values[field.key]"
:image="images[field.key] ?? null"
:relations="relations[field.key] ?? []"
:type-name="typeName"
:issue="issues[field.key]"
:is-default="isDefault(field)"
:disabled="locked"
@update="(key, value, image) => emit('update', key, value, image)"
@update="
(key, value, image, summaries) => emit('update', key, value, image, summaries)
"
/>
</div>
+7 -2
View File
@@ -20,12 +20,17 @@ const props = defineProps<{
defineEmits<{ retry: []; reload: [] }>()
const NAMED_CONTROLS = ['media', 'relation']
const uniqueField = computed(() =>
props.fields.find((field) => props.issues[field.key]?.rule === 'unique'),
props.fields.find(
(field) =>
props.issues[field.key]?.rule === 'unique' && fieldTypeSpec(field.type).supportsUnique,
),
)
const changedLine = computed(() => {
const changed = props.fields.find((field) => field.key === props.schemaField)
return changed && fieldTypeSpec(changed.type).editor.control === 'media'
return changed && NAMED_CONTROLS.includes(fieldTypeSpec(changed.type).editor.control)
? mediaChangedLine(changed.label)
: schemaChangedLine(props.schemaField)
})
+9 -1
View File
@@ -9,11 +9,13 @@ import { EMPTY_TEXT, formatEntryDate } from '@/lib/entryCells'
import { ENTRY_SORT_FIELDS, sortParts } from '@/lib/entryListQuery'
import { fieldTypeSpec } from '@/lib/fieldTypes'
import { mediaOf } from '@/lib/mediaField'
import { summariesOf } from '@/lib/relationField'
import { entryPath } from '@/lib/routePaths'
const ID_WIDTH = 'w-16.5'
const NARROW_WIDTH = 'w-23'
const FIELD_WIDTH = 'w-33'
const WIDE_WIDTH = 'w-50'
const CREATED_WIDTH = 'w-30.5'
const UPDATED_WIDTH = 'w-40.5'
const UPDATED_BY_WIDTH = 'w-37'
@@ -37,7 +39,11 @@ function widthOf(field: BuiltinField, index: number) {
if (index === 0) {
return ''
}
return fieldTypeSpec(field.type).narrowColumn ? NARROW_WIDTH : FIELD_WIDTH
const spec = fieldTypeSpec(field.type)
if (spec.wideColumn) {
return WIDE_WIDTH
}
return spec.narrowColumn ? NARROW_WIDTH : FIELD_WIDTH
}
function column(id: string, header: string, width: string, edge = 'px-1.5') {
@@ -152,6 +158,7 @@ watchPostEffect(() => {
:field="field"
:value="row.original.data[field.key]"
:image="mediaOf(row.original, field.key)"
:relations="summariesOf(row.original, field.key)"
class="min-w-0"
/>
</RouterLink>
@@ -160,6 +167,7 @@ watchPostEffect(() => {
:field="field"
:value="row.original.data[field.key]"
:image="mediaOf(row.original, field.key)"
:relations="summariesOf(row.original, field.key)"
/>
</template>
+21 -1
View File
@@ -2,18 +2,23 @@
import { t } from '@/i18n'
import { computed } from 'vue'
import RelationChip from '@/components/RelationChip.vue'
import type { BuiltinField } from '@/lib/contentTypes'
import { EMPTY_TEXT, describeCell, isEmptyCell } from '@/lib/entryCells'
import { isMissingImage, type MediaSummary } from '@/lib/mediaField'
import type { RelationSummary } from '@/lib/relationField'
const props = defineProps<{
field: BuiltinField
value: unknown
image?: MediaSummary | null
relations?: RelationSummary[]
compact?: boolean
}>()
const cell = computed(() => describeCell(props.field, props.value, props.image ?? undefined))
const cell = computed(() =>
describeCell(props.field, props.value, props.image ?? undefined, props.relations),
)
const shownImage = computed(() => {
const image = cell.value.image
return image && !isMissingImage(image) ? image : null
@@ -61,6 +66,21 @@ const TIP_UI = {
<UIcon name="i-lucide-unlink" :class="compact ? 'size-3' : 'size-3.5'" />
</span>
</UTooltip>
<span
v-else-if="cell.kind === 'relation'"
data-testid="relation-cell"
:title="cell.text"
class="flex min-w-0 items-center gap-1"
:class="compact ? 'flex-wrap' : 'overflow-hidden'"
>
<RelationChip
v-for="chip in cell.chips"
:key="chip.id"
:label="chip.label"
:missing="chip.missing"
/>
<span v-if="cell.more" class="text-xs text-muted">+{{ cell.more }}</span>
</span>
<span v-else-if="cell.kind === 'boolean'" class="flex items-center gap-1.5">
<UIcon
:name="cell.yes ? 'i-lucide-check' : 'i-lucide-minus'"
+20
View File
@@ -6,6 +6,7 @@ import AppSwitch from '@/components/AppSwitch.vue'
import ChoiceList from '@/components/ChoiceList.vue'
import DirectoryField from '@/components/DirectoryField.vue'
import FieldTypePicker from '@/components/FieldTypePicker.vue'
import RelationPicker from '@/components/RelationPicker.vue'
import SlugField from '@/components/SlugField.vue'
import { fieldTypeSpec } from '@/lib/fieldTypes'
import {
@@ -18,6 +19,7 @@ import {
type BuilderField,
type FieldType,
} from '@/lib/schemaBuilderModel'
import type { RelationKind } from '@/lib/relationField'
import type { FieldErrors } from '@/lib/schemaBuilderValidation'
const NO_DEFAULT = 'none'
@@ -29,6 +31,7 @@ const props = defineProps<{
disabled: boolean
compact: boolean
focusToken: number
ownerName?: string
}>()
const emit = defineEmits<{
@@ -37,6 +40,8 @@ const emit = defineEmits<{
unlock: []
reset: []
type: [type: FieldType]
relationType: [key: string]
relationKind: [kind: RelationKind]
required: [value: boolean]
unique: [value: boolean]
limit: [which: 'min' | 'max', value: string]
@@ -58,6 +63,7 @@ const showUnique = computed(() => canUnique.value || spec.value.showsUnsupported
const showRuleGrid = computed(
() => hasLimits.value || spec.value.supportsDefault || spec.value.showsUnsupportedOptions,
)
const holdsRelation = computed(() => spec.value.holdsRelation)
const hint = computed(() => spec.value.builderHint?.() ?? '')
const keyMode = computed(() => keyDisplayMode(props.field.keyMode, props.field.key))
const gridClass = computed(() => (props.compact ? 'grid-cols-1' : 'md:grid-cols-2'))
@@ -193,6 +199,20 @@ watch(
@update:model-value="emit('type', $event)"
/>
<RelationPicker
v-if="holdsRelation"
:label="field.label"
:owner-name="ownerName ?? ''"
:type-key="field.relationType"
:kind="field.relationKind"
:locked="field.saved"
:disabled="disabled"
:compact="compact"
:error="errors.relation"
@type="emit('relationType', $event)"
@kind="emit('relationKind', $event)"
/>
<div class="flex min-w-0 flex-col border-t border-default">
<AppSwitch
:model-value="field.required"
+29
View File
@@ -0,0 +1,29 @@
<script setup lang="ts">
withDefaults(defineProps<{ label: string; missing?: boolean; tall?: boolean }>(), {
missing: false,
tall: false,
})
</script>
<template>
<UBadge
color="neutral"
variant="soft"
:label="label"
data-testid="relation-chip"
:data-missing="missing ? 'true' : undefined"
class="max-w-full ring-0"
:class="
missing
? 'border border-dashed border-accented bg-transparent text-toned'
: 'bg-(--rc-sand) text-(--rc-on-sand)'
"
:ui="{
base: [
tall ? 'h-5.5 px-2' : 'h-5 px-1.5',
'rounded-none py-0 text-xs font-medium whitespace-nowrap',
],
label: 'truncate',
}"
/>
</template>
+461
View File
@@ -0,0 +1,461 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { computed, nextTick, onMounted, ref, useId, watch } from 'vue'
import DirectoryField from '@/components/DirectoryField.vue'
import { useRelationSearch } from '@/composables/useRelationSearch'
import { relationLabel } from '@/lib/entryCells'
import {
RELATION_MAX,
isMissingRelation,
relationIdsOf,
type RelationSummary,
} from '@/lib/relationField'
import { relationRowOf } from '@/lib/relationRows'
import { useContentTypesStore } from '@/stores/contentTypes'
interface ChipItem {
label: string
value: number
missing: boolean
summary: RelationSummary
}
interface RowItem {
label: string
description: string
value: number
summary: RelationSummary
}
interface HighlightPayload {
ref?: HTMLElement
}
const SKELETON_ROWS = 3
const LISTBOX = '[role="listbox"]'
const OWNER_ATTRIBUTE = 'data-relation-owner'
const VOWEL = /^[aeiou]/
const props = withDefaults(
defineProps<{
label: string
name?: string
required?: boolean
many?: boolean
target: string
typeName: string
value: unknown
summaries?: RelationSummary[]
disabled?: boolean
error?: string
}>(),
{
name: undefined,
required: false,
many: false,
summaries: () => [],
disabled: false,
error: '',
},
)
const emit = defineEmits<{
change: [value: number | number[] | null, summaries: RelationSummary[]]
}>()
const id = useId()
const labelId = `${id}-label`
const helpId = `${id}-help`
const errorId = `${id}-error`
const store = useContentTypesStore()
const search = useRelationSearch(() => props.target)
const open = ref(false)
const searchTerm = ref('')
const announcement = ref('')
const activeId = ref<string | undefined>(undefined)
const listboxId = ref<string | undefined>(undefined)
const ids = computed(() => relationIdsOf(props.value))
const chips = computed<ChipItem[]>(() =>
ids.value.map((chipId) => {
const summary = props.summaries.find((candidate) => candidate.id === chipId) ?? {
id: chipId,
missing: true as const,
}
return {
label: relationLabel(summary),
value: chipId,
missing: isMissingRelation(summary),
summary,
}
}),
)
const targetType = computed(() => store.items.find((type) => type.key === props.target))
const targetName = computed(() => targetType.value?.name ?? props.target)
const atCap = computed(() => props.many && ids.value.length >= RELATION_MAX)
const rows = computed<RowItem[]>(() =>
search.entries.value
.map((entry) => relationRowOf(entry, props.target, targetType.value?.fields ?? []))
.filter((row) => !ids.value.includes(row.id))
.map((row) => ({
label: row.title,
description: row.detail,
value: row.id,
summary: row.summary,
})),
)
const menuItems = computed(() => (atCap.value || search.showSkeleton.value ? [] : rows.value))
const hasMissing = computed(() => chips.value.some((chip) => chip.missing))
const ownerWord = computed(() => props.typeName.replace(/s$/i, '').toLowerCase())
const help = computed(() => {
if (hasMissing.value) {
return props.required
? t('{0} is required. Choose another to save.', [props.label])
: t('You can still save. The entry keeps the link until you change it.')
}
if (!props.many) {
return ''
}
const plural = props.label.toLowerCase()
return VOWEL.test(ownerWord.value)
? t('An {0} can have many {1}.', [ownerWord.value, plural])
: t('A {0} can have many {1}.', [ownerWord.value, plural])
})
const describedBy = computed(() => (props.error ? `${errorId} ${helpId}` : helpId))
const emptyKind = computed(() => {
if (atCap.value) {
return 'cap'
}
if (search.showSkeleton.value) {
return 'loading'
}
const status = search.status.value
if (status === 'limited' || status === 'failed') {
return status
}
if (status !== 'ready') {
return 'none'
}
if (search.total.value > 0) {
return 'chosen'
}
return search.query.value === '' ? 'empty' : 'noMatch'
})
const baseUi = computed(() =>
props.error
? 'border-error shadow-[inset_0_0_0_1px_var(--ui-error)] has-focus-visible:border-error'
: 'border-accented has-focus-visible:border-primary has-focus-visible:shadow-[inset_0_0_0_1px_var(--ui-primary)]',
)
const menuUi = computed(() => ({
base: `min-h-8 gap-1.5 rounded-none border bg-default px-2 py-1 text-sm ring-0 outline-0 has-focus-visible:ring-0 has-focus-visible:outline-0 max-md:min-h-11 max-md:text-lg ${baseUi.value} ${props.many ? '' : 'pe-8'}`,
tagsItem:
'h-6 gap-1.5 rounded-none bg-(--rc-sand) py-0 ps-2 pe-1 text-sm font-medium text-(--rc-on-sand) ring-0 has-data-[missing=true]:border has-data-[missing=true]:border-dashed has-data-[missing=true]:border-accented has-data-[missing=true]:bg-transparent has-data-[missing=true]:font-normal has-data-[missing=true]:text-toned max-md:h-8',
tagsItemText: 'truncate',
tagsItemDelete:
'relative rounded-none text-inherit hover:bg-transparent hover:text-inherit max-md:before:absolute max-md:before:-inset-1.5',
tagsInput: 'min-w-20 flex-1 placeholder:text-muted',
trailing: 'pe-2.5',
trailingIcon: 'size-3.5 text-muted',
content: 'rounded-none border border-default p-1 shadow-(--shadow-popover) ring-0',
empty: 'p-2 text-left text-sm text-muted',
group: 'p-0',
item: 'min-h-10 flex-col justify-center gap-0 rounded-none px-2 py-1 before:inset-0 before:rounded-none data-highlighted:not-data-disabled:before:bg-elevated max-md:min-h-12',
itemLabel: 'font-medium text-highlighted',
itemDescription: 'text-xs/5 text-muted',
}))
function removeName(element: HTMLElement, binding: { value: string }) {
const button = element.closest('button')
button?.removeAttribute('aria-labelledby')
button?.setAttribute('aria-label', binding.value)
}
const vRemoveName = { mounted: removeName, updated: removeName }
function removeLabel(item: ChipItem) {
return t('Remove {0} from {1}', [item.label, props.label])
}
function announce(message: string) {
announcement.value = ''
nextTick(() => {
announcement.value = message
})
}
function summaryOf(chipId: number, picked: RowItem[]) {
return (
chips.value.find((chip) => chip.value === chipId)?.summary ??
picked.find((row) => row.value === chipId)?.summary
)
}
function changeSingle(picked: RowItem[]) {
const row = picked[picked.length - 1]
if (!row) {
emit('change', null, [])
announce(t('{0} cleared.', [props.label]))
return
}
emit('change', row.value, [row.summary])
announce(t('{0} set to {1}.', [props.label, row.label]))
open.value = false
}
function changeMany(next: Array<ChipItem | RowItem>, picked: RowItem[]) {
const nextIds = next.map((item) => item.value)
emit(
'change',
nextIds,
nextIds.flatMap((nextId) => summaryOf(nextId, picked) ?? []),
)
const removed = chips.value.find((chip) => !nextIds.includes(chip.value))
if (removed) {
announce(t('{0} removed from {1}.', [removed.label, props.label]))
} else if (picked[0]) {
announce(t('{0} added to {1}.', [picked[0].label, props.label]))
}
}
function onUpdate(next: Array<ChipItem | RowItem>) {
if (props.disabled) {
return
}
const picked = next.filter(
(item): item is RowItem => !ids.value.includes(item.value) && 'description' in item,
)
if (props.many) {
changeMany(next, picked)
} else {
changeSingle(picked)
}
}
function onBackspace(event: KeyboardEvent) {
const input = event.target as HTMLInputElement
const lastChip = chips.value.length - 1
if (
event.key !== 'Backspace' ||
input.getAttribute('role') !== 'combobox' ||
input.value !== '' ||
lastChip < 0 ||
props.disabled
) {
return
}
event.preventDefault()
event.stopPropagation()
onUpdate(chips.value.slice(0, lastChip))
}
function onHighlight(payload: HighlightPayload | undefined) {
activeId.value = payload?.ref?.id || undefined
}
function clearSearch() {
searchTerm.value = ''
}
async function trackListbox() {
await nextTick()
const owned = `[${OWNER_ATTRIBUTE}="${id}"]`
listboxId.value =
document.querySelector<HTMLElement>(`${owned}${LISTBOX}, ${owned} ${LISTBOX}`)?.id ||
undefined
}
function announceResults() {
const total = search.total.value
announce(total > 0 ? t('{0} results', [total]) : t('No results'))
}
watch(searchTerm, (term) => {
if (open.value) {
search.search(term)
}
})
watch(open, (isOpen) => {
if (isOpen) {
search.search(searchTerm.value)
trackListbox()
} else {
activeId.value = undefined
listboxId.value = undefined
}
})
watch(
() => search.status.value,
(status) => {
if (open.value && status === 'ready') {
announceResults()
}
},
)
onMounted(() => store.load())
</script>
<template>
<div class="min-w-0">
<DirectoryField
:label="label"
:required="required"
:name="name"
:label-id="labelId"
:error="error"
:error-id="errorId"
>
<div
role="group"
:aria-labelledby="labelId"
data-testid="relation-control"
@keydown.capture="onBackspace"
>
<UInputMenu
:model-value="chips"
v-model:open="open"
v-model:search-term="searchTerm"
multiple
ignore-filter
open-on-focus
open-on-click
by="value"
:items="menuItems"
:placeholder="t('Search to add')"
:disabled="disabled"
:color="error ? 'error' : undefined"
:trailing="!many"
trailing-icon="i-lucide-search"
:aria-controls="listboxId"
:aria-required="required ? 'true' : undefined"
:aria-activedescendant="activeId"
:aria-describedby="describedBy"
class="w-full"
:content="{ sideOffset: 6, [OWNER_ATTRIBUTE]: id }"
:ui="menuUi"
@update:model-value="onUpdate"
@highlight="onHighlight"
>
<template #tags-item-text="{ item }">
<span :data-missing="item.missing ? 'true' : undefined">{{
item.label
}}</span>
</template>
<template #tags-item-delete="{ item }">
<UIcon
v-remove-name="removeLabel(item)"
name="i-lucide-x"
class="size-3.5"
/>
</template>
<template #item="{ item }">
<span class="font-medium text-highlighted">{{ item.label }}</span>
<span v-if="item.description" class="text-xs/5 text-muted">{{
item.description
}}</span>
</template>
<template #empty>
<div data-testid="relation-empty" class="flex flex-col items-start gap-2">
<template v-if="emptyKind === 'loading'">
<span class="sr-only" role="status" aria-live="polite">{{
t('Searching…')
}}</span>
<USkeleton
v-for="row in SKELETON_ROWS"
:key="row"
data-testid="relation-skeleton"
class="h-10 w-full rounded-none bg-accented max-md:h-12"
/>
</template>
<template v-else-if="emptyKind === 'failed'">
<span class="font-medium text-error">{{
t("Couldn't load {0}", [targetName])
}}</span>
<span>{{ t('Check your connection and try again.') }}</span>
<UButton
color="neutral"
variant="outline"
icon="i-lucide-rotate-cw"
class="h-8 border border-accented bg-default px-2.5 text-xs text-highlighted ring-0 max-md:h-11"
@click="search.reload()"
>
{{ t('Try again') }}
</UButton>
</template>
<template v-else-if="emptyKind === 'limited'">
<span class="font-medium text-warning">{{
t('Too many requests')
}}</span>
<span>{{
search.limit.active.value
? t('Try again in {0}', [search.limit.formatted.value])
: t('Wait a moment before trying again.')
}}</span>
<UButton
v-if="!search.limit.active.value"
color="neutral"
variant="outline"
icon="i-lucide-rotate-cw"
class="h-8 border border-accented bg-default px-2.5 text-xs text-highlighted ring-0 max-md:h-11"
@click="search.reload()"
>
{{ t('Try again') }}
</UButton>
</template>
<span v-else-if="emptyKind === 'cap'">{{
t('You can add up to {0}.', [RELATION_MAX])
}}</span>
<span v-else-if="emptyKind === 'empty'">{{
t('No {0} yet. Add one in Content, then come back.', [targetName])
}}</span>
<template v-else-if="emptyKind === 'noMatch'">
<span>{{
t('No {0} match "{1}"', [targetName, search.query.value])
}}</span>
<UButton
color="neutral"
variant="ghost"
class="h-8 px-2 text-xs text-highlighted max-md:h-11"
@click="clearSearch"
>
{{ t('Clear search') }}
</UButton>
</template>
<span v-else-if="emptyKind === 'chosen'">{{
t('No other {0} to add.', [targetName])
}}</span>
</div>
</template>
<template #content-bottom>
<UButton
v-if="search.hasMore.value && !atCap"
color="neutral"
variant="ghost"
:loading="search.loadingMore.value"
class="h-8 w-full justify-center text-xs text-highlighted max-md:h-11"
@click="search.more()"
>
{{ t('Load more') }}
</UButton>
</template>
</UInputMenu>
</div>
<p
v-if="help"
:id="helpId"
data-testid="relation-help"
class="mt-1.5 text-xs/4.5 text-pretty text-muted"
:class="error ? 'sr-only' : ''"
>
{{ help }}
</p>
<span class="sr-only" role="status" aria-live="polite" data-testid="relation-live">{{
announcement
}}</span>
</DirectoryField>
</div>
</template>
+257
View File
@@ -0,0 +1,257 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { computed, onMounted } from 'vue'
import DirectoryField from '@/components/DirectoryField.vue'
import RelationChip from '@/components/RelationChip.vue'
import { RELATION_KINDS, isRelationKind, type RelationKind } from '@/lib/relationField'
import {
inverseNoun,
inverseSide,
kindFromInverseSide,
kindFromOwnerSide,
kindSentence,
ownerNoun,
ownerSide,
relationNames,
relationSample,
type RelationSide,
} from '@/lib/relationSentences'
import { useContentTypesStore } from '@/stores/contentTypes'
const DIAGRAMS: Record<RelationKind, readonly [number, number]> = {
one_to_one: [1, 1],
one_to_many: [3, 1],
many_to_many: [2, 2],
}
const props = defineProps<{
label: string
ownerName: string
typeKey: string
kind: RelationKind
locked: boolean
disabled: boolean
compact: boolean
error?: string
}>()
const emit = defineEmits<{ type: [key: string]; kind: [kind: RelationKind] }>()
const store = useContentTypesStore()
const typeItems = computed(() =>
store.items.map((type) => ({ label: type.name, value: type.key, hint: type.key })),
)
const related = computed(() => store.items.find((type) => type.key === props.typeKey))
const names = computed(() => relationNames(props.ownerName, related.value?.name ?? '', props.label))
const frozen = computed(() => props.locked || props.disabled)
const kindItems = computed(() =>
RELATION_KINDS.map((kind) => ({
value: kind,
label: kindTitle(kind),
sentence: kindSentence(kind, names.value),
})),
)
const sideItems = computed(() => [
{ label: t('one'), value: 'one' },
{ label: t('many'), value: 'many' },
])
const sample = computed(() => relationSample(props.kind))
function kindTitle(kind: RelationKind) {
if (kind === 'one_to_one') {
return t('One to one')
}
return kind === 'one_to_many' ? t('One to many') : t('Many to many')
}
function squares(count: number) {
return Array.from({ length: count }, (_, index) => index)
}
function onKind(value: unknown) {
if (isRelationKind(value)) {
emit('kind', value)
}
}
function onOwnerSide(value: unknown) {
emit('kind', kindFromOwnerSide(value as RelationSide, props.kind))
}
function onInverseSide(value: unknown) {
emit('kind', kindFromInverseSide(value as RelationSide, props.kind))
}
const SIDE_UI = {
base: 'mx-1 h-7 w-auto gap-1.5 rounded-none border border-accented bg-default py-0 ps-2 pe-7 text-sm font-medium text-highlighted ring-0',
trailing: 'pe-2',
trailingIcon: 'size-3 text-muted',
value: 'truncate',
}
const CARD_UI = {
root: 'w-full',
legend: 'mb-1.5 w-full font-medium text-highlighted',
item: 'group min-h-0 rounded-none border-accented p-2.5 text-highlighted has-data-[state=checked]:border-primary has-data-[state=checked]:bg-(--rc-sand) has-data-[state=checked]:text-(--rc-on-sand)',
wrapper: 'ms-0 w-full',
label: 'w-full text-base font-medium text-inherit',
}
onMounted(() => store.load())
</script>
<template>
<div class="flex min-w-0 flex-col gap-3.5" data-testid="relation-picker">
<p
v-if="locked"
data-testid="relation-locked-note"
class="flex items-center gap-1.5 text-xs/4.5 text-muted"
>
<UIcon name="i-lucide-lock" class="size-3 shrink-0" />
{{ t("The related type and the connection can't change after saving.") }}
</p>
<DirectoryField
:label="t('Related content type')"
name="relation-type"
:error="error"
:help="t('Choose the content type this field points to.')"
>
<USelect
:model-value="typeKey === '' ? undefined : typeKey"
:items="typeItems"
:placeholder="t('Choose a content type')"
:disabled="frozen"
:color="error ? 'error' : undefined"
class="w-full"
:ui="{
base: 'h-11 text-lg disabled:bg-elevated disabled:opacity-100 md:h-8 md:text-sm',
content: 'rounded-none shadow-(--shadow-popover)',
}"
@update:model-value="emit('type', String($event))"
>
<template #item-label="{ item }">
<span class="flex min-w-0 items-baseline gap-2">
<span class="truncate">{{ item.label }}</span>
<span class="font-mono text-xs text-muted">{{ item.hint }}</span>
</span>
</template>
</USelect>
</DirectoryField>
<URadioGroup
:model-value="kind"
:items="kindItems"
:disabled="frozen"
:legend="t('How are they connected?')"
variant="card"
indicator="hidden"
orientation="horizontal"
:ui="{
...CARD_UI,
fieldset: compact ? 'grid grid-cols-1 gap-2' : 'grid grid-cols-3 gap-2',
}"
@update:model-value="onKind"
>
<template #label="{ item }">
<span
class="flex flex-col gap-1.5 text-left"
:class="frozen && !(item.value === kind) ? 'opacity-60' : ''"
>
<span class="flex items-center gap-1.5" aria-hidden="true">
<span class="flex gap-0.75">
<span
v-for="square in squares(DIAGRAMS[item.value as RelationKind][0])"
:key="square"
class="size-2.5 bg-current"
/>
</span>
<span class="h-px w-5 bg-current" />
<span class="flex gap-0.75">
<span
v-for="square in squares(DIAGRAMS[item.value as RelationKind][1])"
:key="square"
class="size-2.5 bg-current"
/>
</span>
</span>
<span class="font-medium">{{ item.label }}</span>
<span
class="text-xs/4 font-normal text-pretty text-muted group-has-data-[state=checked]:text-(--rc-on-sand)"
>{{ item.sentence }}</span
>
</span>
</template>
</URadioGroup>
<div data-testid="relation-preview" class="flex flex-col gap-2 bg-elevated p-3">
<span class="flex flex-wrap items-center" data-testid="relation-owner-sentence">
{{ t('Each {0} has', [names.ownerSingular]) }}
<USelect
:model-value="ownerSide(kind)"
:items="sideItems"
:disabled="frozen"
:aria-label="t('Each {0} has', [names.ownerSingular])"
:ui="SIDE_UI"
@update:model-value="onOwnerSide"
/>
{{ ownerNoun(kind, names) }}
</span>
<span class="flex flex-wrap items-center" data-testid="relation-inverse-sentence">
{{ t('Each {0} has', [names.relatedSingular]) }}
<USelect
:model-value="inverseSide(kind)"
:items="sideItems"
:disabled="frozen"
:aria-label="t('Each {0} has', [names.relatedSingular])"
:ui="SIDE_UI"
@update:model-value="onInverseSide"
/>
{{ inverseNoun(kind, names) }}
<span class="text-muted">{{
` · ${t('shown on {0} as the field "{1}"', [names.relatedSingular, names.ownerPlural])}`
}}</span>
</span>
</div>
<div class="flex gap-3" :class="compact ? 'flex-col' : 'flex-row'">
<div
data-testid="relation-example-owner"
class="flex min-w-0 flex-1 flex-col gap-2 border border-default bg-default p-3"
>
<span class="font-semibold text-highlighted">{{ names.ownerSingular }}</span>
<span class="text-xs text-muted">{{ ownerNoun(kind, names) }}</span>
<div class="flex flex-wrap items-center gap-1.5">
<RelationChip
v-for="chip in sample.ownerChips"
:key="chip"
:label="chip"
tall
/>
<span v-if="sample.ownerMore" class="self-center text-xs text-muted"
>+{{ sample.ownerMore }}</span
>
</div>
</div>
<div
data-testid="relation-example-related"
class="flex min-w-0 flex-1 flex-col gap-2 border border-default bg-default p-3"
>
<span class="font-semibold text-highlighted">{{ names.relatedSingular }}</span>
<span class="text-xs text-muted">{{ inverseNoun(kind, names) }}</span>
<div class="flex flex-wrap items-center gap-1.5">
<RelationChip
v-for="chip in sample.relatedChips"
:key="chip"
:label="chip"
tall
/>
<span v-if="sample.relatedMore" class="self-center text-xs text-muted"
>+{{ sample.relatedMore }}</span
>
</div>
</div>
</div>
</div>
</template>
+2
View File
@@ -262,6 +262,7 @@ async function restoreRowFocus() {
:field="builder.selected.value"
:errors="selectedErrors"
:compact="false"
:owner-name="form.name"
/>
</template>
<template v-else>
@@ -320,6 +321,7 @@ async function restoreRowFocus() {
:focus-token="builder.labelFocusToken.value"
:field="builder.selected.value"
:errors="selectedErrors"
:owner-name="form.name"
compact
/>
</FieldSheet>
@@ -35,6 +35,7 @@ watch(
:name="remove.type.value.name"
:key-value="remove.type.value.key"
:total="remove.total.value"
:referrer="remove.referrer.value"
:pending="remove.pending.value"
:offline="remove.offline.value"
@confirm="remove.confirm"
+3 -3
View File
@@ -7,7 +7,7 @@ import SchemaChangeList from '@/components/SchemaChangeList.vue'
import { entriesLine } from '@/lib/schemaEntries'
import {
hasRefusedChange,
isMediaOnlyClean,
isNoDefaultOnlyClean,
summaryLine,
type FieldChange,
} from '@/lib/schemaBuilderDiff'
@@ -25,7 +25,7 @@ defineEmits<{ apply: []; close: [] }>()
const summary = computed(() => summaryLine(props.changes))
const entries = computed(() => entriesLine(props.name, props.total))
const refused = computed(() => hasRefusedChange(props.changes))
const mediaOnlyClean = computed(() => isMediaOnlyClean(props.changes))
const noDefaultOnlyClean = computed(() => isNoDefaultOnlyClean(props.changes))
</script>
<template>
@@ -53,7 +53,7 @@ const mediaOnlyClean = computed(() => isMediaOnlyClean(props.changes))
<p v-if="refused" class="text-xs/4.5 text-muted">
{{ t('Back to editing keeps your other changes.') }}
</p>
<p v-else-if="!mediaOnlyClean && !applying" class="text-xs/4.5 text-muted">
<p v-else-if="!noDefaultOnlyClean && !applying" class="text-xs/4.5 text-muted">
{{
t(
"Flagged changes can be refused if existing entries don't fit. If that happens, nothing is changed.",
@@ -0,0 +1,232 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { defineComponent, h } from 'vue'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { ApiError } from '@/composables/useApi'
import { RELATION_SEARCH_DEBOUNCE_MS, useRelationSearch } from '@/composables/useRelationSearch'
import type { ContentEntry } from '@/lib/contentTypes'
import { RELATION_PAGE_SIZE } from '@/lib/relationField'
const searchEntries = vi.fn()
vi.mock('@/composables/useEntries', () => ({
useEntries: () => ({ searchEntries }),
}))
interface Deferred {
resolve: (value: unknown) => void
reject: (error: unknown) => void
}
let wrappers: VueWrapper[] = []
function setup() {
let api!: ReturnType<typeof useRelationSearch>
const wrapper = mount(
defineComponent({
setup() {
api = useRelationSearch(() => 'venues')
return () => h('div')
},
}),
)
wrappers.push(wrapper)
return api
}
function entry(id: number): ContentEntry {
return { id, data: {} } as unknown as ContentEntry
}
function answer(ids: number[], total: number, page = 1) {
return { items: ids.map(entry), total, page, size: RELATION_PAGE_SIZE }
}
function deferred() {
const pending: Deferred[] = []
searchEntries.mockImplementation(
() =>
new Promise((resolve, reject) => {
pending.push({ resolve, reject })
}),
)
return pending
}
async function debounce() {
await vi.advanceTimersByTimeAsync(RELATION_SEARCH_DEBOUNCE_MS)
await flushPromises()
}
beforeEach(() => {
vi.useFakeTimers()
searchEntries.mockReset()
})
afterEach(() => {
wrappers.forEach((wrapper) => wrapper.unmount())
wrappers = []
vi.useRealTimers()
})
describe('useRelationSearch query', () => {
it('tracks the latest trimmed query across consecutive searches', async () => {
searchEntries.mockResolvedValue(answer([], 0))
const search = setup()
search.search(' alpha ')
await debounce()
expect(search.query.value).toBe('alpha')
search.search('beta')
await debounce()
expect(search.query.value).toBe('beta')
expect(searchEntries).toHaveBeenLastCalledWith('venues', {
q: 'beta',
page: 1,
size: RELATION_PAGE_SIZE,
})
search.search('')
await debounce()
expect(search.query.value).toBe('')
})
})
describe('useRelationSearch debounce', () => {
it('issues one request for rapid searches', async () => {
searchEntries.mockResolvedValue(answer([1], 1))
const search = setup()
search.search('a')
await vi.advanceTimersByTimeAsync(RELATION_SEARCH_DEBOUNCE_MS - 1)
search.search('ab')
await vi.advanceTimersByTimeAsync(RELATION_SEARCH_DEBOUNCE_MS - 1)
expect(searchEntries).not.toHaveBeenCalled()
await debounce()
expect(searchEntries).toHaveBeenCalledTimes(1)
expect(searchEntries.mock.calls[0]![1].q).toBe('ab')
expect(search.status.value).toBe('ready')
})
})
describe('useRelationSearch stale responses', () => {
it('discards a page-1 answer superseded by a newer load', async () => {
const pending = deferred()
const search = setup()
search.search('old')
await debounce()
search.search('new')
await debounce()
expect(pending).toHaveLength(2)
pending[1]!.resolve(answer([2], 1))
await flushPromises()
pending[0]!.resolve(answer([1], 1))
await flushPromises()
expect(search.entries.value.map((item) => item.id)).toEqual([2])
})
it('discards an in-flight answer when a new search starts during the debounce', async () => {
const pending = deferred()
const search = setup()
search.search('old')
await debounce()
search.search('new')
pending[0]!.resolve(answer([1], 1))
await flushPromises()
expect(search.entries.value).toEqual([])
expect(search.status.value).toBe('loading')
})
it('discards an answer after stop', async () => {
const pending = deferred()
const search = setup()
search.search('x')
await debounce()
search.stop()
pending[0]!.resolve(answer([1], 1))
await flushPromises()
expect(search.entries.value).toEqual([])
})
})
describe('useRelationSearch load more', () => {
it('appends the next page and ends when everything is loaded', async () => {
searchEntries
.mockResolvedValueOnce(answer([1, 2], 3))
.mockResolvedValueOnce(answer([3], 3, 2))
const search = setup()
await search.reload()
expect(search.hasMore.value).toBe(true)
await search.more()
expect(searchEntries).toHaveBeenLastCalledWith('venues', {
q: '',
page: 2,
size: RELATION_PAGE_SIZE,
})
expect(search.entries.value.map((item) => item.id)).toEqual([1, 2, 3])
expect(search.hasMore.value).toBe(false)
expect(search.more()).toBeUndefined()
})
it('starts the limiter on a 429 and keeps the loaded rows', async () => {
searchEntries
.mockResolvedValueOnce(answer([1], 5))
.mockRejectedValueOnce(new ApiError(429, 7))
const search = setup()
await search.reload()
await search.more()
expect(search.status.value).toBe('limited')
expect(search.limit.remaining.value).toBe(7)
expect(search.entries.value.map((item) => item.id)).toEqual([1])
expect(search.loadingMore.value).toBe(false)
})
it('surfaces other errors as failed and keeps the loaded rows', async () => {
searchEntries.mockResolvedValueOnce(answer([1], 5)).mockRejectedValueOnce(new ApiError(500))
const search = setup()
await search.reload()
await search.more()
expect(search.status.value).toBe('failed')
expect(search.entries.value.map((item) => item.id)).toEqual([1])
})
it('goes idle on a 401 during load more', async () => {
searchEntries.mockResolvedValueOnce(answer([1], 5)).mockRejectedValueOnce(new ApiError(401))
const search = setup()
await search.reload()
await search.more()
expect(search.status.value).toBe('idle')
})
it('does not request page+1 of a stale set after a failed page-1', async () => {
searchEntries
.mockResolvedValueOnce(answer([1], 5))
.mockRejectedValueOnce(new ApiError(500))
.mockResolvedValueOnce(answer([9], 9))
const search = setup()
await search.reload()
await search.reload()
expect(search.status.value).toBe('failed')
await search.reload()
await search.more()
expect(searchEntries.mock.calls.map((call) => call[1].page)).toEqual([1, 1, 1, 2])
})
})
+22 -1
View File
@@ -3,6 +3,12 @@ import type { ContentEntry, EntryPage, EntryPageQuery } from '@/lib/contentTypes
import { entryEndpoint } from '@/lib/contentEndpoints'
import { jsonInit } from '@/lib/directoryRequest'
export interface EntrySearchQuery {
q: string
page: number
size: number
}
export function useEntries() {
const { request } = useApi()
const options = { onForbidden: 'passthrough' } as const
@@ -21,6 +27,21 @@ export function useEntries() {
return page
}
async function searchEntries(key: string, query: EntrySearchQuery): Promise<EntryPage> {
const params = new URLSearchParams()
if (query.q !== '') {
params.set('q', query.q)
}
params.set('page', String(query.page))
params.set('size', String(query.size))
const url = `${entryEndpoint(key)}?${params.toString()}`
const page = await request<EntryPage>(url, options)
if (!Array.isArray(page?.items) || typeof page.total !== 'number') {
throw new Error(`Unexpected response from ${url}`)
}
return page
}
async function requestEntry(url: string, init: RequestInit): Promise<ContentEntry> {
const entry = await request<ContentEntry>(url, { ...init, ...options })
if (
@@ -49,5 +70,5 @@ export function useEntries() {
await request<void>(entryEndpoint(key, id), { method: 'DELETE', ...options })
}
return { listEntries, getEntry, createEntry, saveEntry, deleteEntry }
return { listEntries, searchEntries, getEntry, createEntry, saveEntry, deleteEntry }
}
+14 -3
View File
@@ -6,6 +6,7 @@ import { useEntryForm } from '@/composables/useEntryForm'
import { useEntryLoad } from '@/composables/useEntryLoad'
import type { ContentEntry } from '@/lib/contentTypes'
import type { MediaSummary } from '@/lib/mediaField'
import type { RelationSummary } from '@/lib/relationField'
import { resolveEditorPhase, type EntryTarget } from '@/lib/entryEditorState'
import { buildData, issueFor, validateEntry } from '@/lib/entryForm'
import { classifyRefusal, isGoneError, parseEntryRefusal } from '@/lib/entryServerError'
@@ -92,7 +93,12 @@ export function useEntryDraft(typeKey: string, target: EntryTarget) {
return null
}
failure.value = 'none'
const issues = validateEntry(fields.value, form.values.value, form.images.value)
const issues = validateEntry(
fields.value,
form.values.value,
form.images.value,
form.relations.value,
)
if (Object.keys(issues).length > 0) {
form.reject(issues)
focusToken.value++
@@ -114,8 +120,13 @@ export function useEntryDraft(typeKey: string, target: EntryTarget) {
}
}
function change(key: string, value: unknown, image?: MediaSummary | null) {
form.setValue(key, value, image)
function change(
key: string,
value: unknown,
image?: MediaSummary | null,
summaries?: RelationSummary[],
) {
form.setValue(key, value, image, summaries)
}
function reload() {
+18 -1
View File
@@ -1,10 +1,12 @@
import { computed, ref } from 'vue'
import type { BuiltinField, ContentEntry } from '@/lib/contentTypes'
import type { MediaMap, MediaSummary } from '@/lib/mediaField'
import type { RelationSummaries, RelationSummary } from '@/lib/relationField'
import {
carriesDefault,
firstIssueKey,
initialImages,
initialRelations,
initialValues,
valuesDiffer,
type EntryIssues,
@@ -16,6 +18,7 @@ export function useEntryForm(fields: () => BuiltinField[], creating: () => boole
const values = ref<EntryValues>({})
const saved = ref<EntryValues>({})
const images = ref<MediaMap>({})
const relations = ref<RelationSummaries>({})
const issues = ref<EntryIssues>({})
const rejected = ref(false)
@@ -28,6 +31,7 @@ export function useEntryForm(fields: () => BuiltinField[], creating: () => boole
values.value = { ...next }
saved.value = { ...next }
images.value = initialImages(fields(), entry)
relations.value = initialRelations(fields(), entry)
issues.value = {}
rejected.value = false
}
@@ -45,9 +49,21 @@ export function useEntryForm(fields: () => BuiltinField[], creating: () => boole
images.value = next
}
function setValue(key: string, value: unknown, image?: MediaSummary | null) {
function setRelations(key: string, summaries: RelationSummary[] | undefined) {
if (summaries !== undefined) {
relations.value = { ...relations.value, [key]: summaries }
}
}
function setValue(
key: string,
value: unknown,
image?: MediaSummary | null,
summaries?: RelationSummary[],
) {
values.value = { ...values.value, [key]: value }
setImage(key, image)
setRelations(key, summaries)
rejected.value = false
if (issues.value[key]) {
const rest = { ...issues.value }
@@ -72,6 +88,7 @@ export function useEntryForm(fields: () => BuiltinField[], creating: () => boole
return {
values,
images,
relations,
issues,
rejected,
dirty,
+131
View File
@@ -0,0 +1,131 @@
import { computed, onBeforeUnmount, ref } from 'vue'
import { ApiError } from '@/composables/useApi'
import { useDelayedSkeleton } from '@/composables/useDelayedSkeleton'
import { useEntries } from '@/composables/useEntries'
import { useRetryAfter } from '@/composables/useRetryAfter'
import type { ContentEntry } from '@/lib/contentTypes'
import { RELATION_PAGE_SIZE } from '@/lib/relationField'
export const RELATION_SEARCH_DEBOUNCE_MS = 200
const UNAUTHORIZED = 401
const RATE_LIMITED = 429
const RATE_LIMIT_FALLBACK_SECONDS = 30
export type RelationSearchStatus = 'idle' | 'loading' | 'ready' | 'failed' | 'limited'
export function useRelationSearch(target: () => string) {
const { searchEntries } = useEntries()
const skeleton = useDelayedSkeleton()
const limit = useRetryAfter()
const entries = ref<ContentEntry[]>([])
const total = ref(0)
const page = ref(0)
const status = ref<RelationSearchStatus>('idle')
const loadingMore = ref(false)
const query = ref('')
let token = 0
let timer: ReturnType<typeof setTimeout> | null = null
const hasMore = computed(() => status.value === 'ready' && entries.value.length < total.value)
const searching = computed(() => status.value === 'loading' && !loadingMore.value)
const showSkeleton = computed(() => searching.value && skeleton.visible.value)
function clearTimer() {
if (timer !== null) {
clearTimeout(timer)
timer = null
}
}
function fail(error: unknown) {
if (error instanceof ApiError && error.status === UNAUTHORIZED) {
status.value = 'idle'
} else if (error instanceof ApiError && error.status === RATE_LIMITED) {
limit.start(error.retryAfter ?? RATE_LIMIT_FALLBACK_SECONDS)
status.value = 'limited'
} else {
status.value = 'failed'
}
}
async function load(pageNumber: number) {
const current = ++token
loadingMore.value = pageNumber > 1
status.value = 'loading'
skeleton.start()
try {
const answer = await searchEntries(target(), {
q: query.value,
page: pageNumber,
size: RELATION_PAGE_SIZE,
})
if (current !== token) {
return
}
entries.value = pageNumber === 1 ? answer.items : [...entries.value, ...answer.items]
total.value = answer.total
page.value = pageNumber
status.value = 'ready'
} catch (error) {
if (current === token) {
if (pageNumber === 1) {
page.value = 0
}
fail(error)
}
} finally {
if (current === token) {
skeleton.stop()
loadingMore.value = false
}
}
}
function search(text: string) {
clearTimer()
query.value = text.trim()
token++
skeleton.stop()
loadingMore.value = false
timer = setTimeout(() => {
timer = null
load(1)
}, RELATION_SEARCH_DEBOUNCE_MS)
}
function reload() {
clearTimer()
return load(1)
}
function more() {
if (hasMore.value) {
return load(page.value + 1)
}
}
function stop() {
clearTimer()
token++
skeleton.stop()
loadingMore.value = false
}
onBeforeUnmount(stop)
return {
entries,
total,
status,
query,
hasMore,
loadingMore,
showSkeleton,
limit,
search,
reload,
more,
stop,
}
}
+10
View File
@@ -12,6 +12,7 @@ import { SCHEMA_PATH } from '@/lib/routePaths'
import { useContentTypesStore } from '@/stores/contentTypes'
const HAS_ENTRIES_BODY = 'content_type_has_entries'
const REFERENCED_BODY = 'content_type_referenced'
const TOAST_ID = 'content-type-deleted'
export function useSchemaDelete(source: () => EditSource) {
@@ -27,6 +28,12 @@ export function useSchemaDelete(source: () => EditSource) {
const offline = computed(() => !online.value)
const type = computed(() => source().type)
const total = computed(() => source().total)
const referrer = computed(
() =>
store.items.find((candidate) =>
candidate.fields.some((field) => field.relation?.content_type === type.value.key),
)?.name ?? '',
)
function open() {
if (pending.value) {
@@ -60,6 +67,8 @@ export function useSchemaDelete(source: () => EditSource) {
forbidden.value = true
} else if (status === 409 && body === HAS_ENTRIES_BODY) {
stage.value = 'conflict'
} else if (status === 409 && body === REFERENCED_BODY) {
stage.value = 'referenced'
} else {
stage.value = 'failed'
}
@@ -95,6 +104,7 @@ export function useSchemaDelete(source: () => EditSource) {
offline,
type,
total,
referrer,
open,
close,
viewEntries,
+5
View File
@@ -28,6 +28,7 @@ export interface ApiEndpoint {
bodySample: Record<string, unknown> | null
errors: ApiError[]
response: string
status: number
rateLimited: boolean
}
@@ -542,6 +543,7 @@ function endpoint(
bodySample: null,
errors,
response,
status: response === NO_CONTENT_RESPONSE ? 204 : 200,
rateLimited: false,
...extra,
}
@@ -638,6 +640,7 @@ export const API_GROUPS: ApiGroup[] = [
title: 'Choosing tiles for a small bathroom',
body: 'Small rooms show every grout line.',
},
status: 201,
},
),
endpoint(
@@ -886,6 +889,7 @@ export const API_GROUPS: ApiGroup[] = [
json(mediaItem()),
{
pathId: null,
status: 201,
bodyKind: 'multipart',
body: [
{
@@ -1156,6 +1160,7 @@ export const API_GROUPS: ApiGroup[] = [
],
json(invite()),
{
status: 201,
bodyKind: 'json',
body: [
{
+1 -1
View File
@@ -16,7 +16,7 @@ const SOURCES = [
'lib/schemaBuilderDiff.ts',
]
const SAME_IN_FRENCH = new Set<string>(['Date'])
const SAME_IN_FRENCH = new Set<string>(['Date', 'Relation'])
const LITERAL = /\bt\(\s*(?:'((?:\\.|[^'\\])*)'|"((?:\\.|[^"\\])*)")/g
+55
View File
@@ -2663,6 +2663,61 @@ export const messages = {
"A media field can't have a default, so the {0} existing entries would have no image. Make {1} optional to add it.":
'Un champ média ne peut pas avoir de valeur par défaut, donc les {0} entrées existantes n’auraient pas d’image. Rendez {1} facultatif pour l’ajouter.',
'{0} entries are unaffected.': '{0} entrées ne sont pas concernées.',
'Entry no longer exists': 'Cette entrée n’existe plus',
'Choose a {0}.': 'Choisissez une valeur pour {0}.',
'{0} must point to an existing entry.': '{0} doit pointer vers une entrée existante.',
'That {0} is already used by another entry.':
'Cette valeur de {0} est déjà utilisée par une autre entrée.',
Relation: 'Relation',
"Links to another type's entries": 'Renvoie vers les entrées d’un autre type',
"A relation can't have a default, so the existing entry would have no {0}. Make {0} optional to add it.":
'Une relation ne peut pas avoir de valeur par défaut, donc l’entrée existante n’aurait pas de valeur pour {0}. Rendez {0} facultatif pour l’ajouter.',
"A relation can't have a default, so the {0} existing entries would have no {1}. Make {1} optional to add it.":
'Une relation ne peut pas avoir de valeur par défaut, donc les {0} entrées existantes n’auraient pas de valeur pour {1}. Rendez {1} facultatif pour l’ajouter.',
Entries: 'Entrées',
'Each {0} has one {1}, and each {1} has one {0}.':
'Chaque {0} a un seul {1}, et chaque {1} a un seul {0}.',
'Each {0} has one {1}. A {1} has many {2}.':
'Chaque {0} a un seul {1}. Un {1} a plusieurs {2}.',
'Each {0} has many {1}, and each {2} has many {3}.':
'Chaque {0} a plusieurs {1}, et chaque {2} a plusieurs {3}.',
'Choose a related content type.': 'Choisissez un type de contenu lié.',
'{0} has a field that points to {1}. Remove that field first.':
'{0} a un champ qui pointe vers {1}. Supprimez d’abord ce champ.',
'Another content type has a field that points to {0}. Remove that field first.':
'Un autre type de contenu a un champ qui pointe vers {0}. Supprimez d’abord ce champ.',
'{0} is required. Choose another to save.':
'{0} est obligatoire. Choisissez une autre valeur pour enregistrer.',
'An {0} can have many {1}.': 'Un {0} peut avoir plusieurs {1}.',
'A {0} can have many {1}.': 'Un {0} peut avoir plusieurs {1}.',
'Remove {0} from {1}': 'Retirer {0} de {1}',
'{0} set to {1}.': '{0} défini sur {1}.',
'{0} removed from {1}.': '{0} retiré de {1}.',
'{0} added to {1}.': '{0} ajouté à {1}.',
'{0} results': '{0} résultats',
'No results': 'Aucun résultat',
'Search to add': 'Rechercher pour ajouter',
'Searching…': 'Recherche en cours…',
"Couldn't load {0}": 'Impossible de charger {0}',
'You can add up to {0}.': 'Vous pouvez en ajouter jusqu’à {0}.',
'No {0} yet. Add one in Content, then come back.':
'Aucun élément dans {0} pour l’instant. Ajoutez-en depuis Contenu, puis revenez.',
'No {0} match "{1}"': 'Aucun résultat dans {0} pour « {1} »',
'No other {0} to add.': 'Aucun autre élément de {0} à ajouter.',
one: 'un',
many: 'plusieurs',
'One to one': 'Un à un',
'One to many': 'Un à plusieurs',
'Many to many': 'Plusieurs à plusieurs',
"The related type and the connection can't change after saving.":
'Le type lié et la connexion ne peuvent plus changer après l’enregistrement.',
'Related content type': 'Type de contenu lié',
'Choose the content type this field points to.':
'Choisissez le type de contenu vers lequel ce champ pointe.',
'Choose a content type': 'Choisissez un type de contenu',
'How are they connected?': 'Comment sont-ils liés ?',
'Each {0} has': 'Chaque {0} a',
'shown on {0} as the field "{1}"': 'affiché sur {0} comme le champ « {1} »',
} as const
export type MessageKey = keyof typeof messages
@@ -0,0 +1,53 @@
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { messages } from './messages'
const SOURCES = [
'components/RelationField.vue',
'components/RelationPicker.vue',
'components/DeleteTypeDialog.vue',
'lib/relationSentences.ts',
'lib/fieldTypes.ts',
'lib/entryCells.ts',
'lib/entryMessages.ts',
'lib/schemaBuilderValidation.ts',
]
const SAME_IN_FRENCH = new Set<string>(['Relation'])
const LITERAL = /\bt\(\s*(?:'((?:\\.|[^'\\])*)'|"((?:\\.|[^"\\])*)")/g
function keysIn(source: string) {
return [...source.matchAll(LITERAL)].map((match) =>
(match[1] ?? match[2] ?? '').replace(/\\u0022/g, '"').replace(/\\(['"\\])/g, '$1'),
)
}
describe('Relation field messages', () => {
const keys = SOURCES.flatMap((file) =>
keysIn(readFileSync(join(import.meta.dirname, '..', file), 'utf8')).map((key) => ({
file,
key,
})),
)
it('finds the strings of the feature', () => {
expect(keys.length).toBeGreaterThan(40)
})
it.each(keys.map(({ file, key }) => [file, key]))(
'%s: "%s" has its own French entry',
(_file, key) => {
const french = (messages as Record<string, string>)[key as string]
expect(french).toMatch(/\S/)
if (
!SAME_IN_FRENCH.has(key as string) &&
!(key as string).match(/^(Date|Text|Number)$/)
) {
expect(french).not.toBe(key)
}
},
)
})
+1
View File
@@ -10,6 +10,7 @@ const CONTROLS: Record<FieldType, string> = {
date: 'date',
select: 'select',
media: 'media',
relation: 'relation',
}
function editor(type: FieldType) {
+5 -3
View File
@@ -50,9 +50,10 @@ function mediaField(rest: object = {}) {
const media = ENTRY_EDITORS.media
describe('media in the registry', () => {
it('is the seventh type, after select', () => {
expect(FIELD_TYPES).toHaveLength(7)
it('is the seventh type, after select and before relation', () => {
expect(FIELD_TYPES).toHaveLength(8)
expect(FIELD_TYPES[6]).toBe('media')
expect(FIELD_TYPES[7]).toBe('relation')
expect(FIELD_TYPES[5]).toBe('select')
})
@@ -82,7 +83,7 @@ describe('media in the registry', () => {
)
})
it.each(FIELD_TYPES.filter((type) => type !== 'media'))(
it.each(FIELD_TYPES.filter((type) => type !== 'media' && type !== 'relation'))(
'%s keeps its builder options and has no hint',
(type) => {
const spec = fieldTypeSpec(type)
@@ -374,6 +375,7 @@ describe('media in the schema builder', () => {
min: null,
max: null,
options: [],
relation: null,
})
expect(payloadField({ ...field, required: true }).required).toBe(true)
})
+495
View File
@@ -0,0 +1,495 @@
import { describe, expect, it } from 'vitest'
import type { ContentEntry } from '@/lib/contentTypes'
import { describeCell, plainCellText, relationLabel } from '@/lib/entryCells'
import { ENTRY_EDITORS } from '@/lib/entryEditors'
import {
buildData,
entryTitle,
initialRelations,
initialValues,
validateEntry,
valuesDiffer,
} from '@/lib/entryForm'
import { ruleMessage } from '@/lib/entryMessages'
import { groupFields } from '@/lib/entryLayout'
import { classifyRefusal, parseEntryRefusal } from '@/lib/entryServerError'
import { FIELD_TYPES, fieldTypeSpec } from '@/lib/fieldTypes'
import {
RELATION_PAGE_SIZE,
isRelationId,
relationIdsOf,
summariesOf,
type RelationSummary,
} from '@/lib/relationField'
import { relationRowOf } from '@/lib/relationRows'
import { ApiError } from '@/lib/apiError'
import { diffFields } from '@/lib/schemaBuilderDiff'
import { baselinePayload, fieldFromApi, formFromType } from '@/lib/schemaBuilderLoad'
import { createField } from '@/lib/schemaBuilderModel'
import { buildPayload, payloadField } from '@/lib/schemaBuilderPayload'
import { sampleEntry } from '@/lib/schemaBuilderSample'
import { validateField } from '@/lib/schemaBuilderValidation'
import { apiField } from './schemaFixtures'
const relation = ENTRY_EDITORS.relation
function field(kind: 'one_to_one' | 'one_to_many' | 'many_to_many', rest: object = {}) {
return apiField('Venue', 'venue', 'relation', {
options: [],
relation: { content_type: 'venues', kind },
...rest,
})
}
const single = field('one_to_many')
const many = field('many_to_many')
function target(id: number, name: string | null): RelationSummary {
return {
id,
content_type: 'venues',
first_field: { key: 'name', type: 'text', value: name },
}
}
describe('relation in the registry', () => {
it('is the eighth type, after media', () => {
expect(FIELD_TYPES).toHaveLength(8)
expect(FIELD_TYPES[7]).toBe('relation')
expect(FIELD_TYPES[6]).toBe('media')
})
it('describes itself', () => {
const spec = fieldTypeSpec('relation')
expect(spec.label()).toBe('Relation')
expect(spec.description()).toBe("Links to another type's entries")
expect(spec.icon).toBe('i-lucide-link')
expect(spec.editor.control).toBe('relation')
expect(spec.cell).toBe('relation')
expect(spec.pairs).toBe(false)
expect(spec.supportsUnique).toBe(false)
expect(spec.supportsLimits).toBe(false)
expect(spec.supportsDefault).toBe(false)
expect(spec.supportsChoices).toBe(false)
expect(spec.showsUnsupportedOptions).toBe(false)
expect(spec.builderHint).toBeNull()
expect(spec.holdsRelation).toBe(true)
})
it('is never the fallback type, while an unknown type still is', () => {
expect(fieldTypeSpec('relation')).not.toBe(fieldTypeSpec('text'))
expect(fieldTypeSpec('mystery')).toBe(fieldTypeSpec('text'))
expect(fieldFromApi(single, 1).type).toBe('relation')
})
it('has no counter and no help of its own', () => {
expect(relation.counter(single, 3)).toBeNull()
expect(relation.help(single)).toBe('')
})
it('never pairs with a neighbour', () => {
const fields = [
apiField('Online', 'online', 'boolean'),
single,
apiField('Cap', 'cap', 'number'),
]
expect(groupFields(fields).map((row) => row.length)).toEqual([1, 1, 1])
})
})
describe('empty and initial values', () => {
it.each([
['one_to_one', null],
['one_to_many', null],
['many_to_many', []],
] as const)('starts empty for %s on create', (kind, empty) => {
expect(relation.initial(field(kind), 3, true)).toEqual(empty)
})
it('has no default, so no Default tag ever shows', () => {
expect(relation.initial(field('one_to_many', { default: 3 }), undefined, true)).toBeNull()
})
it('takes the stored id or ids on edit', () => {
expect(relation.initial(single, 3, false)).toBe(3)
expect(relation.initial(single, null, false)).toBeNull()
expect(relation.initial(many, [11, 12], false)).toEqual([11, 12])
expect(relation.initial(many, undefined, false)).toEqual([])
})
it('copies the stored array', () => {
const stored = [11]
expect(relation.initial(many, stored, false)).not.toBe(stored)
})
})
describe('client validation of a relation value', () => {
it.each([
['single', true, null, 'required'],
['single', false, null, null],
['single', true, 3, null],
['single', false, 0, 'type'],
['single', false, '3', 'type'],
['single', false, [3], 'type'],
['many', true, [], 'required'],
['many', false, [], null],
['many', false, [11, 12], null],
['many', false, [11, 11], 'type'],
['many', false, 11, 'type'],
['many', false, Array.from({ length: 51 }, (_, index) => index + 1), 'type'],
['many', false, Array.from({ length: 50 }, (_, index) => index + 1), null],
])('%s required=%s value %j gives %s', (kind, required, value, rule) => {
const subject = kind === 'single' ? single : many
expect(relation.validate({ ...subject, required }, value)).toBe(rule)
})
it('treats a required relation whose targets are all missing as empty', () => {
const gone: RelationSummary = { id: 3, missing: true }
expect(
relation.validate({ ...single, required: true }, 3, { image: null, relations: [gone] }),
).toBe('required')
expect(
relation.validate({ ...single, required: false }, 3, {
image: null,
relations: [gone],
}),
).toBeNull()
expect(
relation.validate({ ...many, required: true }, [3, 4], {
image: null,
relations: [gone, { id: 4, missing: true }],
}),
).toBe('required')
expect(
relation.validate({ ...many, required: true }, [3, 4], {
image: null,
relations: [gone, target(4, 'Hall')],
}),
).toBeNull()
})
it('never produces min, max or options', () => {
const rules = [null, 0, '3', [3], [], [1, 1], 5].flatMap((value) =>
[single, many].map((subject) =>
relation.validate({ ...subject, required: true }, value),
),
)
expect(rules.filter((rule) => ['min', 'max', 'options'].includes(rule ?? ''))).toEqual([])
})
})
describe('messages of a relation field', () => {
it.each([
['required', 'Choose a Venue.'],
['type', 'Venue must point to an existing entry.'],
['unique', 'That Venue is already used by another entry.'],
] as const)('the rule %s reads "%s"', (rule, message) => {
expect(ruleMessage(rule, single)).toBe(message)
})
})
describe('the payload', () => {
it('sends the id, null, or an array of ids', () => {
expect(relation.payload(single, 3)).toBe(3)
expect(relation.payload(single, null)).toBeNull()
expect(relation.payload(single, undefined)).toBeNull()
expect(relation.payload(many, [11, 12])).toEqual([11, 12])
expect(relation.payload(many, undefined)).toEqual([])
})
it('puts null and [] in a create body, never absent', () => {
const fields = [single, { ...many, key: 'speakers' }]
const body = buildData(fields, initialValues(fields, null))
expect(body).toEqual({ venue: null, speakers: [] })
expect(Object.keys(body)).toEqual(['venue', 'speakers'])
})
})
describe('the ids helpers', () => {
it('accepts uint32 ids of at least 1', () => {
expect(isRelationId(1)).toBe(true)
expect(isRelationId(4294967295)).toBe(true)
expect(isRelationId(0)).toBe(false)
expect(isRelationId(4294967296)).toBe(false)
expect(isRelationId(1.5)).toBe(false)
expect(isRelationId('3')).toBe(false)
})
it('reads one id or many', () => {
expect(relationIdsOf(3)).toEqual([3])
expect(relationIdsOf([3, 'x', 4])).toEqual([3, 4])
expect(relationIdsOf(null)).toEqual([])
})
})
describe('summaries of an entry', () => {
const entry = {
id: 42,
data: { venue: 3, speakers: [11, 12] },
relations: {
venue: target(3, 'Rue Verte hall'),
speakers: [target(11, 'Ines Duarte'), target(12, 'Jonas Pereira')],
},
} as unknown as ContentEntry
it('wraps a single summary in an array', () => {
expect(summariesOf(entry, 'venue').map((summary) => summary.id)).toEqual([3])
expect(summariesOf(entry, 'speakers').map((summary) => summary.id)).toEqual([11, 12])
expect(summariesOf(entry, 'other')).toEqual([])
expect(summariesOf(null, 'venue')).toEqual([])
})
it('keeps only the summaries of the stored ids', () => {
const stale = { ...entry, data: { venue: 4, speakers: [12] } } as ContentEntry
const kept = initialRelations([single, { ...many, key: 'speakers' }], stale)
expect(kept).toEqual({ speakers: [entry.relations!.speakers![1]] })
})
})
describe('dirty tracking', () => {
it('compares ids by value and by order', () => {
expect(valuesDiffer([single], { venue: 3 }, { venue: 3 })).toBe(false)
expect(valuesDiffer([many], { venue: [11, 12] }, { venue: [11, 12] })).toBe(false)
expect(valuesDiffer([many], { venue: [12, 11] }, { venue: [11, 12] })).toBe(true)
expect(valuesDiffer([many], { venue: [11] }, { venue: [11, 12] })).toBe(true)
})
})
describe('labels and cells', () => {
it('uses the first field of the target, formatted like the list', () => {
expect(relationLabel(target(3, 'Rue Verte hall'))).toBe('Rue Verte hall')
expect(
relationLabel({
id: 5,
content_type: 'x',
first_field: { key: 'on', type: 'boolean', value: true },
}),
).toBe('Yes')
expect(
relationLabel({
id: 6,
content_type: 'x',
first_field: { key: 'on', type: 'number', value: 1500 },
}),
).toBe('1,500')
})
it('falls back to Entry N for a null first field', () => {
expect(relationLabel(target(7, null))).toBe('Entry 7')
expect(
relationLabel({
id: 8,
content_type: 'x',
first_field: { key: 'm', type: 'media', value: 9 },
}),
).toBe('Entry 8')
})
it('labels a missing target', () => {
expect(relationLabel({ id: 3, missing: true })).toBe('Entry no longer exists')
})
it('describes one chip, two chips and a +N, or an empty cell', () => {
const summaries = [11, 12, 13, 14].map((id) => target(id, `Speaker ${id}`))
const cell = describeCell(many, [11, 12, 13, 14], undefined, summaries)
expect(cell.kind).toBe('relation')
expect(cell.chips!.map((chip) => chip.label)).toEqual(['Speaker 11', 'Speaker 12'])
expect(cell.more).toBe(2)
expect(plainCellText(cell)).toBe('Speaker 11, Speaker 12, Speaker 13, Speaker 14')
expect(describeCell(many, []).kind).toBe('empty')
expect(describeCell(single, null).kind).toBe('empty')
expect(plainCellText(describeCell(many, []))).toBe('–')
})
it('never shows the numeric id when no summary came with the item', () => {
const cell = describeCell(single, 3)
expect(cell.chips).toEqual([{ id: 3, label: 'Entry no longer exists', missing: true }])
expect(cell.text).not.toContain('3')
})
it('titles an entry whose first field is a relation "Entry N"', () => {
const entry = {
id: 42,
data: { venue: 3 },
relations: { venue: target(3, 'Hall') },
} as unknown as ContentEntry
expect(entryTitle([single], entry)).toBe('Entry 42')
})
})
describe('rows of the picker', () => {
const fields = [
apiField('Name', 'name', 'text'),
apiField('City', 'city', 'text'),
apiField('Seats', 'seats', 'number'),
apiField('Notes', 'notes', 'text'),
]
const entry = (data: Record<string, unknown>) => ({ id: 3, data }) as unknown as ContentEntry
it('puts the first field in the title and up to two next fields in the second line', () => {
const row = relationRowOf(
entry({ name: 'Rue Verte hall', city: 'Lyon', seats: 120, notes: 'x' }),
'venues',
fields,
)
expect(row.title).toBe('Rue Verte hall')
expect(row.detail).toBe('Lyon · 120')
expect(row.summary.first_field).toEqual({
key: 'name',
type: 'text',
value: 'Rue Verte hall',
})
})
it('skips empty fields and falls back to Entry N', () => {
const row = relationRowOf(entry({ name: '', city: '', seats: 5 }), 'venues', fields)
expect(row.title).toBe('Entry 3')
expect(row.detail).toBe('5')
})
it('copes with a type that is not known yet', () => {
const row = relationRowOf(entry({ name: 'x' }), 'venues', [])
expect(row.title).toBe('Entry 3')
expect(row.detail).toBe('')
})
})
describe('server refusals', () => {
it.each([
[422, 'invalid_entry: venue: required', 'required'],
[422, 'invalid_entry: venue: type', 'type'],
[409, 'invalid_entry: venue: unique', 'unique'],
])('maps %i %s to a rule of the field', (status, body, rule) => {
const outcome = classifyRefusal(
[single],
parseEntryRefusal(new ApiError(status, undefined, body)),
)
expect(outcome).toMatchObject({ kind: 'field', rule })
})
it('maps unknown_field to a schema change', () => {
const outcome = classifyRefusal(
[single],
parseEntryRefusal(new ApiError(422, undefined, 'invalid_entry: venue: unknown_field')),
)
expect(outcome).toEqual({ kind: 'schema', key: 'venue' })
})
})
describe('the entry validation', () => {
it('reports the first rule of each relation field', () => {
const fields = [
{ ...single, required: true },
{ ...many, key: 'speakers', required: true },
]
const issues = validateEntry(fields, { venue: null, speakers: [] })
expect(issues.venue!.rule).toBe('required')
expect(issues.speakers!.rule).toBe('required')
expect(issues.venue!.message).toBe('Choose a Venue.')
})
})
describe('relation in the builder model', () => {
const events = {
id: 1,
key: 'events',
name: 'Events',
icon: null,
created_at: '',
updated_at: '',
}
it('loads the target and the kind', () => {
const loaded = fieldFromApi(field('many_to_many'), 1)
expect(loaded.relationType).toBe('venues')
expect(loaded.relationKind).toBe('many_to_many')
expect(loaded.saved).toBe(true)
})
it('sends the relation only for a relation field', () => {
const sent = payloadField(
createField(1, {
label: 'Venue',
key: 'venue',
type: 'relation',
relationType: 'venues',
}),
)
expect(sent).toEqual({
key: 'venue',
label: 'Venue',
type: 'relation',
required: false,
unique: false,
default: null,
min: null,
max: null,
options: [],
relation: { content_type: 'venues', kind: 'one_to_many' },
})
expect(
payloadField(createField(2, { label: 'T', key: 't', relationType: 'venues' })).relation,
).toBeNull()
})
it('round trips a loaded field with no change', () => {
const type = { ...events, fields: [single, { ...many, key: 'speakers' }] }
let uid = 0
const form = formFromType(type, () => ++uid)
expect(buildPayload(form).fields).toEqual(baselinePayload(type))
expect(diffFields(baselinePayload(type), form.fields, 3)).toEqual([])
})
it('needs a related type', () => {
const created = createField(1, { label: 'Venue', key: 'venue', type: 'relation' })
expect(validateField(created, []).relation).toBe('Choose a related content type.')
expect(validateField({ ...created, relationType: 'venues' }, []).relation).toBeUndefined()
expect(validateField(createField(2, { label: 'T', key: 't' }), []).relation).toBeUndefined()
})
it('samples null for a single kind and [] for many_to_many', () => {
const singleField = createField(1, { label: 'Venue', key: 'venue', type: 'relation' })
const manyField = createField(2, {
label: 'Speakers',
key: 'speakers',
type: 'relation',
relationKind: 'many_to_many',
})
const data = sampleEntry('events', [singleField, manyField]).data
expect(data.venue).toBeNull()
expect(data.speakers).toEqual([])
})
})
describe('the picker page size', () => {
it('is one of the sizes the entry list endpoint accepts', () => {
expect([5, 25, 50, 100]).toContain(RELATION_PAGE_SIZE)
})
})
@@ -0,0 +1,62 @@
import { describe, expect, it } from 'vitest'
import type { BuiltinField, ContentEntry } from '@/lib/contentTypes'
import { ROW_DETAIL_FIELDS, relationRowOf } from '@/lib/relationRows'
function field(key: string, type: string): BuiltinField {
return { key, type, label: key } as unknown as BuiltinField
}
function entry(id: number, data: Record<string, unknown>): ContentEntry {
return { id, data } as unknown as ContentEntry
}
describe('relationRowOf', () => {
it('builds the summary from the first field', () => {
const row = relationRowOf(entry(7, { name: 'Hall' }), 'venues', [field('name', 'text')])
expect(row.id).toBe(7)
expect(row.title).toBe('Hall')
expect(row.summary).toEqual({
id: 7,
content_type: 'venues',
first_field: { key: 'name', type: 'text', value: 'Hall' },
})
})
it('falls back to an empty text summary when the type has no fields', () => {
const row = relationRowOf(entry(3, {}), 'venues', [])
expect(row.summary.first_field).toEqual({ key: '', type: 'text', value: null })
expect(row.detail).toBe('')
})
it('uses null when the first field is absent from the data', () => {
const row = relationRowOf(entry(3, {}), 'venues', [field('name', 'text')])
expect(row.summary.first_field).toEqual({ key: 'name', type: 'text', value: null })
})
it('joins at most the first detail fields and skips empty ones', () => {
const fields = [
field('name', 'text'),
field('city', 'text'),
field('country', 'text'),
field('zip', 'text'),
]
const row = relationRowOf(
entry(1, { name: 'Hall', city: 'Paris', country: 'France', zip: '75000' }),
'venues',
fields,
)
expect(ROW_DETAIL_FIELDS).toBe(2)
expect(row.detail).toBe('Paris · France')
const sparse = relationRowOf(
entry(1, { name: 'Hall', city: '', country: 'France', zip: '75000' }),
'venues',
fields,
)
expect(sparse.detail).toBe('France')
})
})
@@ -0,0 +1,89 @@
import { describe, expect, it } from 'vitest'
import {
inverseNoun,
inverseSide,
kindFromInverseSide,
kindFromOwnerSide,
kindSentence,
ownerNoun,
ownerSide,
relationNames,
relationSample,
singularOf,
} from '@/lib/relationSentences'
import { RELATION_KINDS } from '@/lib/relationField'
const names = relationNames('Events', 'Venues', 'Venue')
describe('the names of both sides', () => {
it('draws the singular from the type name and the related singular from the field label', () => {
expect(names).toEqual({
ownerSingular: 'Event',
ownerPlural: 'Events',
relatedSingular: 'Venue',
relatedPlural: 'Venues',
})
})
it('removes only one final s and keeps one-letter names', () => {
expect(singularOf('Press mentions')).toBe('Press mention')
expect(singularOf('Glass')).toBe('Glas')
expect(singularOf('S')).toBe('S')
})
it('falls back when the related type is not chosen yet', () => {
expect(relationNames('Events', '', 'Place').relatedPlural).toBe('Places')
expect(relationNames('Events', 'Places', '').relatedSingular).toBe('Place')
expect(relationNames('', '', '').ownerSingular).toBe('Entry')
})
})
describe('the sentences of the cards', () => {
it.each([
['one_to_one', 'Each Event has one Venue, and each Venue has one Event.'],
['one_to_many', 'Each Event has one Venue. A Venue has many Events.'],
['many_to_many', 'Each Event has many Venues, and each Venue has many Events.'],
] as const)('reads %s as the design says', (kind, sentence) => {
expect(kindSentence(kind, names)).toBe(sentence)
})
})
describe('the preview', () => {
it.each([
['one_to_one', 'one', 'Venue', 'one', 'Event'],
['one_to_many', 'one', 'Venue', 'many', 'Events'],
['many_to_many', 'many', 'Venues', 'many', 'Events'],
] as const)('follows %s', (kind, owner, ownerWord, inverse, inverseWord) => {
expect(ownerSide(kind)).toBe(owner)
expect(ownerNoun(kind, names)).toBe(ownerWord)
expect(inverseSide(kind)).toBe(inverse)
expect(inverseNoun(kind, names)).toBe(inverseWord)
})
it('maps the selects of the sentences back to a kind', () => {
expect(kindFromOwnerSide('many', 'one_to_one')).toBe('many_to_many')
expect(kindFromOwnerSide('one', 'many_to_many')).toBe('one_to_many')
expect(kindFromOwnerSide('one', 'one_to_one')).toBe('one_to_one')
expect(kindFromInverseSide('one', 'many_to_many')).toBe('one_to_one')
expect(kindFromInverseSide('many', 'one_to_one')).toBe('one_to_many')
expect(kindFromInverseSide('many', 'many_to_many')).toBe('many_to_many')
})
it('keeps every kind stable through its own sides', () => {
for (const kind of RELATION_KINDS) {
expect(kindFromOwnerSide(ownerSide(kind), kind)).toBe(kind)
expect(kindFromInverseSide(inverseSide(kind), kind)).toBe(kind)
}
})
it('draws the example chips of the board', () => {
expect(relationSample('one_to_many')).toEqual({
ownerChips: ['Rue Verte hall'],
ownerMore: 0,
relatedChips: ['Open day', 'Lime plaster workshop'],
relatedMore: 1,
})
expect(relationSample('one_to_one').relatedChips).toEqual(['Open day'])
expect(relationSample('many_to_many').ownerChips).toHaveLength(2)
})
})
@@ -79,6 +79,7 @@ describe('create payload', () => {
min: null,
max: 80,
options: [],
relation: null,
},
{
key: 'starts_on',
@@ -90,6 +91,7 @@ describe('create payload', () => {
min: '2026-01-01',
max: '2027-12-31',
options: [],
relation: null,
},
{
key: 'online',
@@ -101,6 +103,7 @@ describe('create payload', () => {
min: null,
max: null,
options: [],
relation: null,
},
{
key: 'capacity',
@@ -112,6 +115,7 @@ describe('create payload', () => {
min: 1,
max: 5000,
options: [],
relation: null,
},
{
key: 'category',
@@ -123,6 +127,7 @@ describe('create payload', () => {
min: null,
max: null,
options: ['Talk', 'Workshop', 'Meetup'],
relation: null,
},
{
key: 'description',
@@ -134,12 +139,13 @@ describe('create payload', () => {
min: null,
max: 5000,
options: [],
relation: null,
},
],
})
})
it('has no icon key and exactly the nine field keys', () => {
it('has no icon key and exactly the ten field keys', () => {
const body = buildPayload(EVENTS)
expect(Object.keys(body).sort()).toEqual(['fields', 'key', 'name'])
@@ -151,6 +157,7 @@ describe('create payload', () => {
'max',
'min',
'options',
'relation',
'required',
'type',
'unique',
+1
View File
@@ -9,6 +9,7 @@ export function apiField(label: string, key: string, type: string, rest: object
min: null,
max: null,
options: null,
relation: null,
...rest,
}
}
+3
View File
@@ -1,4 +1,5 @@
import type { MediaMap } from '@/lib/mediaField'
import type { RelationDefinition, RelationMap } from '@/lib/relationField'
export interface BuiltinField {
key: string
@@ -10,6 +11,7 @@ export interface BuiltinField {
min: number | string | null
max: number | string | null
options: unknown[] | null
relation?: RelationDefinition | null
}
export interface ContentType {
@@ -27,6 +29,7 @@ export interface ContentEntry {
content_type: string
data: Record<string, unknown>
media?: MediaMap
relations?: RelationMap
created_by: number
updated_by: number
created_at: string
+64 -1
View File
@@ -3,19 +3,30 @@ import type { BuiltinField } from '@/lib/contentTypes'
import { fieldTypeSpec, type FieldCellKind } from '@/lib/fieldTypes'
import { formatDayValue } from '@/lib/entryValue'
import { isMissingImage, type MediaSummary } from '@/lib/mediaField'
import { isMissingRelation, relationIdsOf, type RelationSummary } from '@/lib/relationField'
import { formatAbsoluteDateFromIso } from '@/lib/relativeDate'
export { formatDayValue }
export type CellKind = 'empty' | FieldCellKind
export interface RelationChip {
id: number
label: string
missing: boolean
}
export interface CellView {
kind: CellKind
text: string
yes?: boolean
image?: MediaSummary
chips?: RelationChip[]
more?: number
}
export const RELATION_CHIPS_SHOWN = 2
export const EMPTY_TEXT = '–'
const EMPTY: CellView = { kind: 'empty', text: '' }
@@ -48,7 +59,57 @@ function thumbnailCell(value: unknown, image: MediaSummary | undefined): CellVie
}
}
export function describeCell(field: BuiltinField, value: unknown, image?: MediaSummary): CellView {
function summaryField(first: { key: string; type: string }): BuiltinField {
return {
key: first.key,
label: '',
type: first.type,
required: false,
unique: false,
default: null,
min: null,
max: null,
options: null,
}
}
export function relationLabel(summary: RelationSummary) {
if (isMissingRelation(summary)) {
return t('Entry no longer exists')
}
const first = summary.first_field
const cell = describeCell(summaryField(first), first.value)
return cell.kind === 'empty' || cell.kind === 'thumbnail' || cell.kind === 'relation'
? t('Entry {0}', [summary.id])
: plainCellText(cell)
}
function relationCell(value: unknown, summaries: RelationSummary[]): CellView {
const ids = relationIdsOf(value)
if (ids.length === 0) {
return EMPTY
}
const chips = ids.map((id): RelationChip => {
const summary = summaries.find((candidate) => candidate.id === id) ?? {
id,
missing: true as const,
}
return { id, label: relationLabel(summary), missing: isMissingRelation(summary) }
})
return {
kind: 'relation',
text: chips.map((chip) => chip.label).join(', '),
chips: chips.slice(0, RELATION_CHIPS_SHOWN),
more: Math.max(0, chips.length - RELATION_CHIPS_SHOWN),
}
}
export function describeCell(
field: BuiltinField,
value: unknown,
image?: MediaSummary,
relations: RelationSummary[] = [],
): CellView {
if (value === undefined || value === null || value === '') {
return EMPTY
}
@@ -56,6 +117,8 @@ export function describeCell(field: BuiltinField, value: unknown, image?: MediaS
switch (kind) {
case 'thumbnail':
return thumbnailCell(value, image)
case 'relation':
return relationCell(value, relations)
case 'boolean':
return { kind, text: '', yes: value === true }
case 'number':
+24 -1
View File
@@ -4,8 +4,22 @@ import { rangeHelp, uniqueHelp, type EntryRule } from '@/lib/entryMessages'
import { asBoolean, asNumber, asText, charCount, isBlank, isIsoDay } from '@/lib/entryValue'
import type { FieldType } from '@/lib/fieldTypes'
import { isMediaId, isMissingImage, type MediaSummary } from '@/lib/mediaField'
import {
relationInitial,
relationPayload,
relationViolation,
type RelationSummary,
} from '@/lib/relationField'
export type FieldControl = 'input' | 'markdown' | 'number' | 'switch' | 'date' | 'select' | 'media'
export type FieldControl =
| 'input'
| 'markdown'
| 'number'
| 'switch'
| 'date'
| 'select'
| 'media'
| 'relation'
export interface FieldCounter {
text: string
@@ -14,6 +28,7 @@ export interface FieldCounter {
export interface EntryContext {
image: MediaSummary | null
relations: RelationSummary[]
}
export interface EntryEditorSpec {
@@ -197,4 +212,12 @@ export const ENTRY_EDITORS: Record<FieldType, EntryEditorSpec> = {
help: () => t('One image from your library.'),
counter: noCounter,
},
relation: {
control: 'relation',
initial: relationInitial,
validate: relationViolation,
payload: relationPayload,
help: noHelp,
counter: noCounter,
},
}
+17 -3
View File
@@ -2,9 +2,10 @@ import { t } from '@/i18n'
import type { BuiltinField, ContentEntry } from '@/lib/contentTypes'
import { describeCell, plainCellText } from '@/lib/entryCells'
import { ruleMessage, type EntryRule } from '@/lib/entryMessages'
import { isBlank } from '@/lib/entryValue'
import { isBlank, sameValue } from '@/lib/entryValue'
import { fieldTypeSpec } from '@/lib/fieldTypes'
import { mediaOf, type MediaMap } from '@/lib/mediaField'
import { relationSummariesFor, type RelationSummaries } from '@/lib/relationField'
export type EntryValues = Record<string, unknown>
@@ -39,6 +40,17 @@ export function initialImages(fields: BuiltinField[], stored: ContentEntry | nul
return images
}
export function isRelationField(field: BuiltinField) {
return fieldTypeSpec(field.type).editor.control === 'relation'
}
export function initialRelations(
fields: BuiltinField[],
stored: ContentEntry | null,
): RelationSummaries {
return relationSummariesFor(fields, stored, isRelationField)
}
export function buildData(fields: BuiltinField[], values: EntryValues) {
return Object.fromEntries(
fields.map((field) => [
@@ -56,11 +68,13 @@ export function validateEntry(
fields: BuiltinField[],
values: EntryValues,
images: MediaMap = {},
relations: RelationSummaries = {},
): EntryIssues {
const issues: EntryIssues = {}
for (const field of fields) {
const rule = fieldTypeSpec(field.type).editor.validate(field, values[field.key], {
image: images[field.key] ?? null,
relations: relations[field.key] ?? [],
})
if (rule) {
issues[field.key] = issueFor(field, rule)
@@ -74,7 +88,7 @@ export function firstIssueKey(fields: BuiltinField[], issues: EntryIssues) {
}
export function valuesDiffer(fields: BuiltinField[], current: EntryValues, saved: EntryValues) {
return fields.some((field) => !Object.is(current[field.key], saved[field.key]))
return fields.some((field) => !sameValue(current[field.key], saved[field.key]))
}
export function carriesDefault(field: BuiltinField, value: unknown) {
@@ -91,7 +105,7 @@ export function entryTitle(fields: BuiltinField[], entry: ContentEntry | null) {
return entry ? t('Entry {0}', [entry.id]) : t('New entry')
}
const cell = describeCell(first, entry.data[first.key])
return cell.kind === 'empty' || cell.kind === 'thumbnail'
return cell.kind === 'empty' || cell.kind === 'thumbnail' || cell.kind === 'relation'
? t('Entry {0}', [entry.id])
: plainCellText(cell)
}
+6
View File
@@ -26,6 +26,8 @@ function requiredMessage(field: BuiltinField) {
return t('Choose yes or no for {0}.', [field.label])
case 'media':
return t('Pick an image for {0}.', [field.label])
case 'relation':
return t('Choose a {0}.', [field.label])
default:
return t('Fill in {0}.', [field.label])
}
@@ -43,6 +45,8 @@ function typeMessage(field: BuiltinField) {
return t('{0} must be one of the choices.', [field.label])
case 'media':
return t('{0} must be an image from the library.', [field.label])
case 'relation':
return t('{0} must point to an existing entry.', [field.label])
default:
return t('{0} must be text.', [field.label])
}
@@ -76,6 +80,8 @@ function uniqueMessage(field: BuiltinField) {
return t('Another entry already uses this choice for {0}.', [field.label])
case 'date':
return t('Another entry already uses this date for {0}.', [field.label])
case 'relation':
return t('That {0} is already used by another entry.', [field.label])
default:
return t('Another entry already uses this {0}. Enter a different one.', [field.label])
}
+10
View File
@@ -57,3 +57,13 @@ export function freeSentinel(taken: string[], base = '__none__') {
}
return sentinel
}
export function sameValue(left: unknown, right: unknown) {
if (Array.isArray(left) && Array.isArray(right)) {
return (
left.length === right.length &&
left.every((item, index) => Object.is(item, right[index]))
)
}
return Object.is(left, right)
}
+64 -1
View File
@@ -1,4 +1,4 @@
import { t } from '@/i18n'
import { formatNumber, t } from '@/i18n'
import { ENTRY_EDITORS, type EntryEditorSpec } from '@/lib/entryEditors'
export const FIELD_TYPES = [
@@ -9,6 +9,7 @@ export const FIELD_TYPES = [
'date',
'select',
'media',
'relation',
] as const
export type FieldType = (typeof FIELD_TYPES)[number]
@@ -21,6 +22,7 @@ export type FieldCellKind =
| 'date'
| 'choice'
| 'thumbnail'
| 'relation'
export interface FieldTypeSpec {
icon: string
@@ -28,6 +30,7 @@ export interface FieldTypeSpec {
description: () => string
cell: FieldCellKind
narrowColumn: boolean
wideColumn: boolean
alignEnd: boolean
supportsUnique: boolean
supportsLimits: boolean
@@ -35,6 +38,8 @@ export interface FieldTypeSpec {
supportsChoices: boolean
showsUnsupportedOptions: boolean
builderHint: (() => string) | null
noDefaultCause: ((label: string, total: number) => string) | null
holdsRelation: boolean
pairs: boolean
editor: EntryEditorSpec
}
@@ -48,6 +53,7 @@ export const FIELD_TYPE_SPECS: Record<FieldType, FieldTypeSpec> = {
description: () => t('Short text, like a title or a name'),
cell: 'text',
narrowColumn: false,
wideColumn: false,
alignEnd: false,
supportsUnique: true,
supportsLimits: true,
@@ -55,6 +61,8 @@ export const FIELD_TYPE_SPECS: Record<FieldType, FieldTypeSpec> = {
supportsChoices: false,
showsUnsupportedOptions: true,
builderHint: null,
noDefaultCause: null,
holdsRelation: false,
pairs: false,
editor: ENTRY_EDITORS.text,
},
@@ -64,6 +72,7 @@ export const FIELD_TYPE_SPECS: Record<FieldType, FieldTypeSpec> = {
description: () => t('Long text with formatting, written in Markdown'),
cell: 'richtext',
narrowColumn: false,
wideColumn: false,
alignEnd: false,
supportsUnique: false,
supportsLimits: true,
@@ -71,6 +80,8 @@ export const FIELD_TYPE_SPECS: Record<FieldType, FieldTypeSpec> = {
supportsChoices: false,
showsUnsupportedOptions: true,
builderHint: null,
noDefaultCause: null,
holdsRelation: false,
pairs: false,
editor: ENTRY_EDITORS.richtext,
},
@@ -80,6 +91,7 @@ export const FIELD_TYPE_SPECS: Record<FieldType, FieldTypeSpec> = {
description: () => t('Whole or decimal numbers'),
cell: 'number',
narrowColumn: true,
wideColumn: false,
alignEnd: true,
supportsUnique: true,
supportsLimits: true,
@@ -87,6 +99,8 @@ export const FIELD_TYPE_SPECS: Record<FieldType, FieldTypeSpec> = {
supportsChoices: false,
showsUnsupportedOptions: true,
builderHint: null,
noDefaultCause: null,
holdsRelation: false,
pairs: true,
editor: ENTRY_EDITORS.number,
},
@@ -96,6 +110,7 @@ export const FIELD_TYPE_SPECS: Record<FieldType, FieldTypeSpec> = {
description: () => t('An on or off switch'),
cell: 'boolean',
narrowColumn: true,
wideColumn: false,
alignEnd: false,
supportsUnique: false,
supportsLimits: false,
@@ -103,6 +118,8 @@ export const FIELD_TYPE_SPECS: Record<FieldType, FieldTypeSpec> = {
supportsChoices: false,
showsUnsupportedOptions: true,
builderHint: null,
noDefaultCause: null,
holdsRelation: false,
pairs: true,
editor: ENTRY_EDITORS.boolean,
},
@@ -112,6 +129,7 @@ export const FIELD_TYPE_SPECS: Record<FieldType, FieldTypeSpec> = {
description: () => t('A calendar day, without a time'),
cell: 'date',
narrowColumn: false,
wideColumn: false,
alignEnd: false,
supportsUnique: true,
supportsLimits: true,
@@ -119,6 +137,8 @@ export const FIELD_TYPE_SPECS: Record<FieldType, FieldTypeSpec> = {
supportsChoices: false,
showsUnsupportedOptions: true,
builderHint: null,
noDefaultCause: null,
holdsRelation: false,
pairs: true,
editor: ENTRY_EDITORS.date,
},
@@ -128,6 +148,7 @@ export const FIELD_TYPE_SPECS: Record<FieldType, FieldTypeSpec> = {
description: () => t('One option from a list you define'),
cell: 'choice',
narrowColumn: false,
wideColumn: false,
alignEnd: false,
supportsUnique: true,
supportsLimits: false,
@@ -135,6 +156,8 @@ export const FIELD_TYPE_SPECS: Record<FieldType, FieldTypeSpec> = {
supportsChoices: true,
showsUnsupportedOptions: true,
builderHint: null,
noDefaultCause: null,
holdsRelation: false,
pairs: false,
editor: ENTRY_EDITORS.select,
},
@@ -144,6 +167,7 @@ export const FIELD_TYPE_SPECS: Record<FieldType, FieldTypeSpec> = {
description: () => t('One image from your media library'),
cell: 'thumbnail',
narrowColumn: true,
wideColumn: false,
alignEnd: false,
supportsUnique: false,
supportsLimits: false,
@@ -154,9 +178,48 @@ export const FIELD_TYPE_SPECS: Record<FieldType, FieldTypeSpec> = {
t(
'Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version.',
),
noDefaultCause: (label, total) =>
total === 1
? t(
"A media field can't have a default, so the existing entry would have no image. Make {0} optional to add it.",
[label],
)
: t(
"A media field can't have a default, so the {0} existing entries would have no image. Make {1} optional to add it.",
[formatNumber(total), label],
),
holdsRelation: false,
pairs: false,
editor: ENTRY_EDITORS.media,
},
relation: {
icon: 'i-lucide-link',
label: () => t('Relation'),
description: () => t("Links to another type's entries"),
cell: 'relation',
narrowColumn: false,
wideColumn: true,
alignEnd: false,
supportsUnique: false,
supportsLimits: false,
supportsDefault: false,
supportsChoices: false,
showsUnsupportedOptions: false,
builderHint: null,
noDefaultCause: (label, total) =>
total === 1
? t(
"A relation can't have a default, so the existing entry would have no {0}. Make {0} optional to add it.",
[label],
)
: t(
"A relation can't have a default, so the {0} existing entries would have no {1}. Make {1} optional to add it.",
[formatNumber(total), label],
),
holdsRelation: true,
pairs: false,
editor: ENTRY_EDITORS.relation,
},
}
export function isFieldType(type: string): type is FieldType {
+3 -1
View File
@@ -51,7 +51,9 @@ export function usageEntryTitle(item: MediaUsageItem) {
},
first.value,
)
return cell.kind === 'empty' || cell.kind === 'thumbnail' ? fallback : plainCellText(cell)
return cell.kind === 'empty' || cell.kind === 'thumbnail' || cell.kind === 'relation'
? fallback
: plainCellText(cell)
}
function toEntry(item: MediaUsageItem): UsageEntry {
+170
View File
@@ -0,0 +1,170 @@
import type { BuiltinField, ContentEntry } from '@/lib/contentTypes'
import type { EntryRule } from '@/lib/entryMessages'
export const RELATION_KINDS = ['one_to_one', 'one_to_many', 'many_to_many'] as const
export type RelationKind = (typeof RELATION_KINDS)[number]
export const DEFAULT_RELATION_KIND: RelationKind = 'one_to_many'
export const RELATION_MAX = 50
export const RELATION_PAGE_SIZE = 25
const RELATION_ID_MAX = 4294967295
export interface RelationDefinition {
content_type: string
kind: RelationKind
}
export interface RelationFirstField {
key: string
type: string
value: unknown
}
export interface RelationTarget {
id: number
content_type: string
first_field: RelationFirstField
}
export interface MissingRelation {
id: number
missing: true
}
export type RelationSummary = RelationTarget | MissingRelation
export type RelationMap = Record<string, RelationSummary | RelationSummary[]>
export type RelationSummaries = Record<string, RelationSummary[]>
export interface RelationContext {
relations: RelationSummary[]
}
export function isMissingRelation(summary: RelationSummary): summary is MissingRelation {
return 'missing' in summary
}
export function isRelationKind(value: unknown): value is RelationKind {
return (RELATION_KINDS as readonly unknown[]).includes(value)
}
export function isRelationId(value: unknown): value is number {
return (
typeof value === 'number' &&
Number.isInteger(value) &&
value >= 1 &&
value <= RELATION_ID_MAX
)
}
export function holdsManyRelations(field: Pick<BuiltinField, 'relation'>) {
return field.relation?.kind === 'many_to_many'
}
export function emptyRelationValue(field: Pick<BuiltinField, 'relation'>) {
return holdsManyRelations(field) ? [] : null
}
export function relationIdsOf(value: unknown): number[] {
if (Array.isArray(value)) {
return value.filter(isRelationId)
}
return isRelationId(value) ? [value] : []
}
export function relationInitial(field: BuiltinField, stored: unknown, creating: boolean) {
if (creating) {
return emptyRelationValue(field)
}
if (holdsManyRelations(field)) {
return Array.isArray(stored) && stored.every(isRelationId) ? [...stored] : []
}
return isRelationId(stored) ? stored : null
}
function hasDuplicates(ids: number[]) {
return new Set(ids).size !== ids.length
}
function onlyMissing(ids: number[], summaries: RelationSummary[]) {
const gone = new Set(summaries.filter(isMissingRelation).map((summary) => summary.id))
return ids.length > 0 && ids.every((id) => gone.has(id))
}
function manyViolation(field: BuiltinField, value: unknown, context?: RelationContext) {
if (value === null || value === undefined) {
return field.required ? 'required' : null
}
if (!Array.isArray(value)) {
return 'type'
}
if (value.length === 0) {
return field.required ? 'required' : null
}
if (value.length > RELATION_MAX || !value.every(isRelationId) || hasDuplicates(value)) {
return 'type'
}
return field.required && onlyMissing(value, context?.relations ?? []) ? 'required' : null
}
function singleViolation(field: BuiltinField, value: unknown, context?: RelationContext) {
if (value === null || value === undefined) {
return field.required ? 'required' : null
}
if (!isRelationId(value)) {
return 'type'
}
return field.required && onlyMissing([value], context?.relations ?? []) ? 'required' : null
}
export function relationViolation(
field: BuiltinField,
value: unknown,
context?: RelationContext,
): EntryRule | null {
return holdsManyRelations(field)
? manyViolation(field, value, context)
: singleViolation(field, value, context)
}
export function relationPayload(field: BuiltinField, value: unknown) {
if (holdsManyRelations(field)) {
return Array.isArray(value) ? [...value] : []
}
return value === undefined ? null : value
}
export function summariesOf(
entry: Pick<ContentEntry, 'relations'> | null | undefined,
key: string,
): RelationSummary[] {
const found = entry?.relations?.[key]
if (found === undefined) {
return []
}
return Array.isArray(found) ? found : [found]
}
export function relationSummariesFor(
fields: BuiltinField[],
entry: ContentEntry | null,
isRelation: (field: BuiltinField) => boolean,
): RelationSummaries {
const result: RelationSummaries = {}
for (const field of fields) {
if (!isRelation(field)) {
continue
}
const stored = relationIdsOf(entry?.data[field.key])
const summaries = summariesOf(entry, field.key).filter((summary) =>
stored.includes(summary.id),
)
if (summaries.length > 0) {
result[field.key] = summaries
}
}
return result
}
+47
View File
@@ -0,0 +1,47 @@
import type { BuiltinField, ContentEntry } from '@/lib/contentTypes'
import { describeCell, isEmptyCell, plainCellText, relationLabel } from '@/lib/entryCells'
import type { RelationTarget } from '@/lib/relationField'
export const ROW_DETAIL_FIELDS = 2
const DETAIL_SEPARATOR = ' · '
const UNKNOWN_FIELD_TYPE = 'text'
const NO_TEXT_KINDS = ['thumbnail', 'relation']
export interface RelationRow {
id: number
title: string
detail: string
summary: RelationTarget
}
function summaryOf(entry: ContentEntry, targetKey: string, fields: BuiltinField[]): RelationTarget {
const first = fields[0]
return {
id: entry.id,
content_type: targetKey,
first_field: {
key: first?.key ?? '',
type: first?.type ?? UNKNOWN_FIELD_TYPE,
value: first ? (entry.data[first.key] ?? null) : null,
},
}
}
function detailOf(entry: ContentEntry, fields: BuiltinField[]) {
return fields
.slice(1, 1 + ROW_DETAIL_FIELDS)
.map((field) => describeCell(field, entry.data[field.key]))
.filter((cell) => !isEmptyCell(cell) && !NO_TEXT_KINDS.includes(cell.kind))
.map(plainCellText)
.join(DETAIL_SEPARATOR)
}
export function relationRowOf(
entry: ContentEntry,
targetKey: string,
fields: BuiltinField[],
): RelationRow {
const summary = summaryOf(entry, targetKey, fields)
return { id: entry.id, title: relationLabel(summary), detail: detailOf(entry, fields), summary }
}
Loaded 100 of 125 files, more files were not shown because too many files have changed in this diff. Show more