@mainsoft/agent-cms 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/LICENSE +21 -0
  3. package/README.md +359 -2
  4. package/TODO.md +178 -0
  5. package/UPGRADE-0.6.md +236 -0
  6. package/dist/agent.cjs +250 -0
  7. package/dist/agent.d.cts +88 -0
  8. package/dist/agent.d.ts +88 -0
  9. package/dist/agent.js +24 -0
  10. package/dist/ai.cjs +555 -0
  11. package/dist/ai.d.cts +48 -0
  12. package/dist/ai.d.ts +48 -0
  13. package/dist/ai.js +73 -0
  14. package/dist/bin.js +1556 -0
  15. package/dist/chunk-2NTK7H4W.js +10 -0
  16. package/dist/chunk-52NUUZC7.js +1446 -0
  17. package/dist/chunk-6K5ZTGHQ.js +30 -0
  18. package/dist/chunk-AKN7SUXU.js +281 -0
  19. package/dist/chunk-CRDW6Q72.js +188 -0
  20. package/dist/chunk-DD56PTZ4.js +78 -0
  21. package/dist/chunk-DOADAH4L.js +52 -0
  22. package/dist/chunk-EXV6JNLY.js +251 -0
  23. package/dist/chunk-IGL2V6US.js +324 -0
  24. package/dist/chunk-IW3D4I7Q.js +317 -0
  25. package/dist/chunk-OQ55GEF3.js +6 -0
  26. package/dist/chunk-QC2M4NZY.js +158 -0
  27. package/dist/chunk-QQV6VLYJ.js +204 -0
  28. package/dist/chunk-T66ZKBHF.js +25 -0
  29. package/dist/chunk-VICZ76TR.js +118 -0
  30. package/dist/chunk-Y63XQS2J.js +6 -0
  31. package/dist/cli.cjs +1596 -0
  32. package/dist/cli.d.cts +89 -0
  33. package/dist/cli.d.ts +89 -0
  34. package/dist/cli.js +534 -0
  35. package/dist/client.cjs +185 -0
  36. package/dist/client.d.cts +228 -0
  37. package/dist/client.d.ts +228 -0
  38. package/dist/client.js +13 -0
  39. package/dist/cms-BPp01z-8.d.ts +411 -0
  40. package/dist/cms-D6D89-qZ.d.cts +411 -0
  41. package/dist/config.cjs +61 -0
  42. package/dist/config.d.cts +36 -0
  43. package/dist/config.d.ts +36 -0
  44. package/dist/config.js +11 -0
  45. package/dist/diff.cjs +316 -0
  46. package/dist/diff.d.cts +122 -0
  47. package/dist/diff.d.ts +122 -0
  48. package/dist/diff.js +29 -0
  49. package/dist/drizzle-repo-B1rt7r4j.d.ts +90 -0
  50. package/dist/drizzle-repo-Cn-kL2FK.d.cts +90 -0
  51. package/dist/errors.cjs +193 -0
  52. package/dist/errors.d.cts +109 -0
  53. package/dist/errors.d.ts +109 -0
  54. package/dist/errors.js +16 -0
  55. package/dist/frontmatter.cjs +103 -0
  56. package/dist/frontmatter.d.cts +32 -0
  57. package/dist/frontmatter.d.ts +32 -0
  58. package/dist/frontmatter.js +9 -0
  59. package/dist/http.cjs +1105 -0
  60. package/dist/http.d.cts +75 -0
  61. package/dist/http.d.ts +75 -0
  62. package/dist/http.js +321 -0
  63. package/dist/index.cjs +3066 -0
  64. package/dist/index.d.cts +19 -0
  65. package/dist/index.d.ts +19 -0
  66. package/dist/index.js +263 -0
  67. package/dist/markdown.cjs +220 -0
  68. package/dist/markdown.d.cts +88 -0
  69. package/dist/markdown.d.ts +88 -0
  70. package/dist/markdown.js +23 -0
  71. package/dist/mcp.cjs +652 -0
  72. package/dist/mcp.d.cts +43 -0
  73. package/dist/mcp.d.ts +43 -0
  74. package/dist/mcp.js +26 -0
  75. package/dist/messages/en.cjs +76 -0
  76. package/dist/messages/en.d.cts +7 -0
  77. package/dist/messages/en.d.ts +7 -0
  78. package/dist/messages/en.js +7 -0
  79. package/dist/messages/ko.cjs +76 -0
  80. package/dist/messages/ko.d.cts +7 -0
  81. package/dist/messages/ko.d.ts +7 -0
  82. package/dist/messages/ko.js +53 -0
  83. package/dist/registry/cms-audit.json +25 -0
  84. package/dist/registry/cms-command.json +23 -0
  85. package/dist/registry/cms-doc-editor.json +36 -0
  86. package/dist/registry/cms-doc-list.json +29 -0
  87. package/dist/registry/cms-empty.json +22 -0
  88. package/dist/registry/cms-keys.json +29 -0
  89. package/dist/registry/cms-lib.json +33 -0
  90. package/dist/registry/cms-merge.json +26 -0
  91. package/dist/registry/cms-shell.json +22 -0
  92. package/dist/registry/cms-versions.json +26 -0
  93. package/dist/registry/registry.json +255 -0
  94. package/dist/repo-BWI2Pkrv.d.ts +162 -0
  95. package/dist/repo-CeDxUxO6.d.cts +162 -0
  96. package/dist/tables.cjs +356 -0
  97. package/dist/tables.d.cts +3515 -0
  98. package/dist/tables.d.ts +3515 -0
  99. package/dist/tables.js +35 -0
  100. package/dist/tools.cjs +420 -0
  101. package/dist/tools.d.cts +27 -0
  102. package/dist/tools.d.ts +27 -0
  103. package/dist/tools.js +18 -0
  104. package/dist/types.cjs +226 -0
  105. package/dist/types.d.cts +286 -0
  106. package/dist/types.d.ts +286 -0
  107. package/dist/types.js +28 -0
  108. package/package.json +277 -4
