@kidecms/core 0.19.0 → 0.20.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.
@@ -3,6 +3,7 @@ import AdminLayout from "../../admin/layouts/AdminLayout.astro";
3
3
  import AccessDeniedView from "../../admin/views/AccessDeniedView.astro";
4
4
  import EditView from "../../admin/views/EditView.astro";
5
5
  import ListView from "../../admin/views/ListView.astro";
6
+ import NeedsYouView from "../../admin/views/NeedsYouView.astro";
6
7
  import RecentView from "../../admin/views/RecentView.astro";
7
8
  import SinglesView from "../../admin/views/SinglesView.astro";
8
9
  import config from "virtual:kide/config";
@@ -26,7 +27,11 @@ if (route.kind === "dashboard") return Astro.redirect("/admin/recent");
26
27
  const collectionSlug = "collectionSlug" in route ? route.collectionSlug : null;
27
28
  const collection = collectionSlug ? (cms.meta.getCollection(collectionSlug) as any) : null;
28
29
  const canAccessCurrent =
29
- route.kind === "recent" || route.kind === "singles" || !collectionSlug || canRead(config, user, collectionSlug);
30
+ route.kind === "recent" ||
31
+ route.kind === "needs-you" ||
32
+ route.kind === "singles" ||
33
+ !collectionSlug ||
34
+ canRead(config, user, collectionSlug);
30
35
 
31
36
  // Singletons: redirect list/new to the single document's edit page
