@kidecms/core 0.19.1 → 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.
@@ -0,0 +1,100 @@
1
+ ---
2
+ import DocumentsDataTable from "../components/DocumentsDataTable";
3
+ import config from "virtual:kide/config";
4
+ import { cms } from "virtual:kide/api";
5
+ import { collaboration } from "virtual:kide/runtime";
6
+ import { formatDate, getLabelField, isApprover, resolveCollaboration } from "../../core";
7
+ import { canRead, getVisualStatus } from "../lib/access";
8
+ import { REVIEW_STATE_META, eligibleCollabSlugs, loadNeedsYou } from "../lib/collaboration";
9
+
10
+ const user = Astro.locals.user;
11
+ const runtimeContext = user ? { user } : {};
12
+ const cmsRuntime = cms as Record<string, any>;
13
+ const defaultLocale = config.locales?.default ?? "en";
14
+
15
+ const eligible = eligibleCollabSlugs(config, user, resolveCollaboration, canRead);
16
+ const approver = isApprover(config, user?.role);
17
+
18
+ const items = user
19
+ ? await loadNeedsYou({ collaboration, userId: String(user.id), isApprover: approver, eligibleSlugs: eligible })
20
+ : [];
21
+
22
+ // Hydrate each queued document. A row whose document is gone is skipped rather
23
+ // than rendered as a broken link.
24
+ type Hydrated = { item: (typeof items)[number]; doc: Record<string, unknown>; collection: any };
25
+ const hydrated: Hydrated[] = [];
26
+ for (const item of items) {
27
+ const collection = config.collections.find((c: any) => c.slug === item.collectionSlug);
28
+ const api = cmsRuntime[item.collectionSlug];
29
+ if (!collection || !api) continue;
30
+ const doc = await api
31
+ .findById(item.documentId, { status: "any", locale: defaultLocale }, runtimeContext)
32
+ .catch(() => null);
33
+ if (!doc) continue;
34
+ hydrated.push({ item, doc, collection });
35
+ }
36
+
37
+ hydrated.sort((a, b) => String(b.doc._updatedAt ?? "").localeCompare(String(a.doc._updatedAt ?? "")));
38
+
39
+ const rows = hydrated.map(({ item, doc, collection }) => {
40
+ const displayTitle = collection.singleton
41
+ ? collection.labels.singular
42
+ : String(doc[getLabelField(collection)] ?? doc.slug ?? collection.labels.singular);
43
+
44
+ return {
45
+ id: `${item.collectionSlug}:${item.documentId}`,
46
+ editHref: `/admin/${item.collectionSlug}/${item.documentId}`,
47
+ status: collection.drafts ? getVisualStatus(doc) : "",
48
+ singleton: collection.singleton,
49
+ locales: [defaultLocale],
50
+ searchText: displayTitle,
51
+ values: {
52
+ title: displayTitle,
53
+ collection: collection.labels.singular,
54
+ _review: REVIEW_STATE_META[item.reviewState].label,
55
+ _reason: item.reason === "assigned" ? "Assigned to you" : "Waiting for your review",
56
+ _updatedAt: formatDate(doc._updatedAt),
57
+ },
58
+ };
59
+ });
60
+ ---
61
+
62
+ <section class="space-y-6 px-4 py-6 lg:py-8 lg:pr-8 lg:pl-12">
63
+ <div class="flex items-start justify-between gap-4">
64
+ <div>
65
+ <h1 class="text-2xl font-semibold tracking-tight">Needs you</h1>
66
+ <p class="text-muted-foreground mt-1 text-sm">
67
+ {
68
+ approver
69
+ ? "Documents assigned to you, and anything submitted for review."
70
+ : "Documents assigned to you that still need work."
71
+ }
72
+ </p>
73
+ </div>
74
+ </div>
75
+ {
76
+ rows.length === 0 ? (
77
+ <div class="text-muted-foreground rounded-lg border border-dashed px-6 py-12 text-center text-sm">
78
+ Nothing needs you right now.
79
+ </div>
80
+ ) : (
81
+ <DocumentsDataTable
82
+ client:load
83
+ collectionSlug="needs-you"
84
+ draftsEnabled={true}
85
+ duplicateEnabled={false}
86
+ showLocalesColumn={false}
87
+ title="Needs you"
88
+ columns={[
89
+ { key: "title", label: "Title" },
90
+ { key: "collection", label: "Collection" },
91
+ { key: "_reason", label: "Why" },
92
+ { key: "_review", label: "Review" },
93
+ { key: "_updatedAt", label: "Updated" },
94
+ ]}
95
+ data={rows}
96
+ searchPlaceholder="Filter…"
97
+ />
98
+ )
99
+ }
100
+ </section>
@@ -85,6 +85,88 @@
85
85
  </script>