@@ -0,0 +1,26 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "cms-merge",
4
+ "type": "registry:component",
5
+ "title": "Merge after a conflict",
6
+ "description": "Three-way merge when someone saved first: what merged automatically, and theirs, mine or both for each conflict.",
7
+ "dependencies": [
8
+ "@mainsoft/agent-cms",
9
+ "lucide-react"
10
+ ],
11
+ "registryDependencies": [
12
+ "badge",
13
+ "button",
14
+ "label",
15
+ "radio-group",
16
+ "table",
17
+ "cms-lib"
18
+ ],
19
+ "files": [
20
+ {
21
+ "path": "registry/cms/cms-merge.tsx",
22
+ "type": "registry:component",
23
+ "content": "// agent-cms registry: cms-merge (0.6.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// Someone saved first. Shows what merged by itself and, for each place both\n// sides changed, lets you pick theirs, mine or both (body) / theirs or mine\n// (other fields). \"Save merged\" saves on top of their version; if they saved\n// yet again, the merge starts over with the newest copy.\n\"use client\";\n\nimport * as React from \"react\";\nimport { GitMerge } from \"lucide-react\";\nimport type { CmsDoc } from \"@mainsoft/agent-cms/types\";\nimport { diffWords, mergeDocs, resolveDocMerge, type DocLike, type MergeChoice } from \"@mainsoft/agent-cms/diff\";\nimport { isCmsRemoteError } from \"@mainsoft/agent-cms/client\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { Button } from \"@/components/ui/button\";\nimport { Label } from \"@/components/ui/label\";\nimport { RadioGroup, RadioGroupItem } from \"@/components/ui/radio-group\";\nimport { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from \"@/components/ui/table\";\nimport { cn } from \"@/lib/utils\";\nimport { errorMessage, type MessageKey } from \"./cms-messages\";\nimport { Avatar, PageHeader, StatusText, Who } from \"./cms-parts\";\nimport { contentOf, toInput, useCms } from \"./use-cms\";\n\nexport interface CmsMergeProps {\n collection: string;\n slug: string;\n /** The version both edits started from (`version(c, s, baseVersion).snapshot`). */\n base: DocLike;\n baseVersion: number;\n /** The editor's content. */\n mine: DocLike;\n /** The copy someone else saved (`CmsRemoteError.current` of the 409). */\n theirs: CmsDoc;\n /** Saved: the new document. */\n onSaved: (doc: CmsDoc) => void;\n /** Back to the editor without saving. */\n onCancel: () => void;\n /** Breadcrumb before the title (e.g. the collection and document). */\n crumbs?: React.ReactNode[];\n className?: string;\n}\n\nconst FIELD_LABEL: Record<string, MessageKey> = { title: \"field_title\", slug: \"field_slug\", summary: \"field_summary\", category: \"field_category\", keywords: \"field_keywords\", body: \"field_body\" };\n\nconst show = (v: unknown, empty: string): string => (v === undefined || v === null || v === \"\" ? empty : Array.isArray(v) ? v.join(\", \") : typeof v === \"object\" ? JSON.stringify(v) : String(v));\n\n/** Where a conflict sits: the nearest heading above and the line in the merged text. */\nfunction locate(chunks: ReturnType<typeof mergeDocs>[\"body\"][\"chunks\"], id: number): { heading: string | null; line: number } {\n let line = 1;\n let heading: string | null = null;\n for (const c of chunks) {\n if (c.t === \"conflict\" && c.id === id) return { heading, line };\n const lines = c.t === \"ok\" ? c.lines : c.theirs;\n for (const l of lines) if (/^#{1,6}\\s/.test(l)) heading = l;\n line += lines.length;\n }\n return { heading, line };\n}\n\nexport function CmsMerge({ collection, slug, base: base0, baseVersion: baseVersion0, mine: mine0, theirs: theirs0, onSaved, onCancel, crumbs, className }: CmsMergeProps) {\n const { client, t } = useCms();\n const [round, setRound] = React.useState({ base: contentOf(base0), baseVersion: baseVersion0, mine: contentOf(mine0), theirs: theirs0, again: false });\n const m = React.useMemo(() => mergeDocs(round.base, round.mine, contentOf(round.theirs)), [round]);\n const [body, setBody] = React.useState<Record<number, MergeChoice>>({});\n const [fields, setFields] = React.useState<Record<string, \"mine\" | \"theirs\">>({});\n const [busy, setBusy] = React.useState(false);\n const [error, setError] = React.useState<string | null>(null);\n\n const total = m.body.conflicts.length + m.fieldConflicts.length;\n const chosen = m.body.conflicts.filter((c) => body[c.id]).length + m.fieldConflicts.filter((f) => fields[f.path]).length;\n const theirsWho = round.theirs.updatedBy ?? \"\";\n const theirsKind = round.theirs.updatedByKind;\n\n const auto = React.useMemo(() => {\n const rows: { where: string; from: \"mine\" | \"theirs\" | \"both\"; content: React.ReactNode }[] = [];\n for (const a of m.autoMerged) {\n if (a.path === \"body\") continue;\n const label = FIELD_LABEL[a.path] ? t(FIELD_LABEL[a.path]) : a.path.replace(/^fields\\./, \"\");\n const get = (d: DocLike) => (a.path.startsWith(\"fields.\") ? a.path.slice(7).split(\".\").reduce<unknown>((o, k) => (o && typeof o === \"object\" ? (o as Record<string, unknown>)[k] : undefined), d.fields) : (d as unknown as Record<string, unknown>)[a.path]);\n const before = show(get(round.base), \"\");\n const after = show(get(m.merged), t(\"merge_field_empty\"));\n rows.push({ where: label, from: a.from, content: <WordIns a={before} b={after} /> });\n }\n let line = 1;\n let heading: string | null = null;\n for (const c of m.body.chunks) {\n const lines = c.t === \"ok\" ? c.lines : c.theirs;\n if (c.t === \"ok\" && c.from !== \"base\") {\n rows.push({\n where: heading ? t(\"merge_location\", { heading, line }) : t(\"merge_line\", { line }),\n from: c.from,\n content: <span className=\"whitespace-pre-wrap\">{c.lines.join(\"\\n\")}</span>,\n });\n }\n for (const l of lines) if (/^#{1,6}\\s/.test(l)) heading = l;\n line += lines.length;\n }\n return rows;\n }, [m, round.base, t]);\n\n const save = async () => {\n if (chosen < total) {\n setError(t(\"merge_pick_all\"));\n return;\n }\n setBusy(true);\n setError(null);\n const merged = resolveDocMerge(m, { body, fields });\n try {\n const doc = await client.update(collection, slug, toInput(merged, round.theirs.fields), { expectedVersion: round.theirs.version });\n onSaved(doc);\n } catch (e) {\n if (isCmsRemoteError(e) && e.code === \"conflict_version\" && e.current) {\n // They saved again: merge what we resolved against the newest copy.\n setRound({ base: contentOf(round.theirs), baseVersion: round.theirs.version, mine: merged, theirs: e.current as CmsDoc, again: true });\n setBody({});\n setFields({});\n } else setError(errorMessage(e, t));\n } finally {\n setBusy(false);\n }\n };\n\n let index = 0;\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n <PageHeader title={t(\"merge\")} crumbs={crumbs}>\n <Button type=\"button\" variant=\"ghost\" onClick={onCancel}>\n {t(\"cancel\")}\n </Button>\n <Button type=\"button\" onClick={() => void save()} disabled={busy}>\n {t(\"merge_save\")}\n </Button>\n </PageHeader>\n <div className=\"flex max-w-4xl flex-col gap-3.5 px-4 py-4 md:px-6\">\n <div role=\"status\" className=\"flex flex-wrap items-center gap-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2.5 text-sm text-amber-950\">\n <GitMerge aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>{round.again ? t(\"merge_again\", { who: theirsWho, version: round.theirs.version }) : t(\"merge_banner\", { who: theirsWho, version: round.theirs.version })}</span>\n <span className=\"flex-1\" />\n <span className=\"text-xs\">{t(\"merge_counts\", { auto: auto.length, conflicts: total })}</span>\n </div>\n {error ? <StatusText tone=\"error\">{error}</StatusText> : null}\n\n {m.body.conflicts.map((c) => {\n index++;\n const loc = locate(m.body.chunks, c.id);\n const name = `cms-merge-body-${c.id}`;\n const titleId = `${name}-title`;\n return (\n <section key={`b${c.id}`} aria-labelledby={titleId} className=\"rounded-lg border p-3.5\">\n <div className=\"mb-2 flex flex-wrap items-center gap-2\">\n <Badge id={titleId} variant=\"outline\" className=\"border-red-200 bg-red-50 text-red-700\">\n {t(\"merge_choose\", { i: index, n: total })}\n </Badge>\n <span className=\"font-mono text-xs text-muted-foreground\">{loc.heading ? t(\"merge_location\", { heading: loc.heading, line: loc.line }) : t(\"merge_line\", { line: loc.line })}</span>\n </div>\n <div className=\"mb-1 text-xs text-muted-foreground\">{t(\"merge_base\", { version: round.baseVersion })}</div>\n <pre className=\"mb-3 whitespace-pre-wrap rounded-md bg-muted/50 px-2.5 py-1.5 font-mono text-xs text-muted-foreground\">{c.base.join(\"\\n\") || t(\"merge_field_empty\")}</pre>\n <RadioGroup aria-labelledby={titleId} value={body[c.id] ?? \"\"} onValueChange={(v) => setBody((b) => ({ ...b, [c.id]: v as MergeChoice }))} className=\"grid gap-2 md:grid-cols-3\">\n {(\n [\n { v: \"theirs\", head: <><Avatar kind={theirsKind} label={theirsWho} />{t(\"merge_theirs\", { who: theirsWho, version: round.theirs.version })}</>, lines: c.theirs },\n { v: \"mine\", head: <>{t(\"merge_mine\")}</>, lines: c.mine },\n { v: \"both\", head: <>{t(\"merge_both\")}</>, lines: [...c.theirs, ...c.mine] },\n ] as const\n ).map((o) => (\n <Option key={o.v} id={`${name}-${o.v}`} value={o.v} selected={body[c.id] === o.v} head={o.head}>\n {o.lines.join(\"\\n\") || t(\"merge_field_empty\")}\n </Option>\n ))}\n </RadioGroup>\n </section>\n );\n })}\n\n {m.fieldConflicts.map((f) => {\n index++;\n const name = `cms-merge-f-${f.path.replace(/[^a-z0-9_-]/gi, \"-\")}`;\n const titleId = `${name}-title`;\n const label = FIELD_LABEL[f.path] ? t(FIELD_LABEL[f.path]) : f.path.replace(/^fields\\./, \"\");\n return (\n <section key={f.path} aria-labelledby={titleId} className=\"rounded-lg border p-3.5\">\n <div className=\"mb-2 flex flex-wrap items-center gap-2\">\n <Badge variant=\"outline\" className=\"border-red-200 bg-red-50 text-red-700\">\n {t(\"merge_choose\", { i: index, n: total })}\n </Badge>\n <span id={titleId} className=\"text-sm font-medium\">\n {label}\n </span>\n </div>\n <div className=\"mb-1 text-xs text-muted-foreground\">{t(\"merge_base\", { version: round.baseVersion })}</div>\n <div className=\"mb-3 rounded-md bg-muted/50 px-2.5 py-1.5 text-xs text-muted-foreground\">{show(f.base, t(\"merge_field_empty\"))}</div>\n <RadioGroup aria-labelledby={titleId} value={fields[f.path] ?? \"\"} onValueChange={(v) => setFields((x) => ({ ...x, [f.path]: v as \"mine\" | \"theirs\" }))} className=\"grid gap-2 md:grid-cols-2\">\n <Option id={`${name}-theirs`} value=\"theirs\" selected={fields[f.path] === \"theirs\"} head={<><Avatar kind={theirsKind} label={theirsWho} />{t(\"merge_theirs\", { who: theirsWho, version: round.theirs.version })}</>}>\n {show(f.theirs, t(\"merge_field_empty\"))}\n </Option>\n <Option id={`${name}-mine`} value=\"mine\" selected={fields[f.path] === \"mine\"} head={<>{t(\"merge_mine\")}</>}>\n {show(f.mine, t(\"merge_field_empty\"))}\n </Option>\n </RadioGroup>\n </section>\n );\n })}\n\n {auto.length ? (\n <section aria-label={t(\"merge_auto\")} className=\"rounded-lg border\">\n <Table>\n <TableHeader>\n <TableRow>\n <TableHead>{t(\"merge_auto\")}</TableHead>\n <TableHead>{t(\"merge_whose\")}</TableHead>\n <TableHead>{t(\"merge_content\")}</TableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {auto.map((r, i) => (\n <TableRow key={i}>\n <TableCell className=\"whitespace-nowrap align-top text-xs\">{r.where}</TableCell>\n <TableCell className=\"whitespace-nowrap align-top text-sm\">\n {r.from === \"theirs\" ? <Who kind={theirsKind} label={theirsWho} /> : r.from === \"mine\" ? t(\"merge_mine\") : t(\"merge_from_both\")}\n </TableCell>\n <TableCell className=\"align-top text-sm\">{r.content}</TableCell>\n </TableRow>\n ))}\n </TableBody>\n </Table>\n </section>\n ) : null}\n </div>\n </div>\n );\n}\n\nfunction Option({ id, value, selected, head, children }: { id: string; value: string; selected: boolean; head: React.ReactNode; children: React.ReactNode }) {\n return (\n <div className={cn(\"flex flex-col gap-1.5 rounded-md border p-2.5\", selected && \"border-foreground ring-1 ring-foreground\")}>\n <div className=\"flex items-center gap-2\">\n <RadioGroupItem id={id} value={value} />\n <Label htmlFor={id} className=\"flex items-center gap-1.5 text-sm font-medium\">\n {head}\n </Label>\n </div>\n <pre className=\"whitespace-pre-wrap font-mono text-xs\">{children}</pre>\n </div>\n );\n}\n\nfunction WordIns({ a, b }: { a: string; b: string }) {\n return (\n <>\n {diffWords(a, b).map((p, i) =>\n p.t === \"del\" ? null : p.t === \"ins\" ? (\n <ins key={i} className=\"bg-green-200 no-underline\">\n {p.v}\n </ins>\n ) : (\n <React.Fragment key={i}>{p.v}</React.Fragment>\n )\n )}\n </>\n );\n}\n"
24
+ }
25
+ ]
26
+ }
@@ -0,0 +1,22 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "cms-shell",
4
+ "type": "registry:component",
5
+ "title": "Admin layout",
6
+ "description": "Sidebar with collections, API keys and audit log, plus extraNav for your app's own screens. A sheet menu under 768px.",
7
+ "dependencies": [
8
+ "@mainsoft/agent-cms",
9
+ "lucide-react"
10
+ ],
11
+ "registryDependencies": [
12
+ "sheet",
13
+ "cms-lib"
14
+ ],
15
+ "files": [
16
+ {
17
+ "path": "registry/cms/cms-shell.tsx",
18
+ "type": "registry:component",
19
+ "content": "// agent-cms registry: cms-shell (0.6.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// The admin layout: a sidebar with the collections you may read, the\n// operations screens (API keys, audit log, admins only) and `extraNav`, the\n// place for your app's own screens. Under 768px the sidebar opens in a sheet.\n\"use client\";\n\nimport * as React from \"react\";\nimport { BookOpen, KeyRound, ScrollText, Search, FileText } from \"lucide-react\";\nimport { Sheet, SheetContent, SheetDescription, SheetTitle } from \"@/components/ui/sheet\";\nimport { cn } from \"@/lib/utils\";\nimport { ShellNavContext, useCms } from \"./use-cms\";\n\nexport interface CmsNavItem {\n label: string;\n href: string;\n badge?: React.ReactNode;\n icon?: React.ReactNode;\n}\n\nexport interface CmsNavGroup {\n label: string;\n items: CmsNavItem[];\n}\n\nexport interface CmsLinkProps {\n href: string;\n className?: string;\n children: React.ReactNode;\n \"aria-current\"?: \"page\" | undefined;\n onClick?: () => void;\n}\n\nexport type CmsShellTarget = { kind: \"collection\"; slug: string } | { kind: \"keys\" } | { kind: \"audit\" };\n\nexport interface CmsShellProps {\n children?: React.ReactNode;\n /** Brand text on top of the sidebar. Default \"Admin\". */\n title?: React.ReactNode;\n /** Brand mark (logo) before the title. */\n logo?: React.ReactNode;\n /** The collection shown now (highlighted). */\n activeCollection?: string;\n /** The current path; highlights the ops or `extraNav` link with this href. */\n activeHref?: string;\n /** Where the admin pages live, for the default links. Default \"/admin\". */\n basePath?: string;\n /** Override the link of a sidebar entry. Default `${basePath}/<collection>`, `${basePath}/keys`, `${basePath}/audit`. */\n hrefFor?: (target: CmsShellTarget) => string;\n /** Your app's own screens, shown under the operations section. */\n extraNav?: CmsNavGroup[];\n /** Show the search button (pair it with <CmsCommand>). */\n onSearch?: () => void;\n /** Render links with your router, e.g. `LinkComponent={Link}` from next/link. Default `<a>`. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n LinkComponent?: React.ComponentType<CmsLinkProps> | React.ComponentType<any>;\n /** Full control over links (wins over LinkComponent). */\n renderLink?: (props: CmsLinkProps) => React.ReactNode;\n /** Item counts beside collections; default: the \"all\" count from `counts()` for collections you can edit. */\n counts?: Record<string, number>;\n className?: string;\n}\n\nexport function CmsShell({ children, title, logo, activeCollection, activeHref, basePath = \"/admin\", hrefFor, extraNav, onSearch, LinkComponent, renderLink, counts, className }: CmsShellProps) {\n const { t, me, client } = useCms();\n const [open, setOpen] = React.useState(false);\n const [loaded, setLoaded] = React.useState<Record<string, number>>({});\n\n React.useEffect(() => {\n if (counts || !me) return;\n let live = true;\n void Promise.all(\n me.collections\n .filter((c) => c.canWrite)\n .map((c) =>\n client.counts(c.slug).then(\n (n) => [c.slug, n.all] as const,\n () => null\n )\n )\n ).then((rows) => {\n if (live) setLoaded(Object.fromEntries(rows.filter((r): r is readonly [string, number] => !!r)));\n });\n return () => {\n live = false;\n };\n }, [client, me, counts]);\n const shown = counts ?? loaded;\n\n const href = (target: CmsShellTarget) =>\n hrefFor?.(target) ?? (target.kind === \"collection\" ? `${basePath}/${encodeURIComponent(target.slug)}` : `${basePath}/${target.kind}`);\n\n const link = (p: CmsLinkProps) => {\n if (renderLink) return renderLink(p);\n const L = LinkComponent;\n if (L) return <L {...p} />;\n return (\n <a href={p.href} className={p.className} aria-current={p[\"aria-current\"]} onClick={p.onClick}>\n {p.children}\n </a>\n );\n };\n\n const navClass = (active: boolean) =>\n cn(\n \"flex h-8 items-center gap-2 rounded-md px-2 text-sm text-foreground/80 outline-none hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring\",\n active && \"bg-accent font-medium text-accent-foreground\"\n );\n\n const close = () => setOpen(false);\n\n const nav = (\n <nav aria-label={t(\"nav_label\")} className=\"flex flex-col gap-0.5 text-sm\">\n {onSearch ? (\n <button\n type=\"button\"\n onClick={() => {\n close();\n onSearch();\n }}\n className=\"mb-3 flex h-8 items-center gap-2 rounded-md border bg-background px-2 text-sm text-muted-foreground outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <Search aria-hidden className=\"h-4 w-4\" />\n <span className=\"flex-1 text-left\">{t(\"search\")}</span>\n <kbd className=\"rounded border border-b-2 px-1 font-mono text-[11px]\">⌘K</kbd>\n </button>\n ) : null}\n <h2 className=\"px-2 pb-1 pt-2 text-xs font-medium text-muted-foreground\">{t(\"nav_collections\")}</h2>\n <ul className=\"flex flex-col gap-0.5\">\n {(me?.collections ?? []).map((c) => {\n const active = c.slug === activeCollection;\n return (\n <li key={c.slug}>\n {link({\n href: href({ kind: \"collection\", slug: c.slug }),\n className: navClass(active),\n \"aria-current\": active ? \"page\" : undefined,\n onClick: close,\n children: (\n <>\n <BookOpen aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span className=\"flex-1 truncate\">{c.label}</span>\n {shown[c.slug] !== undefined ? <span className=\"text-xs tabular-nums text-muted-foreground\">{shown[c.slug]}</span> : null}\n </>\n ),\n })}\n </li>\n );\n })}\n </ul>\n {me?.isAdmin ? (\n <>\n <h2 className=\"px-2 pb-1 pt-4 text-xs font-medium text-muted-foreground\">{t(\"nav_ops\")}</h2>\n <ul className=\"flex flex-col gap-0.5\">\n {(\n [\n { kind: \"keys\", label: t(\"nav_keys\"), Icon: KeyRound },\n { kind: \"audit\", label: t(\"nav_audit\"), Icon: ScrollText },\n ] as const\n ).map(({ kind, label, Icon }) => {\n const h = href({ kind });\n const active = activeHref === h;\n return (\n <li key={kind}>\n {link({\n href: h,\n className: navClass(active),\n \"aria-current\": active ? \"page\" : undefined,\n onClick: close,\n children: (\n <>\n <Icon aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span className=\"flex-1 truncate\">{label}</span>\n </>\n ),\n })}\n </li>\n );\n })}\n </ul>\n </>\n ) : null}\n {(extraNav ?? []).map((g, gi) => (\n <div key={gi} data-cms-extra-nav=\"\">\n <h2 className=\"px-2 pb-1 pt-4 text-xs font-medium text-muted-foreground\">{g.label}</h2>\n <ul className=\"flex flex-col gap-0.5\">\n {g.items.map((it) => {\n const active = activeHref === it.href;\n return (\n <li key={it.href}>\n {link({\n href: it.href,\n className: navClass(active),\n \"aria-current\": active ? \"page\" : undefined,\n onClick: close,\n children: (\n <>\n {it.icon ?? <FileText aria-hidden className=\"h-4 w-4 shrink-0\" />}\n <span className=\"flex-1 truncate\">{it.label}</span>\n {it.badge !== undefined && it.badge !== null ? <span className=\"text-xs tabular-nums text-muted-foreground\">{it.badge}</span> : null}\n </>\n ),\n })}\n </li>\n );\n })}\n </ul>\n </div>\n ))}\n </nav>\n );\n\n const brand = (\n <div className=\"mb-4 flex items-center gap-2 px-2 font-semibold\">\n {logo}\n <span className=\"truncate\">{title ?? t(\"shell_title\")}</span>\n </div>\n );\n\n const navCtx = React.useMemo(() => ({ openNav: () => setOpen(true) }), []);\n\n return (\n <ShellNavContext.Provider value={navCtx}>\n <div className={cn(\"flex min-h-screen bg-background text-foreground\", className)}>\n <aside className=\"sticky top-0 hidden h-screen w-60 shrink-0 overflow-y-auto border-r bg-muted/30 p-3 md:block\">\n {brand}\n {nav}\n </aside>\n <Sheet open={open} onOpenChange={setOpen}>\n <SheetContent side=\"left\" className=\"w-72 overflow-y-auto p-3\">\n <SheetTitle className=\"sr-only\">{t(\"menu\")}</SheetTitle>\n <SheetDescription className=\"sr-only\">{t(\"nav_label\")}</SheetDescription>\n {brand}\n {nav}\n </SheetContent>\n </Sheet>\n <main className=\"flex min-w-0 flex-1 flex-col\">{children}</main>\n </div>\n </ShellNavContext.Provider>\n );\n}\n"
20
+ }
21
+ ]
22
+ }
@@ -0,0 +1,26 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "cms-versions",
4
+ "type": "registry:component",
5
+ "title": "Version history",
6
+ "description": "Versions with author, note and changed fields; compare any two side by side or unified with word highlights; restore or publish a version.",
7
+ "dependencies": [
8
+ "@mainsoft/agent-cms",
9
+ "lucide-react"
10
+ ],
11
+ "registryDependencies": [
12
+ "badge",
13
+ "button",
14
+ "dialog",
15
+ "label",
16
+ "select",
17
+ "cms-lib"
18
+ ],
19
+ "files": [
20
+ {
21
+ "path": "registry/cms/cms-versions.tsx",
22
+ "type": "registry:component",
23
+ "content": "// agent-cms registry: cms-versions (0.6.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// Version history of one document: who saved what (agent or person, note,\n// published marker, changed fields), a compare of any two versions (side by\n// side or unified, word-level highlight), restore and publish a version.\n\"use client\";\n\nimport * as React from \"react\";\nimport { ArrowLeft, ArrowRight, ChevronLeft, RotateCcw } from \"lucide-react\";\nimport { diffWords, type Hunk, type HunkLine } from \"@mainsoft/agent-cms/diff\";\nimport type { CmsDoc, VersionSummary } from \"@mainsoft/agent-cms/types\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { Button } from \"@/components/ui/button\";\nimport { Label } from \"@/components/ui/label\";\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from \"@/components/ui/select\";\nimport { cn } from \"@/lib/utils\";\nimport { errorMessage, type MessageKey } from \"./cms-messages\";\nimport { ConfirmDialog, PageHeader, Segmented, StateBadge, StatusText, Who } from \"./cms-parts\";\nimport { relativeTime, useAsync, useCms, useIsMobile, useLocalStorage } from \"./use-cms\";\n\ntype DocDiff = Awaited<ReturnType<import(\"@mainsoft/agent-cms/client\").RestClient[\"diff\"]>>;\n\nexport interface CmsVersionsProps {\n collection: string;\n slug: string;\n /** \"Back to editing\". */\n onBack?: () => void;\n /** After a restore or publish. */\n onChanged?: (doc: CmsDoc) => void;\n className?: string;\n}\n\nconst FIELD_LABEL: Record<string, MessageKey> = { title: \"field_title\", slug: \"field_slug\", summary: \"field_summary\", category: \"field_category\", keywords: \"field_keywords\", body: \"field_body\" };\nconst show = (v: unknown): string => (v === undefined || v === null ? \"\" : Array.isArray(v) ? v.join(\", \") : typeof v === \"object\" ? JSON.stringify(v) : String(v));\n\n/** Pair the removed and added lines of a hunk row by row (for side by side and word highlight). */\ntype Row = { t: \"ctx\"; a: HunkLine; b: HunkLine } | { t: \"chg\"; a: HunkLine | null; b: HunkLine | null };\nfunction rowsOf(h: Hunk): Row[] {\n const out: Row[] = [];\n let dels: HunkLine[] = [];\n let adds: HunkLine[] = [];\n const flush = () => {\n for (let i = 0; i < Math.max(dels.length, adds.length); i++) out.push({ t: \"chg\", a: dels[i] ?? null, b: adds[i] ?? null });\n dels = [];\n adds = [];\n };\n for (const l of h.lines) {\n if (l.t === \"-\") dels.push(l);\n else if (l.t === \"+\") adds.push(l);\n else {\n flush();\n out.push({ t: \"ctx\", a: l, b: l });\n }\n }\n flush();\n return out;\n}\n\nfunction Words({ a, b, side }: { a: string; b: string; side: \"a\" | \"b\" }) {\n return (\n <>\n {diffWords(a, b).map((p, i) =>\n p.t === \"eq\" ? (\n <React.Fragment key={i}>{p.v}</React.Fragment>\n ) : p.t === \"del\" && side === \"a\" ? (\n <del key={i} className=\"bg-red-200 no-underline\">\n {p.v}\n </del>\n ) : p.t === \"ins\" && side === \"b\" ? (\n <ins key={i} className=\"bg-green-200 no-underline\">\n {p.v}\n </ins>\n ) : null\n )}\n </>\n );\n}\n\nfunction headingBefore(body: string | undefined, line: number): string | null {\n if (!body) return null;\n const lines = body.split(\"\\n\").slice(0, Math.max(0, line - 1));\n for (let i = lines.length - 1; i >= 0; i--) if (/^#{1,6}\\s/.test(lines[i])) return lines[i];\n return null;\n}\n\nexport function CmsVersions({ collection, slug, onBack, onChanged, className }: CmsVersionsProps) {\n const { client, t, locale } = useCms();\n const mobile = useIsMobile();\n const schema = useAsync(() => client.schema(collection), [client, collection]);\n const list = useAsync(() => client.versions(collection, slug), [client, collection, slug]);\n const versions = list.data ?? [];\n const latest = versions[0]?.version ?? 0;\n const publishedV = versions.find((v) => v.published)?.version ?? null;\n\n const [to, setTo] = React.useState<number | null>(null);\n const [from, setFrom] = React.useState<number | null>(null);\n const [savedView, setView] = useLocalStorage<\"split\" | \"unified\">(\"agent-cms:diff-view\", \"split\");\n const view = mobile ? \"unified\" : savedView;\n const [confirm, setConfirm] = React.useState<\"restore\" | null>(null);\n const [busy, setBusy] = React.useState(false);\n const [status, setStatus] = React.useState<{ text: string; tone: \"ok\" | \"error\" } | null>(null);\n\n // Default: latest against the published version (or the one before).\n React.useEffect(() => {\n if (!versions.length || to !== null) return;\n const b = versions[0].version;\n const a = publishedV !== null && publishedV !== b ? publishedV : (versions[1]?.version ?? b);\n setTo(b);\n setFrom(a);\n }, [versions, to, publishedV]);\n\n const diff = useAsync<{ d: DocDiff; body?: string } | null>(\n async () => {\n if (from === null || to === null) return null;\n const [d, v] = await Promise.all([client.diff(collection, slug, from, to), client.version(collection, slug, to).catch(() => null)]);\n return { d, body: v?.snapshot.body };\n },\n [client, collection, slug, from, to]\n );\n\n const pick = (v: VersionSummary) => {\n setTo(v.version);\n const idx = versions.findIndex((x) => x.version === v.version);\n const prev = versions[idx + 1]?.version;\n setFrom(publishedV !== null && publishedV < v.version ? publishedV : (prev ?? v.version));\n };\n\n const run = async (what: \"restore\" | \"publish\") => {\n if (from === null || to === null) return;\n setBusy(true);\n setStatus(null);\n try {\n const d = what === \"restore\" ? await client.restore(collection, slug, from, { expectedVersion: latest }) : await client.publish(collection, slug, { version: to, expectedVersion: latest });\n setStatus({ text: what === \"restore\" ? t(\"restored\", { version: d.version }) : t(\"published_v\", { version: to }), tone: \"ok\" });\n setConfirm(null);\n setTo(null);\n list.reload();\n onChanged?.(d);\n } catch (e) {\n setStatus({ text: errorMessage(e, t), tone: \"error\" });\n } finally {\n setBusy(false);\n }\n };\n\n const canWrite = schema.data?.canWrite ?? false;\n const canPublish = schema.data?.canPublish ?? false;\n const label = (n: number) => (n === publishedV ? t(\"version_published_tag\", { version: n }) : `v${n}`);\n const toInfo = versions.find((v) => v.version === to);\n\n const picker = (id: string, text: string, value: number | null, set: (n: number) => void) => (\n <div className={cn(\"flex flex-col gap-1\", mobile && \"flex-1\")}>\n <Label htmlFor={id} className=\"sr-only\">\n {text}\n </Label>\n <Select value={value === null ? undefined : String(value)} onValueChange={(v: string | null) => v && set(Number(v))}>\n <SelectTrigger id={id} className={cn(\"h-8 text-[13px]\", mobile ? \"w-full\" : \"w-40\")}>\n <SelectValue>{value === null ? null : label(value)}</SelectValue>\n </SelectTrigger>\n <SelectContent>\n {versions.map((v) => (\n <SelectItem key={v.version} value={String(v.version)}>\n {label(v.version)}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n );\n\n const compare = (\n <div className=\"flex flex-wrap items-center gap-2\" role=\"group\" aria-label={`${t(\"compare_from\")}, ${t(\"compare_to\")}`}>\n {picker(\"cms-v-from\", t(\"compare_from\"), from, setFrom)}\n <ArrowRight aria-hidden className=\"h-4 w-4 text-muted-foreground\" />\n {picker(\"cms-v-to\", t(\"compare_to\"), to, setTo)}\n {!mobile ? (\n <Segmented\n label={t(\"view_mode\")}\n value={savedView}\n onChange={setView}\n options={[\n { value: \"split\", label: t(\"side_by_side\") },\n { value: \"unified\", label: t(\"unified\") },\n ]}\n />\n ) : null}\n </div>\n );\n\n const actions = (cls?: string) =>\n from !== null && to !== null ? (\n <>\n {canWrite && from !== latest ? (\n <Button type=\"button\" variant=\"outline\" className={cn(\"gap-1.5\", cls)} disabled={busy} onClick={() => setConfirm(\"restore\")}>\n <RotateCcw aria-hidden className=\"h-4 w-4\" />\n {t(\"restore_version\", { version: from })}\n </Button>\n ) : null}\n {canPublish && to !== publishedV ? (\n <Button type=\"button\" className={cls} disabled={busy} onClick={() => void run(\"publish\")}>\n {t(\"publish_version\", { version: to })}\n </Button>\n ) : null}\n </>\n ) : null;\n\n const d = diff.data?.d;\n const body = diff.data?.body;\n\n const fieldTable = d && d.fields.length ? (\n <div className=\"overflow-hidden rounded-lg border\">\n <table className=\"w-full text-sm\">\n <thead>\n <tr className=\"border-b text-left text-xs text-muted-foreground\">\n <th className=\"px-3 py-2 font-medium\">{t(\"field\")}</th>\n {!mobile ? <th className=\"px-3 py-2 font-medium\">{label(d.a)}</th> : null}\n <th className=\"px-3 py-2 font-medium\">{mobile ? `${label(d.a)} → v${d.b}` : `v${d.b}`}</th>\n </tr>\n </thead>\n <tbody>\n {d.fields.map((f) => {\n const name = FIELD_LABEL[f.path] ? t(FIELD_LABEL[f.path]) : f.path.replace(/^fields\\./, \"\");\n const a = show(f.from);\n const b = show(f.to);\n return (\n <tr key={f.path} className=\"border-b last:border-b-0 align-top\">\n <td className=\"px-3 py-2 text-xs\">{name}</td>\n {!mobile ? (\n <td className=\"px-3 py-2 font-mono text-xs\">\n <Words a={a} b={b} side=\"a\" />\n </td>\n ) : null}\n <td className=\"px-3 py-2 font-mono text-xs\">\n <Words a={a} b={b} side=\"b\" />\n </td>\n </tr>\n );\n })}\n </tbody>\n </table>\n </div>\n ) : null;\n\n const hunkHead = (h: Hunk) => {\n const head = headingBefore(body, h.bStart + 1);\n return `@@ ${head ?? `-${h.aStart},${h.aLines} +${h.bStart},${h.bLines}`}`;\n };\n\n const lineCls = (k: \"del\" | \"add\" | \"ctx\" | \"pad\") => cn(\"flex min-w-0 gap-2 px-2 font-mono text-xs leading-6\", k === \"del\" && \"bg-red-50\", k === \"add\" && \"bg-green-50\", k === \"pad\" && \"bg-muted/40\");\n const num = (n?: number) => (\n <i aria-hidden className=\"w-8 shrink-0 select-none text-right not-italic text-muted-foreground\">\n {n ?? \"\"}\n </i>\n );\n\n const split = d ? (\n <div className=\"overflow-hidden rounded-lg border\">\n <div className=\"grid grid-cols-2 border-b text-xs font-medium text-muted-foreground\">\n <span className=\"px-3 py-1.5\">{label(d.a)}</span>\n <span className=\"border-l px-3 py-1.5\">v{d.b}</span>\n </div>\n {d.hunks.map((h, hi) => (\n <div key={hi}>\n <div className=\"border-y bg-muted/40 px-3 py-1 font-mono text-xs text-muted-foreground first:border-t-0\">{hunkHead(h)}</div>\n <div className=\"grid grid-cols-2\">\n {rowsOf(h).map((r, i) => (\n <React.Fragment key={i}>\n <div className={lineCls(r.t === \"ctx\" ? \"ctx\" : r.a ? \"del\" : \"pad\")}>\n {num(r.a?.a)}\n <span className=\"min-w-0 whitespace-pre-wrap break-words\">\n {r.t === \"chg\" && r.a ? <span className=\"sr-only\">- </span> : null}\n {r.a ? r.t === \"chg\" && r.b ? <Words a={r.a.v} b={r.b.v} side=\"a\" /> : r.a.v : \"\"}\n </span>\n </div>\n <div className={cn(lineCls(r.t === \"ctx\" ? \"ctx\" : r.b ? \"add\" : \"pad\"), \"border-l\")}>\n {num(r.b?.b)}\n <span className=\"min-w-0 whitespace-pre-wrap break-words\">\n {r.t === \"chg\" && r.b ? <span className=\"sr-only\">+ </span> : null}\n {r.b ? r.t === \"chg\" && r.a ? <Words a={r.a.v} b={r.b.v} side=\"b\" /> : r.b.v : \"\"}\n </span>\n </div>\n </React.Fragment>\n ))}\n </div>\n </div>\n ))}\n </div>\n ) : null;\n\n const unified = d ? (\n <div className={cn(\"overflow-hidden\", mobile ? \"border-t\" : \"rounded-lg border\")}>\n {d.hunks.map((h, hi) => {\n const rows = rowsOf(h);\n const pairs = new Map<HunkLine, string>();\n for (const r of rows) if (r.t === \"chg\" && r.a && r.b) (pairs.set(r.a, r.b.v), pairs.set(r.b, r.a.v));\n return (\n <div key={hi}>\n <div className=\"border-b bg-muted/40 px-3 py-1 font-mono text-xs text-muted-foreground\">{hunkHead(h)}</div>\n {h.lines.map((l, i) => {\n const other = pairs.get(l);\n return (\n <div key={i} className={lineCls(l.t === \"-\" ? \"del\" : l.t === \"+\" ? \"add\" : \"ctx\")}>\n <span aria-hidden className=\"w-3 shrink-0 select-none text-muted-foreground\">\n {l.t === \"-\" ? \"−\" : l.t === \"+\" ? \"+\" : \" \"}\n </span>\n <span className=\"min-w-0 whitespace-pre-wrap break-words\">\n {l.t !== \" \" ? <span className=\"sr-only\">{l.t} </span> : null}\n {other !== undefined ? l.t === \"-\" ? <Words a={l.v} b={other} side=\"a\" /> : <Words a={other} b={l.v} side=\"b\" /> : l.v}\n </span>\n </div>\n );\n })}\n </div>\n );\n })}\n </div>\n ) : null;\n\n const diffArea = (\n <div className=\"flex min-w-0 flex-1 flex-col gap-3\">\n {diff.error ? <StatusText tone=\"error\">{errorMessage(diff.error, t)}</StatusText> : null}\n {d && !d.fields.length && !d.hunks.length ? <p className=\"text-sm text-muted-foreground\">{t(\"no_diff\")}</p> : null}\n {fieldTable}\n {d && d.hunks.length ? (view === \"unified\" ? unified : split) : null}\n </div>\n );\n\n const confirmDialog = (\n <ConfirmDialog\n open={confirm === \"restore\"}\n onOpenChange={(o) => !o && setConfirm(null)}\n title={t(\"restore_confirm\", { version: from ?? 0 })}\n description={t(\"restore_confirm_note\", { version: from ?? 0 })}\n confirmLabel={t(\"restore_version\", { version: from ?? 0 })}\n busy={busy}\n onConfirm={() => run(\"restore\")}\n />\n );\n\n const statusLine = (\n <StatusText tone={status?.tone === \"error\" ? \"error\" : \"ok\"} className=\"text-xs\">\n {status?.text ?? (list.loading && !versions.length ? t(\"loading\") : \"\")}\n </StatusText>\n );\n\n if (mobile)\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n <PageHeader\n title={t(\"versions\")}\n back={\n onBack ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"-ml-2 h-8 w-8\" aria-label={t(\"versions_back\")} onClick={onBack}>\n <ChevronLeft aria-hidden className=\"h-4 w-4\" />\n </Button>\n ) : undefined\n }\n />\n <div className=\"border-b px-4 py-2.5\">{compare}</div>\n <div className=\"flex-1\">\n {toInfo ? (\n <div className=\"flex flex-col gap-0.5 px-4 py-2.5 text-xs\">\n <div className=\"flex items-center gap-2\">\n <Who kind={toInfo.authorKind} label={toInfo.authorLabel} className=\"font-medium\" />\n <span className=\"text-muted-foreground\">{relativeTime(toInfo.createdAt, t, locale)}</span>\n </div>\n {toInfo.note ? <div className=\"text-muted-foreground\">{toInfo.note}</div> : null}\n </div>\n ) : null}\n <div className=\"px-4 pb-2\">{statusLine}</div>\n {diffArea}\n </div>\n <div className=\"sticky bottom-0 flex gap-2 border-t bg-background p-2\">{actions(\"flex-1\")}</div>\n {confirmDialog}\n </div>\n );\n\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n <PageHeader title={t(\"versions\")} crumbs={[schema.data?.label ?? collection, slug]}>\n {onBack ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" onClick={onBack}>\n <ArrowLeft aria-hidden className=\"h-4 w-4\" />\n {t(\"versions_back\")}\n </Button>\n ) : null}\n </PageHeader>\n <div className=\"flex min-h-0 flex-1\">\n <nav aria-label={t(\"versions_list\")} className=\"w-64 shrink-0 overflow-y-auto border-r\">\n <ul>\n {versions.map((v) => {\n const on = v.version === to;\n const cmp = v.version === from && !on;\n return (\n <li key={v.version}>\n <button\n type=\"button\"\n aria-current={on ? \"true\" : undefined}\n onClick={() => pick(v)}\n className={cn(\"flex w-full flex-col gap-1 border-b px-3.5 py-2.5 text-left outline-none hover:bg-muted/50 focus-visible:bg-muted\", on && \"bg-muted\", cmp && \"bg-muted/40\")}\n >\n <span className=\"flex w-full items-center gap-2 text-sm\">\n <b>v{v.version}</b>\n {v.published ? <StateBadge state=\"published\" /> : null}\n <span className=\"flex-1\" />\n <span className=\"text-xs text-muted-foreground\">{relativeTime(v.createdAt, t, locale)}</span>\n </span>\n <span className=\"flex items-center gap-1.5 text-xs\">\n <Who kind={v.authorKind} label={v.authorLabel} />\n <Badge variant=\"outline\" className={cn(\"h-4 rounded-full px-1.5 text-[10.5px] font-normal\", v.authorKind !== \"user\" && \"border-blue-200 bg-blue-50 text-blue-700\")}>\n {v.authorKind === \"user\" ? t(\"kind_user\") : t(\"kind_agent\")}\n </Badge>\n </span>\n {v.note ? <span className=\"text-xs text-muted-foreground\">{v.note}</span> : null}\n {v.changed?.fields.length ? (\n <span className=\"text-[11px] text-muted-foreground\">\n {t(\"changed_fields\", { fields: v.changed.fields.map((f) => (FIELD_LABEL[f] ? t(FIELD_LABEL[f]) : f.replace(/^fields\\./, \"\"))).join(\", \") })}\n </span>\n ) : null}\n </button>\n </li>\n );\n })}\n </ul>\n </nav>\n <div className=\"flex min-w-0 flex-1 flex-col gap-3 overflow-y-auto px-6 py-4\">\n <div className=\"flex flex-wrap items-center gap-2\">\n {compare}\n <span className=\"flex-1\" />\n {actions()}\n </div>\n {statusLine}\n {diffArea}\n </div>\n </div>\n {confirmDialog}\n </div>\n );\n}\n"
24
+ }
25
+ ]
26
+ }
@@ -0,0 +1,255 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry.json",
3
+ "name": "agent-cms",
4
+ "homepage": "https://github.com/mainsoft-2024/agent-cms",
5
+ "items": [
6
+ {
7
+ "name": "cms-lib",
8
+ "type": "registry:lib",
9
+ "title": "agent-cms client and helpers",
10
+ "description": "CmsProvider and useCms (REST client, UI strings in English and Korean), small hooks, shared parts (state badge, copy box, confirm dialog, page header, markdown preview).",
11
+ "dependencies": [
12
+ "@mainsoft/agent-cms",
13
+ "lucide-react"
14
+ ],
15
+ "registryDependencies": [
16
+ "badge",
17
+ "button",
18
+ "dialog"
19
+ ],
20
+ "files": [
21
+ {
22
+ "path": "registry/cms/use-cms.ts",
23
+ "type": "registry:lib"
24
+ },
25
+ {
26
+ "path": "registry/cms/cms-messages.ts",
27
+ "type": "registry:lib"
28
+ },
29
+ {
30
+ "path": "registry/cms/cms-parts.tsx",
31
+ "type": "registry:lib"
32
+ }
33
+ ]
34
+ },
35
+ {
36
+ "name": "cms-shell",
37
+ "type": "registry:component",
38
+ "title": "Admin layout",
39
+ "description": "Sidebar with collections, API keys and audit log, plus extraNav for your app's own screens. A sheet menu under 768px.",
40
+ "dependencies": [
41
+ "@mainsoft/agent-cms",
42
+ "lucide-react"
43
+ ],
44
+ "registryDependencies": [
45
+ "sheet",
46
+ "cms-lib"
47
+ ],
48
+ "files": [
49
+ {
50
+ "path": "registry/cms/cms-shell.tsx",
51
+ "type": "registry:component"
52
+ }
53
+ ]
54
+ },
55
+ {
56
+ "name": "cms-empty",
57
+ "type": "registry:component",
58
+ "title": "Empty collection",
59
+ "description": "New document, and how to write with an agent instead (CLI one-liner, MCP URL, API key link).",
60
+ "dependencies": [
61
+ "@mainsoft/agent-cms",
62
+ "lucide-react"
63
+ ],
64
+ "registryDependencies": [
65
+ "button",
66
+ "cms-lib"
67
+ ],
68
+ "files": [
69
+ {
70
+ "path": "registry/cms/cms-empty.tsx",
71
+ "type": "registry:component"
72
+ }
73
+ ]
74
+ },
75
+ {
76
+ "name": "cms-doc-list",
77
+ "type": "registry:component",
78
+ "title": "Document list",
79
+ "description": "State tabs with counts, category and author filters, search, 7-day views, selection with bulk publish, unpublish, hide, unhide and delete. Cards with long-press selection on phones.",
80
+ "dependencies": [
81
+ "@mainsoft/agent-cms",
82
+ "lucide-react"
83
+ ],
84
+ "registryDependencies": [
85
+ "button",
86
+ "checkbox",
87
+ "dialog",
88
+ "dropdown-menu",
89
+ "input",
90
+ "select",
91
+ "table",
92
+ "cms-lib",
93
+ "cms-empty"
94
+ ],
95
+ "files": [
96
+ {
97
+ "path": "registry/cms/cms-doc-list.tsx",
98
+ "type": "registry:component"
99
+ }
100
+ ]
101
+ },
102
+ {
103
+ "name": "cms-merge",
104
+ "type": "registry:component",
105
+ "title": "Merge after a conflict",
106
+ "description": "Three-way merge when someone saved first: what merged automatically, and theirs, mine or both for each conflict.",
107
+ "dependencies": [
108
+ "@mainsoft/agent-cms",
109
+ "lucide-react"
110
+ ],
111
+ "registryDependencies": [
112
+ "badge",
113
+ "button",
114
+ "label",
115
+ "radio-group",
116
+ "table",
117
+ "cms-lib"
118
+ ],
119
+ "files": [
120
+ {
121
+ "path": "registry/cms/cms-merge.tsx",
122
+ "type": "registry:component"
123
+ }
124
+ ]
125
+ },
126
+ {
127
+ "name": "cms-doc-editor",
128
+ "type": "registry:component",
129
+ "title": "Document editor",
130
+ "description": "Info form generated from the collection schema, markdown with live preview, autosave and restore, problems on the fields, agent change review (accept, revert), save, publish, preview links.",
131
+ "dependencies": [
132
+ "@mainsoft/agent-cms",
133
+ "lucide-react"
134
+ ],
135
+ "registryDependencies": [
136
+ "button",
137
+ "checkbox",
138
+ "dialog",
139
+ "dropdown-menu",
140
+ "input",
141
+ "label",
142
+ "select",
143
+ "tabs",
144
+ "textarea",
145
+ "cms-lib",
146
+ "cms-merge"
147
+ ],
148
+ "files": [
149
+ {
150
+ "path": "registry/cms/cms-doc-editor.tsx",
151
+ "type": "registry:component"
152
+ },
153
+ {
154
+ "path": "registry/cms/cms-field-form.tsx",
155
+ "type": "registry:component"
156
+ }
157
+ ]
158
+ },
159
+ {
160
+ "name": "cms-versions",
161
+ "type": "registry:component",
162
+ "title": "Version history",
163
+ "description": "Versions with author, note and changed fields; compare any two side by side or unified with word highlights; restore or publish a version.",
164
+ "dependencies": [
165
+ "@mainsoft/agent-cms",
166
+ "lucide-react"
167
+ ],
168
+ "registryDependencies": [
169
+ "badge",
170
+ "button",
171
+ "dialog",
172
+ "label",
173
+ "select",
174
+ "cms-lib"
175
+ ],
176
+ "files": [
177
+ {
178
+ "path": "registry/cms/cms-versions.tsx",
179
+ "type": "registry:component"
180
+ }
181
+ ]
182
+ },
183
+ {
184
+ "name": "cms-keys",
185
+ "type": "registry:component",
186
+ "title": "API keys",
187
+ "description": "Keys with scopes, collections, last use and expiry; revoke; create with the secret shown once and MCP and CLI setup to copy.",
188
+ "dependencies": [
189
+ "@mainsoft/agent-cms",
190
+ "lucide-react"
191
+ ],
192
+ "registryDependencies": [
193
+ "badge",
194
+ "button",
195
+ "checkbox",
196
+ "dialog",
197
+ "input",
198
+ "label",
199
+ "table",
200
+ "tabs",
201
+ "cms-lib"
202
+ ],
203
+ "files": [
204
+ {
205
+ "path": "registry/cms/cms-keys.tsx",
206
+ "type": "registry:component"
207
+ }
208
+ ]
209
+ },
210
+ {
211
+ "name": "cms-audit",
212
+ "type": "registry:component",
213
+ "title": "Audit log",
214
+ "description": "Who did what through which channel, filtered by action, who and result.",
215
+ "dependencies": [
216
+ "@mainsoft/agent-cms",
217
+ "lucide-react"
218
+ ],
219
+ "registryDependencies": [
220
+ "badge",
221
+ "button",
222
+ "select",
223
+ "table",
224
+ "cms-lib"
225
+ ],
226
+ "files": [
227
+ {
228
+ "path": "registry/cms/cms-audit.tsx",
229
+ "type": "registry:component"
230
+ }
231
+ ]
232
+ },
233
+ {
234
+ "name": "cms-command",
235
+ "type": "registry:component",
236
+ "title": "Command menu",
237
+ "description": "Cmd+K or Ctrl+K: find documents (drafts included) across collections and open, publish or start a new one.",
238
+ "dependencies": [
239
+ "@mainsoft/agent-cms",
240
+ "lucide-react"
241
+ ],
242
+ "registryDependencies": [
243
+ "command",
244
+ "dialog",
245
+ "cms-lib"
246
+ ],
247
+ "files": [
248
+ {
249
+ "path": "registry/cms/cms-command.tsx",
250
+ "type": "registry:component"
251
+ }
252
+ ]
253
+ }
254
+ ]
255
+ }
@@ -0,0 +1,162 @@
1
+ import { CmsDoc, DocStatus, CmsVersion, ReviewMark, KeyScope, CmsKey, AuditEntry } from './types.js';
2
+
3
+ /**
4
+ * Storage behind the CMS. `cms.ts` holds every rule (states, access, versions,
5
+ * validation) and talks only to this interface, so the rules are tested
6
+ * against `MemoryRepo` and run in production on `DrizzleRepo`.
7
+ */
8
+
9
+ type DocPatch = Partial<Omit<CmsDoc, "id" | "collection" | "createdAt">>;
10
+ type NewDoc = Omit<CmsDoc, "id" | "createdAt" | "updatedAt" | "republishedAt" | "autosave"> & {
11
+ id?: string;
12
+ createdAt?: string;
13
+ updatedAt?: string;
14
+ republishedAt?: string | null;
15
+ autosave?: CmsDoc["autosave"];
16
+ };
17
+ type StoredVersion = Omit<CmsVersion, "published">;
18
+ type NewVersion = Omit<CmsVersion, "id" | "createdAt" | "published" | "reviewed" | "changed"> & {
19
+ createdAt?: string;
20
+ changed?: CmsVersion["changed"];
21
+ };
22
+ interface KeyRow extends CmsKey {
23
+ hash: string;
24
+ createdBy: string | null;
25
+ }
26
+ interface AuditQuery {
27
+ /** Entries strictly older than this cursor (from the previous page). */
28
+ before?: string | null;
29
+ limit: number;
30
+ action?: string;
31
+ outcome?: AuditEntry["outcome"];
32
+ actorKind?: AuditEntry["actorKind"];
33
+ }
34
+ interface CmsRepo {
35
+ /** Run `fn` atomically (one DB transaction). */
36
+ tx<T>(fn: (repo: CmsRepo) => Promise<T>): Promise<T>;
37
+ findDoc(collection: string, slug: string): Promise<CmsDoc | null>;
38
+ findDocById(id: string): Promise<CmsDoc | null>;
39
+ listDocs(filter: {
40
+ collection?: string;
41
+ statuses?: DocStatus[];
42
+ published?: boolean;
43
+ }): Promise<CmsDoc[]>;
44
+ insertDoc(doc: NewDoc): Promise<CmsDoc>;
45
+ /** Returns null when `expectedVersion` is given and the row moved on. */
46
+ updateDoc(id: string, patch: DocPatch, expectedVersion?: number): Promise<CmsDoc | null>;
47
+ deleteDoc(id: string): Promise<void>;
48
+ insertVersion(v: NewVersion): Promise<void>;
49
+ listVersions(documentId: string): Promise<StoredVersion[]>;
50
+ getVersion(documentId: string, version: number): Promise<StoredVersion | null>;
51
+ setVersionReviewed(documentId: string, version: number, reviewed: ReviewMark[]): Promise<void>;
52
+ /** Delete all but the newest `keep` versions, never one in `protect`. */
53
+ pruneVersions(documentId: string, keep: number, protect: number[]): Promise<void>;
54
+ insertKey(k: {
55
+ name: string;
56
+ prefix: string;
57
+ hash: string;
58
+ scopes: KeyScope[];
59
+ collections: string[] | null;
60
+ createdBy: string | null;
61
+ expiresAt: string | null;
62
+ }): Promise<KeyRow>;
63
+ listKeys(): Promise<KeyRow[]>;
64
+ findKeyByHash(hash: string): Promise<KeyRow | null>;
65
+ touchKey(id: string, at: string): Promise<void>;
66
+ revokeKey(id: string, at: string): Promise<boolean>;
67
+ addHits(documentIds: string[], day: string, source: string): Promise<void>;
68
+ /** Hits per document since `sinceDay` (inclusive); only documents of `collection` when given. */
69
+ hitCounts(sinceDay: string, collection?: string): Promise<Map<string, number>>;
70
+ insertAudit(e: Omit<AuditEntry, "id">): Promise<void>;
71
+ /** Newest first. */
72
+ listAudit(q: AuditQuery): Promise<AuditEntry[]>;
73
+ /** Changes whenever any document changes (for cross-process index refresh). */
74
+ changeStamp(): Promise<string>;
75
+ getMeta(key: string): Promise<unknown>;
76
+ setMeta(key: string, value: unknown): Promise<void>;
77
+ }
78
+ /** In-memory repo for tests and examples. Starts at the current schema version. */
79
+ declare class MemoryRepo implements CmsRepo {
80
+ docs: Map<string, CmsDoc>;
81
+ versions: StoredVersion[];
82
+ keys: KeyRow[];
83
+ hits: Map<string, number>;
84
+ audit: AuditEntry[];
85
+ meta: Map<string, unknown>;
86
+ private seq;
87
+ private id;
88
+ tx<T>(fn: (repo: CmsRepo) => Promise<T>): Promise<T>;
89
+ findDoc(collection: string, slug: string): Promise<CmsDoc | null>;
90
+ findDocById(id: string): Promise<CmsDoc | null>;
91
+ listDocs(f: {
92
+ collection?: string;
93
+ statuses?: DocStatus[];
94
+ published?: boolean;
95
+ }): Promise<CmsDoc[]>;
96
+ insertDoc(doc: NewDoc): Promise<CmsDoc>;
97
+ updateDoc(id: string, patch: DocPatch, expectedVersion?: number): Promise<CmsDoc | null>;
98
+ deleteDoc(id: string): Promise<void>;
99
+ insertVersion(v: NewVersion): Promise<void>;
100
+ listVersions(documentId: string): Promise<StoredVersion[]>;
101
+ getVersion(documentId: string, version: number): Promise<StoredVersion | null>;
102
+ setVersionReviewed(documentId: string, version: number, reviewed: ReviewMark[]): Promise<void>;
103
+ pruneVersions(documentId: string, keep: number, protect: number[]): Promise<void>;
104
+ insertKey(k: {
105
+ name: string;
106
+ prefix: string;
107
+ hash: string;
108
+ scopes: KeyScope[];
109
+ collections: string[] | null;
110
+ createdBy: string | null;
111
+ expiresAt: string | null;
112
+ }): Promise<{
113
+ hash: string;
114
+ createdBy: string | null;
115
+ id: string;
116
+ name: string;
117
+ prefix: string;
118
+ scopes: KeyScope[];
119
+ collections: string[] | null;
120
+ lastUsedAt: string | null;
121
+ revokedAt: string | null;
122
+ expiresAt: string | null;
123
+ createdAt: string;
124
+ }>;
125
+ listKeys(): Promise<{
126
+ hash: string;
127
+ createdBy: string | null;
128
+ id: string;
129
+ name: string;
130
+ prefix: string;
131
+ scopes: KeyScope[];
132
+ collections: string[] | null;
133
+ lastUsedAt: string | null;
134
+ revokedAt: string | null;
135
+ expiresAt: string | null;
136
+ createdAt: string;
137
+ }[]>;
138
+ findKeyByHash(hash: string): Promise<{
139
+ hash: string;
140
+ createdBy: string | null;
141
+ id: string;
142
+ name: string;
143
+ prefix: string;
144
+ scopes: KeyScope[];
145
+ collections: string[] | null;
146
+ lastUsedAt: string | null;
147
+ revokedAt: string | null;
148
+ expiresAt: string | null;
149
+ createdAt: string;
150
+ } | null>;
151
+ touchKey(id: string, at: string): Promise<void>;
152
+ revokeKey(id: string, at: string): Promise<boolean>;
153
+ addHits(ids: string[], day: string, source: string): Promise<void>;
154
+ hitCounts(sinceDay: string, collection?: string): Promise<Map<string, number>>;
155
+ insertAudit(e: Omit<AuditEntry, "id">): Promise<void>;
156
+ listAudit(q: AuditQuery): Promise<AuditEntry[]>;
157
+ changeStamp(): Promise<string>;
158
+ getMeta(key: string): Promise<{} | null>;
159
+ setMeta(key: string, value: unknown): Promise<void>;
160
+ }
161
+
162
+ export { type AuditQuery as A, type CmsRepo as C, type DocPatch as D, type KeyRow as K, MemoryRepo as M, type NewDoc as N, type StoredVersion as S, type NewVersion as a };