32
37
  if (collection?.singleton && canAccessCurrent && (route.kind === "list" || route.kind === "new")) {
@@ -40,11 +45,14 @@ if (collection?.singleton && canAccessCurrent && (route.kind === "list" || route
40
45
  const title =
41
46
  route.kind === "recent"
42
47
  ? "Recent | Kide CMS"
43
- : route.kind === "singles"
44
- ? "Singles | Kide CMS"
45
- : `${collection?.labels?.plural ?? "Admin"} | Kide CMS`;
48
+ : route.kind === "needs-you"
49
+ ? "Needs you | Kide CMS"
50
+ : route.kind === "singles"
51
+ ? "Singles | Kide CMS"
52
+ : `${collection?.labels?.plural ?? "Admin"} | Kide CMS`;
46
53
 
47
- const activeCollection = route.kind === "recent" ? "recent" : (collectionSlug ?? "singles");
54
+ const activeCollection =
55
+ route.kind === "recent" ? "recent" : route.kind === "needs-you" ? "needs-you" : (collectionSlug ?? "singles");
48
56
  ---
49
57
 
50
58
  <AdminLayout
@@ -55,8 +63,13 @@ const activeCollection = route.kind === "recent" ? "recent" : (collectionSlug ??
55
63
  customNav={config.admin?.nav}
56
64
  >
57
65
  {route.kind === "recent" && <RecentView />}
66
+ {route.kind === "needs-you" && <NeedsYouView />}
58
67
  {route.kind === "singles" && <SinglesView />}
59
- {route.kind !== "recent" && route.kind !== "singles" && !canAccessCurrent && <AccessDeniedView />}
68
+ {
69
+ route.kind !== "recent" && route.kind !== "needs-you" && route.kind !== "singles" && !canAccessCurrent && (
70
+ <AccessDeniedView />
71
+ )
72
+ }
60
73
  {route.kind === "list" && canAccessCurrent && collection && <ListView collection={collection} />}
61
74
  {
62
75
  (route.kind === "new" || route.kind === "edit") && canAccessCurrent && collection && (
@@ -5,17 +5,18 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../..
5
5
  import { Input } from "../../admin/components/ui/input";
6
6
  import { Label } from "../../admin/components/ui/label";
7
7
  import { buttonVariants } from "../../admin/components/ui/button";
8
+ import { eq } from "drizzle-orm";
8
9
  import { getDb } from "virtual:kide/db";
9
10
  import { MIN_PASSWORD_LENGTH } from "../../core";
10
11
 
11
12
  export const prerender = false;
12
13
 
13
- // If users already exist, redirect to login
14
+ // Setup is done once an admin exists — seeded editors must not close this door.
14
15
  const db = await getDb();
15
16
  const schema = await import("virtual:kide/schema");
16
17
  const tables = schema.cmsTables as Record<string, { main: any }>;
17
18
  if (tables.users) {
18
- const rows = await db.select().from(tables.users.main).limit(1);
19
+ const rows = await db.select().from(tables.users.main).where(eq(tables.users.main.role, "admin")).limit(1);
19
20
  if (rows.length > 0) {
20
21
  return Astro.redirect("/admin/login");
21
22
  }
@@ -3,7 +3,7 @@ import type { APIRoute } from "astro";
3
3
  import config from "virtual:kide/config";
4
4
  import { cms } from "virtual:kide/api";
5
5
  import { collaboration } from "virtual:kide/runtime";
6
- import { formatPagePath, getPageHref, isApprover, resolveCollaboration } from "../../../core";
6
+ import { FieldError, formatPagePath, getPageHref, isApprover, resolveCollaboration } from "../../../core";
7
7
  import { loadSharedSectionUsageCounts } from "../../../admin/lib/edit-data";
8
8
 
9
9
  export const prerender = false;
@@ -32,15 +32,19 @@ const isFormRequest = (request: Request) => {
32
32
  };
33
33
 
34
34
  // Append _toast and _msg params so the layout can render a server-side toast
35
- const redirect = (location: string, toast?: { status: "success" | "error"; msg: string }) => {
35
+ const redirect = (location: string, toast?: { status: "success" | "error"; msg: string; field?: string }) => {
36
36
  let target = location;
37
37
  if (toast) {
38
38
  const sep = target.includes("?") ? "&" : "?";
39
39
  target += `${sep}_toast=${toast.status}&_msg=${encodeURIComponent(toast.msg)}`;
40
+ // The admin uses this to focus and mark the offending input.
41
+ if (toast.field) target += `&_field=${encodeURIComponent(toast.field)}`;
40
42
  }
41
43
  return new Response(null, { status: 303, headers: { Location: target } });
42
44
  };
43
45
 
46
+ const camelCaseColumn = (column: string) => column.replace(/_([a-z0-9])/g, (_, c: string) => c.toUpperCase());
47
+
44
48
  const stripToastParams = (url: string) => {
45
49
  const [path, query] = url.split("?");
46
50
  if (!query) return url;
@@ -206,15 +210,18 @@ const handleHtmlMutation = async (
206
210
  return redirect(redirectTo);
207
211
  } catch (error) {
208
212
  let msg = error instanceof Error ? error.message : `Failed to ${action}`;
213
+ // Structured where we raise it ourselves; parsed only where SQLite is the source.
214
+ let field = error instanceof FieldError ? error.field : undefined;
209
215
  if (msg.toLowerCase().includes("unique constraint failed")) {
210
216
  const match = msg.match(/unique constraint failed:\s*\S+\.(\w+)/i);
211
- const field = match ? match[1] : "field";
212
- msg = `A document with this ${field} already exists`;
217
+ const column = match ? match[1] : null;
218
+ field = column ? camelCaseColumn(column) : undefined;
219
+ msg = `A document with this ${column ?? "field"} already exists`;
213
220
  } else if (msg.startsWith("Failed query:")) {
214
221
  msg = `Failed to ${action} ${collection.labels.singular.toLowerCase()}`;
215
222
  }
216
223
  const fallback = documentId ? redirectTo : redirectTo || `/admin/${collectionSlug}/new`;
217
- return redirect(fallback, { status: "error", msg });
224
+ return redirect(fallback, { status: "error", msg, field });
218
225
  }
219
226
  };
220
227
 
@@ -60,8 +60,10 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
60
60
  return Response.json({ error: "Users collection not configured." }, { status: 500 });
61
61
  }
62
62
 
63
- // Prevent setup if users already exist (fast path / friendly redirect).
64
- const existing = await db.select().from(tables.users.main).limit(1);
63
+ // Prevent setup if an admin already exists (fast path / friendly redirect).
64
+ // Deliberately admin-scoped: seeded demo editors, or an invite that created an
65
+ // editor first, must not strand a project with no way to make its first admin.
66
+ const existing = await db.select().from(tables.users.main).where(eq(tables.users.main.role, "admin")).limit(1);
65
67
  if (existing.length > 0) {
66
68
  return new Response(null, {
67
69
  status: 303,
@@ -74,12 +76,12 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
74
76
  const hashedPassword = await hashPassword(password);
75
77
 
76
78
  // Atomic winner election that leaves no orphan state: a single conditional insert creates
77
- // the first admin only if the table is still empty. Self-recovering — if anything fails
78
- // there's no marker to strand setup, and a retry just runs the same guarded insert.
79
+ // the first admin only if none exists yet. Self-recovering — if anything fails there's no
80
+ // marker to strand setup, and a retry just runs the same guarded insert.
79
81
  await db.run(sql`
80
82
  INSERT INTO cms_users (_id, name, email, role, password, _created_at, _updated_at)
81
83
  SELECT ${id}, ${name}, ${email}, 'admin', ${hashedPassword}, ${now}, ${now}
82
- WHERE NOT EXISTS (SELECT 1 FROM cms_users)
84
+ WHERE NOT EXISTS (SELECT 1 FROM cms_users WHERE role = 'admin')
83
85
  `);
84
86
 
85
87
  // Confirm we won the race (our row exists). If not, another concurrent setup created the
@@ -45,6 +45,15 @@ export const GET: APIRoute = async ({ url }) => {
45
45
  return Response.json({ state, comments, activity });
46
46
  };
47
47
 
48
+ // Editing is author-only, deliberately narrower than resolve/delete: removing a
49
+ // comment is moderation, but rewriting the words under someone else's name and
50
+ // avatar is not something an approver should be able to do.
51
+ const authorizeCommentEdit = async (commentId: string, actor: { id: string }) => {
52
+ const comment = await collaboration.getComment(commentId);
53
+ if (!comment || !isEnabled(comment.collection)) return null;
54
+ return comment.authorId === actor.id ? comment : null;
55
+ };
56
+
48
57
  // POST /api/cms/collaboration { collection, id, action, ...payload }
49
58
  export const POST: APIRoute = async ({ request, locals }) => {
50
59
  const actor = getActor(locals);
@@ -85,6 +94,12 @@ export const POST: APIRoute = async ({ request, locals }) => {
85
94
  );
86
95
  return Response.json({ comment });
87
96
  }
97
+ case "updateComment": {
98
+ const comment = await authorizeCommentEdit(String((body as any).commentId), actor);
99
+ if (!comment) return forbidden();
100
+ const updated = await collaboration.updateComment(comment._id, String((body as any).body ?? ""), actor);
101
+ return Response.json({ comment: updated });
102
+ }
88
103
  case "resolveComment": {
89
104
  const comment = await authorizeComment(String((body as any).commentId), actor);
90
105
  if (!comment) return forbidden();
@@ -1 +0,0 @@
1
- deleting