86
86
 
87
87
  <script is:inline>
88
+ // A toast alone leaves the editor hunting for which field it means — especially
89
+ // in a long form where the culprit may sit inside a collapsed group. Point at it:
90
+ // open its group, scroll it into view, focus it, and mark it invalid until touched.
91
+ function clearInvalidMarks() {
92
+ // Both markers, because they are mutually exclusive: an input carries
93
+ // aria-invalid only, a composite control carries data-cms-invalid only.
94
+ // Scoped to the form so a component managing its own aria-invalid is untouched.
95
+ var form = document.getElementById("document-form");
96
+ if (!form) return;
97
+ form.querySelectorAll("[data-cms-invalid], [aria-invalid='true']").forEach(function (el) {
98
+ el.removeAttribute("data-cms-invalid");
99
+ el.removeAttribute("aria-invalid");
100
+ });
101
+ }
102
+
103
+ function highlightInvalidField(fieldName) {
104
+ clearInvalidMarks();
105
+ if (!fieldName) return;
106
+ var wrapper = document.querySelector('[data-field-name="' + CSS.escape(fieldName) + '"]');
107
+ if (!wrapper) return;
108
+
109
+ // Collapsible groups are <details>; a field inside a closed one is invisible.
110
+ var group = wrapper.closest("details");
111
+ if (group && !group.open) group.open = true;
112
+
113
+ var control = wrapper.querySelector("input, textarea, select, [contenteditable='true']");
114
+ if (control) {
115
+ // Inputs and textareas already style [aria-invalid]; adding the fallback
116
+ // outline on top of that border+ring reads as an error about an error.
117
+ control.setAttribute("aria-invalid", "true");
118
+ } else {
119
+ wrapper.setAttribute("data-cms-invalid", "");
120
+ }
121
+ // Drop the mark as soon as they start fixing it — keeping it red while someone
122
+ // types is nagging, and the server re-marks on the next submit if still wrong.
123
+ // Listening on the wrapper covers composite controls (pickers, block editors)
124
+ // whose events come from a child rather than an input we can find.
125
+ wrapper.addEventListener("input", clearInvalidMarks, { once: true });
126
+ wrapper.addEventListener("change", clearInvalidMarks, { once: true });
127
+ wrapper.scrollIntoView({ behavior: "smooth", block: "center" });
128
+ if (control && typeof control.focus === "function") {
129
+ setTimeout(function () {
130
+ control.focus({ preventScroll: true });
131
+ }, 300);
132
+ }
133
+ }
134
+
135
+ function showErrorToast(msg, fieldName) {
136
+ var existing = document.getElementById("admin-toast");
137
+ if (existing) existing.parentElement.remove();
138
+ var w = document.createElement("div");
139
+ w.className = "fixed top-4 left-1/2 z-50 w-full max-w-sm -translate-x-1/2";
140
+ w.innerHTML =
141
+ '<div id="admin-toast" role="alert" class="bg-card flex items-center gap-2 rounded-lg border border-red-500/30 px-5 py-3 text-sm shadow-lg" style="animation:toast-in .25s ease-out,toast-out .3s ease-in 4.7s forwards">' +
142
+ '<svg class="size-4 shrink-0 text-red-600 dark:text-red-400" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/></svg>' +
143
+ '<span class="text-red-700 dark:text-red-400"></span></div>';
144
+ // Carries document data (hook errors quote field values) — never innerHTML.
145
+ w.querySelector("span").textContent = msg;
146
+ document.body.appendChild(w);
147
+ setTimeout(function () {
148
+ w.remove();
149
+ }, 5200);
150
+ highlightInvalidField(fieldName);
151
+ }
152
+
153
+ // The browser's own bubble is OS-styled, says "Please fill out this field", and
154
+ // shows only one field at a time — three ways it disagrees with how the admin
155
+ // reports the identical error from the server. Keep the browser's constraint
156
+ // engine (required, maxlength, type=email all still apply) and replace only its
157
+ // presentation, so a missing Title looks the same whoever caught it.
158
+ function reportClientValidity(f) {
159
+ if (f.checkValidity()) return true;
160
+ var invalid = f.querySelector(":invalid");
161
+ if (!invalid) return false;
162
+ var wrapper = invalid.closest("[data-field-name]");
163
+ var fieldName = wrapper ? wrapper.getAttribute("data-field-name") : null;
164
+ var label = wrapper ? wrapper.querySelector("label") : null;
165
+ var labelText = label ? label.textContent.replace(/\*/g, "").trim() : "";
166
+ showErrorToast(labelText ? labelText + " is required." : invalid.validationMessage, fieldName);
167
+ return false;
168
+ }
169
+
88
170
  (function () {
89
171
  var form = document.getElementById("document-form");
90
172
  if (!form) return;
@@ -92,9 +174,13 @@
92
174
  var first = form.querySelector('input[type="text"], textarea');
93
175
  if (first) first.focus();
94
176
  }
177
+ // Suppress the native bubbles; reportClientValidity() below re-runs the same
178
+ // checks and presents them in the admin's own language.
179
+ form.setAttribute("novalidate", "");
95
180
  form.addEventListener("submit", function (e) {
96
181
  e.preventDefault();
97
182
  var f = e.target;
183
+ if (!reportClientValidity(f)) return;
98
184
  var sub = e.submitter;
99
185
  var fd = new FormData(f);
100
186
  if (sub && sub.name && sub.value) fd.set(sub.name, sub.value);
@@ -106,21 +192,10 @@
106
192
  .then(function (res) {
107
193
  var u = new URL(res.url);
108
194
  if (u.searchParams.get("_toast") === "error") {
109
- var existing = document.getElementById("admin-toast");
110
- if (existing) existing.parentElement.remove();
111
- var msg = decodeURIComponent(u.searchParams.get("_msg") || "Something went wrong");
112
- var w = document.createElement("div");
113
- w.className = "fixed top-4 left-1/2 z-50 w-full max-w-sm -translate-x-1/2";
114
- w.innerHTML =
115
- '<div id="admin-toast" role="alert" class="bg-card flex items-center gap-2 rounded-lg border border-red-500/30 px-5 py-3 text-sm shadow-lg" style="animation:toast-in .25s ease-out,toast-out .3s ease-in 4.7s forwards">' +
116
- '<svg class="size-4 shrink-0 text-red-600 dark:text-red-400" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/></svg>' +
117
- '<span class="text-red-700 dark:text-red-400"></span></div>';
118
- // Carries document data (hook errors quote field values) — never innerHTML.
119
- w.querySelector("span").textContent = msg;
120
- document.body.appendChild(w);
121
- setTimeout(function () {
122
- w.remove();
123
- }, 5200);
195
+ showErrorToast(
196
+ decodeURIComponent(u.searchParams.get("_msg") || "Something went wrong"),
197
+ u.searchParams.get("_field"),
198
+ );
124
199
  return;
125
200
  }
126
201
  if (u.searchParams.get("_toast") === "success") {
package/core/admin.ts CHANGED
@@ -82,6 +82,7 @@ export const formatDate = (value: unknown): string => {
82
82
  export type AdminRoute =
83
83
  | { kind: "dashboard" }
84
84
  | { kind: "recent" }
85
+ | { kind: "needs-you" }
85
86
  | { kind: "singles" }
86
87
  | { kind: "list"; collectionSlug: string }
87
88
  | { kind: "new"; collectionSlug: string }
@@ -92,6 +93,7 @@ export const resolveAdminRoute = (path: string | undefined): AdminRoute => {
92
93
 
93
94
  if (segments.length === 0) return { kind: "dashboard" };
94
95
  if (segments[0] === "recent" && segments.length === 1) return { kind: "recent" };
96
+ if (segments[0] === "needs-you" && segments.length === 1) return { kind: "needs-you" };
95
97
  if (segments[0] === "singles" && segments.length === 1) return { kind: "singles" };
96
98
  if (segments.length === 1) return { kind: "list", collectionSlug: segments[0] };
97
99
  if (segments[1] === "new") return { kind: "new", collectionSlug: segments[0] };
package/core/api.ts CHANGED
@@ -2,6 +2,7 @@ import { and, asc, desc, eq, inArray, like, lte, ne, or, sql } from "drizzle-orm
2
2
  import { nanoid } from "nanoid";
3
3
 
4
4
  import { setUsageConfig } from "./asset-usage";
5
+ import { removeCollaborationFor } from "./collaboration";
5
6
  import { recordAudit, type AuditActor } from "./audit";
6
7
  import { hashPassword, MIN_PASSWORD_LENGTH } from "./auth";
7
8
  import type { CMSConfig, CollectionConfig, FieldConfig, RichTextDocument } from "./define";
@@ -164,6 +165,24 @@ const coerceFieldValue = (field: FieldConfig, value: unknown): unknown => {
164
165
  }
165
166
  };
166
167
 
168
+ /** "seoDescription" -> "Seo description", unless the field declares a label. */
169
+ const fieldLabel = (fieldName: string, field: FieldConfig): string =>
170
+ field.label ??
171
+ fieldName
172
+ .replace(/^_+/, "")
173
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
174
+ .replace(/^./, (c) => c.toUpperCase());
175
+
176
+ export class FieldError extends Error {
177
+ readonly field: string;
178
+
179
+ constructor(field: string, message: string) {
180
+ super(message);
181
+ this.name = "FieldError";
182
+ this.field = field;
183
+ }
184
+ }
185
+
167
186
  const prepareIncomingData = (
168
187
  collection: CollectionConfig,
169
188
  input: Record<string, unknown>,
@@ -204,7 +223,7 @@ const prepareIncomingData = (
204
223
  for (const [fieldName, field] of Object.entries(collection.fields)) {
205
224
  if (!field.required) continue;
206
225
  const candidate = data[fieldName] ?? existing?.[fieldName];
207
- if (isEmptyValue(candidate)) throw new Error(`Field "${fieldName}" is required.`);
226
+ if (isEmptyValue(candidate)) throw new FieldError(fieldName, `${fieldLabel(fieldName, field)} is required.`);
208
227
  }
209
228
 
210
229
  for (const [fieldName, field] of Object.entries(collection.fields)) {
@@ -212,7 +231,10 @@ const prepareIncomingData = (
212
231
  if (!maxItems) continue;
213
232
  const candidate = data[fieldName] ?? existing?.[fieldName];
214
233
  if (Array.isArray(candidate) && candidate.length > maxItems) {
215
- throw new Error(`Field "${fieldName}" allows at most ${maxItems} item${maxItems === 1 ? "" : "s"}.`);
234
+ throw new FieldError(
235
+ fieldName,
236
+ `${fieldLabel(fieldName, field)} allows at most ${maxItems} item${maxItems === 1 ? "" : "s"}.`,
237
+ );
216
238
  }
217
239
  }
218
240
 
@@ -394,6 +416,10 @@ const getTableRefs = async (collectionSlug: string) => {
394
416
  return tables;
395
417
  };
396
418
 
419
+ /**
420
+ * A validation failure that knows which field caused it, so the admin can point at
421
+ * the offending input instead of showing a toast and leaving the editor to hunt.
422
+ */
397
423
  export const createCms = (config: CMSConfig) => {
398
424
  // A partially-evaluated config here means a module cycle: cms.config.ts
399
425
  // statically imported a module that itself imports the generated API (which
@@ -902,6 +928,9 @@ export const createCms = (config: CMSConfig) => {
902
928
  }
903
929
  if (tables.translations) await db.delete(tables.translations).where(eq(tables.translations._entityId, id));
904
930
  if (tables.versions) await db.delete(tables.versions).where(eq(tables.versions._docId, id));
931
+ // Collaboration rows outlive their document otherwise, and an orphaned
932
+ // review row still counts towards the "Needs you" badge.
933
+ await removeCollaborationFor(slug, id);
905
934
 
906
935
  await collection.hooks?.afterDelete?.(existing, hookContext);
907
936
  auditContent("content.delete", slug, id, context);
@@ -7,6 +7,12 @@ import { getSchema } from "./schema";
7
7
 
8
8
  // `in_progress` is the default before any collaboration row exists.
9
9
  export const REVIEW_STATES = ["in_progress", "ready_for_review", "changes_requested", "approved"] as const;
10
+
11
+ /**
12
+ * States that still represent outstanding work. "approved" is deliberately absent:
13
+ * a queue that keeps finished documents forever stops being read.
14
+ */
15
+ export const OPEN_REVIEW_STATES = ["in_progress", "ready_for_review", "changes_requested"] as const;
10
16
  export type ReviewState = (typeof REVIEW_STATES)[number];
11
17
 
12
18
  const DEFAULT_STATE: ReviewState = "in_progress";
@@ -24,6 +30,8 @@ export type CommentRecord = {
24
30
  authorEmail: string | null;
25
31
  resolved: boolean;
26
32
  createdAt: string;
33
+ /** Set the first time the author rewrites the body; null means never edited. */
34
+ editedAt: string | null;
27
35
  };
28
36
 
29
37
  export type ActivityRecord = {
@@ -107,6 +115,26 @@ export const collaboration = {
107
115
  }));
108
116
  },
109
117
 
118
+ // Every document sitting in one of these review states, whoever holds it.
119
+ // Approvers need "waiting on me", which is not the same question as "assigned to me".
120
+ async inReviewStates(
121
+ states: readonly ReviewState[],
122
+ ): Promise<Array<{ collection: string; documentId: string; reviewState: ReviewState; editor: string | null }>> {
123
+ if (states.length === 0) return [];
124
+ const db = await getDb();
125
+ const schema = getSchema();
126
+ const rows = await db
127
+ .select()
128
+ .from(schema.cmsCollaboration)
129
+ .where(inArray(schema.cmsCollaboration.reviewState, states as unknown as string[]));
130
+ return (rows as any[]).map((r) => ({
131
+ collection: String(r.collection),
132
+ documentId: String(r.documentId),
133
+ reviewState: isReviewState(r.reviewState) ? r.reviewState : DEFAULT_STATE,
134
+ editor: r.editor ?? null,
135
+ }));
136
+ },
137
+
110
138
  async setReviewState(
111
139
  collection: string,
112
140
  documentId: string,
@@ -190,6 +218,7 @@ export const collaboration = {
190
218
  body,
191
219
  authorId: actor?.id ?? null,
192
220
  authorEmail: actor?.email ?? null,
221
+ editedAt: null,
193
222
  resolved: false,
194
223
  createdAt: new Date().toISOString(),
195
224
  };
@@ -218,11 +247,39 @@ export const collaboration = {
218
247
  body: row.body,
219
248
  authorId: row.authorId ?? null,
220
249
  authorEmail: row.authorEmail ?? null,
250
+ editedAt: row.editedAt ?? null,
221
251
  resolved: !!row.resolved,
222
252
  createdAt: row.createdAt,
223
253
  };
224
254
  },
225
255
 
256
+ /**
257
+ * Rewrites a comment body and stamps `editedAt`. Authorship is enforced by the
258
+ * caller — unlike delete, an approver must not rewrite words that appear under
259
+ * someone else's name.
260
+ */
261
+ async updateComment(id: string, body: string, actor: AuditActor): Promise<CommentRecord> {
262
+ const trimmed = body.trim();
263
+ if (!trimmed) throw new Error("Comment cannot be empty.");
264
+
265
+ const db = await getDb();
266
+ const schema = getSchema();
267
+ const rows = await db.select().from(schema.cmsComments).where(eq(schema.cmsComments._id, id)).limit(1);
268
+ const row = rows[0] as any;
269
+ if (!row) throw new Error("Comment not found.");
270
+
271
+ const editedAt = new Date().toISOString();
272
+ await db.update(schema.cmsComments).set({ body: trimmed, editedAt }).where(eq(schema.cmsComments._id, id));
273
+ await recordAudit({
274
+ action: "collab.comment.edit",
275
+ resourceType: "content",
276
+ resourceCollection: row.collection,
277
+ resourceId: row.documentId,
278
+ actor,
279
+ });
280
+ return { ...(row as CommentRecord), body: trimmed, editedAt };
281
+ },
282
+
226
283
  async resolveComment(id: string, resolved: boolean, actor: AuditActor): Promise<void> {
227
284
  const db = await getDb();
228
285
  const schema = getSchema();
@@ -274,3 +331,19 @@ export const collaboration = {
274
331
  return rows as ActivityRecord[];
275
332
  },
276
333
  };
334
+
335
+ /**
336
+ * Drops a document's collaboration row and its comments. Called when the document
337
+ * itself is deleted — a review row with no document behind it would still be
338
+ * counted and listed as outstanding work.
339
+ */
340
+ export const removeCollaborationFor = async (collection: string, documentId: string): Promise<void> => {
341
+ const db = await getDb();
342
+ const schema = getSchema();
343
+ await db
344
+ .delete(schema.cmsCollaboration)
345
+ .where(and(eq(schema.cmsCollaboration.collection, collection), eq(schema.cmsCollaboration.documentId, documentId)));
346
+ await db
347
+ .delete(schema.cmsComments)
348
+ .where(and(eq(schema.cmsComments.collection, collection), eq(schema.cmsComments.documentId, documentId)));
349
+ };
package/core/generator.ts CHANGED
@@ -80,7 +80,19 @@ const generateMainTable = (collection: CollectionConfig): string => {
80
80
  columns.push(` _updatedAt: text("_updated_at").notNull(),`);
81
81
  }
82
82
 
83
- return `export const ${varName} = sqliteTable("${tableName}", {\n${columns.join("\n")}\n});`;
83
+ // scheduled.processPublishing() sweeps every drafts-enabled collection on each
84
+ // cron tick, filtering on _status plus the due timestamp. Without these it is a
85
+ // full table scan per collection, per tick.
86
+ const indexes: string[] = [];
87
+ if (collection.drafts) {
88
+ const idxPrefix = snakeCase(collection.slug);
89
+ indexes.push(` publishIdx: index("${idxPrefix}_publish_idx").on(table._status, table._publishAt),`);
90
+ indexes.push(` unpublishIdx: index("${idxPrefix}_unpublish_idx").on(table._status, table._unpublishAt),`);
91
+ }
92
+
93
+ const body = `{\n${columns.join("\n")}\n}`;
94
+ if (indexes.length === 0) return `export const ${varName} = sqliteTable("${tableName}", ${body});`;
95
+ return `export const ${varName} = sqliteTable("${tableName}", ${body}, (table) => ({\n${indexes.join("\n")}\n}));`;
84
96
  };
85
97
 
86
98
  const generateTranslationsTable = (config: CMSConfig, collection: CollectionConfig): string | null => {
@@ -177,7 +189,9 @@ const generateSchemaFile = (config: CMSConfig): string => {
177
189
  userId: text("user_id").notNull(),
178
190
  userEmail: text("user_email").notNull(),
179
191
  lockedAt: text("locked_at").notNull(),
180
- });`);
192
+ }, (table) => ({
193
+ docIdx: index("locks_doc_idx").on(table.collection, table.documentId),
194
+ }));`);
181
195
  parts.push("");
182
196
  parts.push(`export const cmsInvites = sqliteTable("cms_invites", {
183
197
  _id: text("_id").primaryKey(),
@@ -247,6 +261,8 @@ const generateSchemaFile = (config: CMSConfig): string => {
247
261
  updatedAt: text("updated_at").notNull(),
248
262
  }, (table) => ({
249
263
  pk: primaryKey({ columns: [table.collection, table.documentId] }),
264
+ editorIdx: index("collaboration_editor_idx").on(table.editor),
265
+ reviewStateIdx: index("collaboration_review_state_idx").on(table.reviewState),
250
266
  }));`);
251
267
  parts.push("");
252
268
  parts.push(`export const cmsComments = sqliteTable("cms_comments", {
@@ -259,6 +275,7 @@ const generateSchemaFile = (config: CMSConfig): string => {
259
275
  authorEmail: text("author_email"),
260
276
  resolved: integer("resolved", { mode: "boolean" }).notNull().default(false),
261
277
  createdAt: text("created_at").notNull(),
278
+ editedAt: text("edited_at"),
262
279
  }, (table) => ({
263
280
  docIdx: index("comments_doc_idx").on(table.collection, table.documentId),
264
281
  }));`);
package/core/index.ts CHANGED
@@ -104,7 +104,7 @@ export type {
104
104
  WithSiteOptions,
105
105
  } from "./define";
106
106
 
107
- export { createCms } from "./api";
107
+ export { createCms, FieldError } from "./api";
108
108
  export type { FindOptions } from "./api";
109
109
 
110
110
  export { enqueueTask, drainTasks, tickSchedules, pruneTasks } from "./tasks";
@@ -194,7 +194,13 @@ export { readLimitedFormData, PayloadTooLargeError } from "./http";
194
194
 
195
195
  export { recordAudit, logAudit, pruneAuditLog, auditRequestMeta, tokenReference } from "./audit";
196
196
  export type { AuditEvent, AuditActor } from "./audit";
197
- export { collaboration, REVIEW_STATES, isReviewState } from "./collaboration";
197
+ export {
198
+ collaboration,
199
+ OPEN_REVIEW_STATES,
200
+ removeCollaborationFor,
201
+ REVIEW_STATES,
202
+ isReviewState,
203
+ } from "./collaboration";
198
204
  export type { ReviewState, CollaborationState, CommentRecord, ActivityRecord } from "./collaboration";
199
205
 
200
206
  export {
@@ -2,6 +2,8 @@ import { defineMiddleware } from "astro:middleware";
2
2
  import type { APIContext, MiddlewareNext } from "astro";
3
3
  import { readEnv, resolveAdminAuth, runWithRequestScope } from "../core";
4
4
  import type { RequestScope, SessionUser } from "../core";
5
+ import { eq } from "drizzle-orm";
6
+
5
7
  import config from "virtual:kide/config";
6
8
  import { getSessionUser } from "virtual:kide/runtime";
7
9
  import { getDb } from "virtual:kide/db";
@@ -142,7 +144,11 @@ const handle = async (context: APIContext, next: MiddlewareNext) => {
142
144
  const schema = await import("virtual:kide/schema");
143
145
  const tables = schema.cmsTables as Record<string, { main: any }>;
144
146
  if (tables.users) {
145
- const rows = await db.select().from(tables.users.main).limit(1);
147
+ // Setup is complete once an *admin* exists, not merely a user. Seeded demo
148
+ // editors (or an invite-created editor) would otherwise skip first-run
149
+ // setup and leave the project with no way in. The API guards deleting or
150
+ // demoting the last admin, so "no admin" only ever means "not set up yet".
151
+ const rows = await db.select().from(tables.users.main).where(eq(tables.users.main.role, "admin")).limit(1);
146
152
  hasUsers = rows.length > 0;
147
153
  } else {
148
154
  hasUsers = true;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kidecms/core",
3
- "version": "0.19.1",
3
+ "version": "0.20.0",
4
4
  "description": "Kide CMS runtime — core library, admin UI, routes, and middleware for Astro. Shipped as TypeScript source.",
5
5
  "keywords": [
6
6
  "cms",
@@ -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
  }