@kidecms/core 0.1.11 → 0.14.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 (180) hide show
  1. package/LICENSE +21 -0
  2. package/admin/components/AssetsGrid.tsx +366 -173
  3. package/admin/components/BlockEditor.tsx +260 -679
  4. package/admin/components/CheckboxField.tsx +2 -2
  5. package/admin/components/CollaborationReviewBar.tsx +384 -0
  6. package/admin/components/ColorField.tsx +87 -0
  7. package/admin/components/CommandPalette.tsx +169 -0
  8. package/admin/components/ContentEditor.tsx +687 -0
  9. package/admin/components/DocumentActions.tsx +4 -2
  10. package/admin/components/DocumentsDataTable.tsx +91 -10
  11. package/admin/components/FieldControl.astro +151 -26
  12. package/admin/components/FocalPointSelector.tsx +27 -1
  13. package/admin/components/InternalLinkPicker.tsx +4 -3
  14. package/admin/components/LinkField.tsx +126 -0
  15. package/admin/components/RelationField.tsx +105 -26
  16. package/admin/components/RepeaterInput.tsx +46 -0
  17. package/admin/components/RichTextEditor.tsx +44 -9
  18. package/admin/components/SharedSectionBlockField.tsx +93 -0
  19. package/admin/components/SidebarUserMenu.tsx +1 -1
  20. package/admin/components/Toast.astro +1 -1
  21. package/admin/components/TreeItemsEditor.tsx +20 -19
  22. package/admin/components/TreeSelect.tsx +2 -2
  23. package/admin/components/YoutubeField.tsx +48 -0
  24. package/admin/components/block-fields.tsx +777 -0
  25. package/admin/components/content-block-spec.ts +114 -0
  26. package/admin/components/slash-command.tsx +242 -0
  27. package/admin/components/tree-utils.ts +14 -2
  28. package/admin/components/ui/badge.tsx +2 -3
  29. package/admin/components/ui/button.tsx +5 -4
  30. package/admin/components/ui/checkbox.tsx +1 -1
  31. package/admin/components/ui/input.tsx +1 -1
  32. package/admin/components/ui/select.tsx +1 -1
  33. package/admin/components/ui/table.tsx +1 -1
  34. package/admin/components/ui/textarea.tsx +1 -1
  35. package/admin/layouts/AdminLayout.astro +323 -123
  36. package/admin/lib/access.ts +54 -0
  37. package/admin/lib/collaboration.ts +178 -0
  38. package/admin/lib/edit-data.ts +448 -0
  39. package/admin/views/AccessDeniedView.astro +8 -0
  40. package/admin/views/EditView.astro +706 -0
  41. package/admin/views/ListView.astro +202 -0
  42. package/admin/views/RecentView.astro +76 -0
  43. package/admin/views/SinglesView.astro +65 -0
  44. package/admin/views/edit/EditScripts.astro +145 -0
  45. package/admin/views/edit/ReverseReferencesList.astro +68 -0
  46. package/core/admin.ts +193 -0
  47. package/core/ai.ts +87 -0
  48. package/core/api.ts +1392 -0
  49. package/core/assets.ts +336 -0
  50. package/core/audit.ts +86 -0
  51. package/core/auth-config.ts +44 -0
  52. package/core/auth.ts +303 -0
  53. package/core/collaboration.ts +276 -0
  54. package/core/content.ts +27 -0
  55. package/core/create-admin.ts +28 -0
  56. package/core/define.ts +623 -0
  57. package/core/field-model.ts +172 -0
  58. package/core/generator.ts +519 -0
  59. package/core/http.ts +42 -0
  60. package/core/image.ts +219 -0
  61. package/core/index.ts +211 -0
  62. package/core/locks.ts +52 -0
  63. package/core/log.ts +37 -0
  64. package/core/migrate.ts +278 -0
  65. package/core/rate-limit.ts +110 -0
  66. package/core/request-scope.ts +33 -0
  67. package/core/richtext.ts +1 -0
  68. package/core/runtime.ts +63 -0
  69. package/core/schema.ts +32 -0
  70. package/core/search.ts +489 -0
  71. package/core/seed.ts +101 -0
  72. package/core/shared-sections.ts +96 -0
  73. package/core/tasks.ts +176 -0
  74. package/core/values.ts +433 -0
  75. package/core/webhooks.ts +85 -0
  76. package/core/youtube.ts +39 -0
  77. package/internals/cli.mjs +34 -0
  78. package/internals/context.ts +67 -0
  79. package/internals/create-admin.ts +40 -0
  80. package/internals/describe.ts +25 -0
  81. package/internals/eject.ts +144 -0
  82. package/internals/generator.ts +11 -0
  83. package/internals/integration.ts +481 -0
  84. package/internals/mcp.ts +397 -0
  85. package/internals/project.ts +31 -0
  86. package/internals/push.ts +160 -0
  87. package/internals/reindex.ts +11 -0
  88. package/internals/restore.ts +257 -0
  89. package/internals/seed.ts +15 -0
  90. package/internals/upgrade.ts +785 -0
  91. package/{virtual.d.ts → internals/virtual.d.ts} +39 -5
  92. package/middleware/auth.ts +130 -17
  93. package/middleware/push.ts +121 -0
  94. package/package.json +55 -67
  95. package/platform/cloudflare/cf-env.ts +60 -0
  96. package/platform/cloudflare/database.ts +28 -0
  97. package/platform/cloudflare/globals.d.ts +5 -0
  98. package/platform/cloudflare/storage.ts +33 -0
  99. package/platform/cloudflare/uploads-route.ts +37 -0
  100. package/platform/node/database.ts +39 -0
  101. package/platform/node/storage.ts +52 -0
  102. package/routes/admin/[...path].astro +71 -0
  103. package/routes/{pages/admin → admin}/assets/[id].astro +25 -19
  104. package/routes/admin/assets/index.astro +90 -0
  105. package/routes/{pages/admin/login.astro → admin/forgot-password.astro} +21 -19
  106. package/routes/{pages/admin → admin}/invite.astro +13 -6
  107. package/routes/admin/login.astro +103 -0
  108. package/routes/admin/reset-password.astro +73 -0
  109. package/routes/{pages/admin → admin}/setup.astro +32 -8
  110. package/routes/api/{cms/[collection] → [collection]}/[...path].ts +67 -15
  111. package/routes/api/admin/search.ts +89 -0
  112. package/routes/api/{cms/assets → assets}/[id].ts +24 -14
  113. package/routes/api/{cms/assets → assets}/index.ts +4 -2
  114. package/routes/api/assets/upload.ts +147 -0
  115. package/routes/api/auth/forgot-password.ts +77 -0
  116. package/routes/api/{cms/auth → auth}/invite.ts +41 -9
  117. package/routes/api/auth/login.ts +167 -0
  118. package/routes/api/{cms/auth → auth}/logout.ts +11 -2
  119. package/routes/api/auth/reset-password.ts +85 -0
  120. package/routes/api/auth/setup.ts +110 -0
  121. package/routes/api/auth/sso/[provider]/start.ts +34 -0
  122. package/routes/api/collaboration/index.ts +106 -0
  123. package/routes/api/cron/_authorize.ts +25 -0
  124. package/routes/api/{cms/cron → cron}/publish.ts +3 -9
  125. package/routes/api/cron/tasks.ts +34 -0
  126. package/routes/api/forms/submit/[slug].ts +143 -0
  127. package/routes/api/img/[...path].ts +65 -0
  128. package/routes/api/{cms/preview → preview}/render.ts +8 -3
  129. package/routes/api/{cms/references → references}/[collection]/[id].ts +31 -1
  130. package/routes/api/webhooks/[provider].ts +54 -0
  131. package/README.md +0 -28
  132. package/dist/admin.d.ts +0 -33
  133. package/dist/admin.js +0 -92
  134. package/dist/ai.d.ts +0 -15
  135. package/dist/ai.js +0 -70
  136. package/dist/api.d.ts +0 -14
  137. package/dist/api.js +0 -833
  138. package/dist/assets.d.ts +0 -51
  139. package/dist/assets.js +0 -163
  140. package/dist/auth.d.ts +0 -30
  141. package/dist/auth.js +0 -132
  142. package/dist/content.d.ts +0 -3
  143. package/dist/content.js +0 -29
  144. package/dist/create-admin.d.ts +0 -5
  145. package/dist/create-admin.js +0 -23
  146. package/dist/define.d.ts +0 -254
  147. package/dist/define.js +0 -36
  148. package/dist/generator.d.ts +0 -9
  149. package/dist/generator.js +0 -370
  150. package/dist/image.d.ts +0 -9
  151. package/dist/image.js +0 -69
  152. package/dist/index.d.ts +0 -28
  153. package/dist/index.js +0 -16
  154. package/dist/integration.d.ts +0 -14
  155. package/dist/integration.js +0 -327
  156. package/dist/locks.d.ts +0 -7
  157. package/dist/locks.js +0 -37
  158. package/dist/richtext.d.ts +0 -1
  159. package/dist/richtext.js +0 -1
  160. package/dist/runtime.d.ts +0 -24
  161. package/dist/runtime.js +0 -26
  162. package/dist/schema.d.ts +0 -17
  163. package/dist/schema.js +0 -13
  164. package/dist/seed.d.ts +0 -2
  165. package/dist/seed.js +0 -84
  166. package/dist/values.d.ts +0 -8
  167. package/dist/values.js +0 -102
  168. package/dist/webhooks.d.ts +0 -2
  169. package/dist/webhooks.js +0 -73
  170. package/routes/api/cms/assets/upload.ts +0 -112
  171. package/routes/api/cms/auth/login.ts +0 -124
  172. package/routes/api/cms/auth/setup.ts +0 -77
  173. package/routes/api/cms/img/[...path].ts +0 -24
  174. package/routes/pages/admin/[...path].astro +0 -1107
  175. package/routes/pages/admin/assets/index.astro +0 -63
  176. /package/routes/api/{cms/ai → ai}/alt-text.ts +0 -0
  177. /package/routes/api/{cms/ai → ai}/seo.ts +0 -0
  178. /package/routes/api/{cms/ai → ai}/translate.ts +0 -0
  179. /package/routes/api/{cms/assets → assets}/folders.ts +0 -0
  180. /package/routes/api/{cms/locks → locks}/[...path].ts +0 -0
package/core/api.ts ADDED
@@ -0,0 +1,1392 @@
1
+ import { and, asc, desc, eq, inArray, like, lte, ne, or, sql } from "drizzle-orm";
2
+ import { nanoid } from "nanoid";
3
+
4
+ import { recordAudit, type AuditActor } from "./audit";
5
+ import { hashPassword, MIN_PASSWORD_LENGTH } from "./auth";
6
+ import type { CMSConfig, CollectionConfig, FieldConfig, RichTextDocument } from "./define";
7
+ import { getCollectionMap, getTranslatableFieldNames, isStructuralField } from "./define";
8
+ import { getDb, trackTask } from "./runtime";
9
+ import { getSchema } from "./schema";
10
+ import { indexDocument, isCollectionSearchable, removeDocument } from "./search";
11
+ import { drainTasks, enqueueTask, pruneTasks, tickSchedules, type EnqueueTaskOptions } from "./tasks";
12
+ import { cloneValue, createRichTextFromPlainText, slugify } from "./values";
13
+ import { dispatchWebhooks } from "./webhooks";
14
+
15
+ export type FindOptions = {
16
+ where?: Record<string, unknown>;
17
+ sort?: {
18
+ field: string;
19
+ direction: "asc" | "desc";
20
+ };
21
+ limit?: number;
22
+ offset?: number;
23
+ status?: "draft" | "published" | "scheduled" | "any";
24
+ locale?: string;
25
+ search?: string;
26
+ };
27
+
28
+ type RuntimeContext = {
29
+ user?: {
30
+ id: string;
31
+ role?: string;
32
+ email?: string;
33
+ [key: string]: unknown;
34
+ } | null;
35
+ cache?: {
36
+ invalidate: (opts: { tags: string[] }) => void | Promise<void>;
37
+ };
38
+ /** Bypass access rules (server-side / migration / system operations). */
39
+ _system?: boolean;
40
+ /**
41
+ * Skip the fire-and-forget search (re)indexing this operation would trigger.
42
+ * Useful for bulk imports — index once afterwards with `reindexAll()`.
43
+ */
44
+ _skipSearch?: boolean;
45
+ };
46
+
47
+ type CMSOperation = "read" | "create" | "update" | "delete" | "publish" | "schedule";
48
+
49
+ const now = () => new Date().toISOString();
50
+
51
+ const pick = (input: Record<string, unknown>, keys: string[]) =>
52
+ Object.fromEntries(keys.filter((key) => key in input).map((key) => [key, input[key]]));
53
+
54
+ const isJsonField = (field: FieldConfig) =>
55
+ field.type === "richText" ||
56
+ field.type === "content" ||
57
+ field.type === "array" ||
58
+ field.type === "json" ||
59
+ field.type === "blocks" ||
60
+ (field.type === "relation" && field.hasMany);
61
+
62
+ const ensureCollection = (config: CMSConfig, slug: string) => {
63
+ const collection = getCollectionMap(config)[slug];
64
+ if (!collection) {
65
+ const available = config.collections.map((collectionEntry) => collectionEntry.slug).join(", ");
66
+ throw new Error(`Unknown collection "${slug}". Available collections: ${available}`);
67
+ }
68
+ return collection;
69
+ };
70
+
71
+ const getDefaultStatus = (collection: CollectionConfig) => (collection.drafts ? "draft" : "published");
72
+
73
+ const isEmptyValue = (value: unknown) =>
74
+ value === undefined || value === null || value === "" || (Array.isArray(value) && value.length === 0);
75
+
76
+ const coerceString = (value: unknown) => (value === null ? "" : String(value).trim());
77
+ const coerceNumber = (value: unknown) => (value === "" || value === null ? undefined : Number(value));
78
+ const coerceBoolean = (value: unknown) =>
79
+ value === true || value === "true" || value === "on" || value === 1 || value === "1";
80
+
81
+ const coerceRelation = (field: FieldConfig, value: unknown) => {
82
+ if (!("hasMany" in field && field.hasMany)) return value ? String(value) : "";
83
+ if (Array.isArray(value)) return value.map((item) => String(item));
84
+
85
+ const stringValue = String(value).trim();
86
+ if (stringValue.startsWith("[")) {
87
+ try {
88
+ const parsed = JSON.parse(stringValue);
89
+ if (Array.isArray(parsed)) return parsed.map((item: unknown) => String(item)).filter(Boolean);
90
+ } catch {
91
+ // fall through to comma split
92
+ }
93
+ }
94
+
95
+ return stringValue
96
+ .split(",")
97
+ .map((item) => item.trim())
98
+ .filter(Boolean);
99
+ };
100
+
101
+ const coerceArray = (value: unknown) => {
102
+ if (Array.isArray(value)) return value;
103
+ if (typeof value === "string") {
104
+ return value
105
+ .split(/\n|,/)
106
+ .map((item) => item.trim())
107
+ .filter(Boolean);
108
+ }
109
+ return [];
110
+ };
111
+
112
+ const coerceJsonOrBlocks = (field: FieldConfig, value: unknown) => {
113
+ const fallback = field.defaultValue ?? (field.type === "blocks" ? [] : {});
114
+ if (typeof value === "string") {
115
+ const trimmed = value.trim();
116
+ return trimmed ? JSON.parse(trimmed) : fallback;
117
+ }
118
+ return value ?? fallback;
119
+ };
120
+
121
+ const coerceRichText = (value: unknown) => {
122
+ if (typeof value === "string") {
123
+ const trimmed = value.trim();
124
+ if (trimmed.startsWith("{")) {
125
+ try {
126
+ const parsed = JSON.parse(trimmed);
127
+ if (parsed?.type === "root") return parsed;
128
+ } catch {}
129
+ }
130
+ return createRichTextFromPlainText(value);
131
+ }
132
+ return (value as RichTextDocument | undefined) ?? createRichTextFromPlainText("");
133
+ };
134
+
135
+ const coerceFieldValue = (field: FieldConfig, value: unknown): unknown => {
136
+ if (value === undefined) return undefined;
137
+
138
+ switch (field.type) {
139
+ case "text":
140
+ case "slug":
141
+ case "email":
142
+ case "image":
143
+ case "date":
144
+ return coerceString(value);
145
+ case "number":
146
+ return coerceNumber(value);
147
+ case "boolean":
148
+ return coerceBoolean(value);
149
+ case "select":
150
+ return value === "" || value === null ? "" : String(value);
151
+ case "relation":
152
+ return coerceRelation(field, value);
153
+ case "array":
154
+ return coerceArray(value);
155
+ case "json":
156
+ case "blocks":
157
+ return coerceJsonOrBlocks(field, value);
158
+ case "richText":
159
+ case "content":
160
+ return coerceRichText(value);
161
+ default:
162
+ return value;
163
+ }
164
+ };
165
+
166
+ const prepareIncomingData = (
167
+ collection: CollectionConfig,
168
+ input: Record<string, unknown>,
169
+ locale: string | undefined,
170
+ existing?: Record<string, unknown>,
171
+ ) => {
172
+ const data: Record<string, unknown> = {};
173
+ const translatableFields = new Set(getTranslatableFieldNames(collection));
174
+
175
+ for (const [fieldName, field] of Object.entries(collection.fields)) {
176
+ if (locale && !translatableFields.has(fieldName)) continue;
177
+ if (!locale && translatableFields.has(fieldName) && input[fieldName] === undefined && existing) continue;
178
+
179
+ const rawValue = input[fieldName];
180
+ const coercedValue = coerceFieldValue(field, rawValue);
181
+
182
+ if (coercedValue === undefined) {
183
+ if (!existing && field.defaultValue !== undefined) {
184
+ data[fieldName] = cloneValue(field.defaultValue);
185
+ }
186
+ continue;
187
+ }
188
+
189
+ data[fieldName] = coercedValue;
190
+ }
191
+
192
+ for (const [fieldName, field] of Object.entries(collection.fields)) {
193
+ if (field.type !== "slug") continue;
194
+ if (!isEmptyValue(data[fieldName])) {
195
+ data[fieldName] = slugify(String(data[fieldName]));
196
+ continue;
197
+ }
198
+ const sourceField = field.from;
199
+ const sourceValue = sourceField ? (data[sourceField] ?? input[sourceField]) : undefined;
200
+ if (sourceValue) data[fieldName] = slugify(String(sourceValue));
201
+ }
202
+
203
+ for (const [fieldName, field] of Object.entries(collection.fields)) {
204
+ if (!field.required) continue;
205
+ const candidate = data[fieldName] ?? existing?.[fieldName];
206
+ if (isEmptyValue(candidate)) throw new Error(`Field "${fieldName}" is required.`);
207
+ }
208
+
209
+ for (const [fieldName, field] of Object.entries(collection.fields)) {
210
+ const maxItems = "maxItems" in field ? field.maxItems : undefined;
211
+ if (!maxItems) continue;
212
+ const candidate = data[fieldName] ?? existing?.[fieldName];
213
+ if (Array.isArray(candidate) && candidate.length > maxItems) {
214
+ throw new Error(`Field "${fieldName}" allows at most ${maxItems} item${maxItems === 1 ? "" : "s"}.`);
215
+ }
216
+ }
217
+
218
+ return data;
219
+ };
220
+
221
+ const serializeForDb = (collection: CollectionConfig, data: Record<string, unknown>): Record<string, unknown> => {
222
+ const result: Record<string, unknown> = {};
223
+ for (const [key, value] of Object.entries(data)) {
224
+ const field = collection.fields[key];
225
+ result[key] = field && isJsonField(field) && value !== undefined && value !== null ? JSON.stringify(value) : value;
226
+ }
227
+ return result;
228
+ };
229
+
230
+ const deserializeFromDb = (collection: CollectionConfig, row: Record<string, unknown>): Record<string, unknown> => {
231
+ const result: Record<string, unknown> = { ...row };
232
+ for (const [key, field] of Object.entries(collection.fields)) {
233
+ if (isJsonField(field) && typeof result[key] === "string") {
234
+ try {
235
+ result[key] = JSON.parse(result[key] as string);
236
+ } catch {
237
+ // leave as string if not valid JSON
238
+ }
239
+ }
240
+ }
241
+ return result;
242
+ };
243
+
244
+ /** Auth collections are default-deny: admin-only, non-admins limited to their own row. */
245
+ const defaultAuthAccess = (operation: CMSOperation, context: RuntimeContext, doc?: Record<string, unknown> | null) => {
246
+ const user = context.user;
247
+ if (!user) return false;
248
+ if (user.role === "admin") return true;
249
+ if (operation === "read" || operation === "update") return !!doc && doc._id === user.id;
250
+ return false;
251
+ };
252
+
253
+ /** Auth collections have an implicit read rule, so reads need per-document filtering. */
254
+ const hasReadRule = (collection: CollectionConfig) => !!collection.access?.read || !!collection.auth;
255
+
256
+ const canAccess = async (
257
+ collection: CollectionConfig,
258
+ operation: CMSOperation,
259
+ context: RuntimeContext,
260
+ doc?: Record<string, unknown> | null,
261
+ ) => {
262
+ if (context._system) return true;
263
+ const rule = collection.access?.[operation];
264
+ if (rule) {
265
+ return rule({ user: context.user ?? null, doc: doc ?? null, operation, collection: collection.slug });
266
+ }
267
+ if (collection.auth) return defaultAuthAccess(operation, context, doc);
268
+ return true;
269
+ };
270
+
271
+ /** SQL predicate: another admin besides `excludeId` exists — for the atomic last-admin guards. */
272
+ const anotherAdminExists = (mainTable: any, excludeId: string) =>
273
+ sql`EXISTS (SELECT 1 FROM ${mainTable} WHERE role = 'admin' AND _id != ${excludeId})`;
274
+
275
+ /** Count admin rows in an auth collection's main table. */
276
+ const countAdmins = async (db: any, mainTable: any): Promise<number> => {
277
+ const rows = await db.select({ _id: mainTable._id }).from(mainTable).where(eq(mainTable.role, "admin"));
278
+ return rows.length;
279
+ };
280
+
281
+ const canWriteAuthField = (fieldName: string, context: RuntimeContext, doc?: Record<string, unknown> | null) => {
282
+ const user = context.user;
283
+ if (user?.role === "admin") return true;
284
+ if (fieldName === "role") return false;
285
+ return !!user && !!doc && doc._id === user.id;
286
+ };
287
+
288
+ /** On create only `role` is privileged; a password on a new account escalates nothing. */
289
+ const stripProtectedAuthFields = (
290
+ collection: CollectionConfig,
291
+ data: Record<string, unknown>,
292
+ context: RuntimeContext,
293
+ operation: "create" | "update",
294
+ doc?: Record<string, unknown> | null,
295
+ ) => {
296
+ if (!collection.auth || context._system) return;
297
+ const protectedFields = operation === "create" ? ["role"] : ["role", "password"];
298
+ for (const fieldName of protectedFields) {
299
+ if (data[fieldName] === undefined) continue;
300
+ if (collection.fields[fieldName]?.access?.update) continue;
301
+ if (!canWriteAuthField(fieldName, context, doc)) delete data[fieldName];
302
+ }
303
+ };
304
+
305
+ const stripUnwritableFields = async (
306
+ collection: CollectionConfig,
307
+ data: Record<string, unknown>,
308
+ context: RuntimeContext,
309
+ doc: Record<string, unknown> | null,
310
+ ) => {
311
+ if (context._system) return;
312
+ const operation = doc ? "update" : "create";
313
+ const accessCtx = { user: context.user ?? null, doc, operation, collection: collection.slug };
314
+ for (const [fieldName, field] of Object.entries(collection.fields)) {
315
+ if (!field.access?.update || data[fieldName] === undefined) continue;
316
+ if (!(await field.access.update(accessCtx))) delete data[fieldName];
317
+ }
318
+ };
319
+
320
+ /** Unreadable fields are omitted entirely, matching how `password` is handled. */
321
+ const stripUnreadableFields = async (
322
+ collection: CollectionConfig,
323
+ doc: Record<string, unknown>,
324
+ context: RuntimeContext,
325
+ ) => {
326
+ if (context._system) return doc;
327
+ const accessCtx = { user: context.user ?? null, doc, operation: "read", collection: collection.slug };
328
+ let result = doc;
329
+ for (const [fieldName, field] of Object.entries(collection.fields)) {
330
+ if (!field.access?.read || !(fieldName in result)) continue;
331
+ if (!(await field.access.read(accessCtx))) {
332
+ if (result === doc) result = { ...doc };
333
+ delete result[fieldName];
334
+ }
335
+ }
336
+ return result;
337
+ };
338
+
339
+ const collectionHasFieldReadRules = (collection: CollectionConfig) =>
340
+ Object.values(collection.fields).some((field) => !!field.access?.read);
341
+
342
+ const getHookContext = (collection: CollectionConfig, operation: string, context: RuntimeContext) => ({
343
+ user: context.user ?? null,
344
+ operation,
345
+ collection: collection.slug,
346
+ timestamp: now(),
347
+ cache: context.cache,
348
+ });
349
+
350
+ const toAuditActor = (context: RuntimeContext): AuditActor => {
351
+ if (!context.user) return null;
352
+ return {
353
+ id: context.user.id,
354
+ email: context.user.email ?? "",
355
+ role: context.user.role ?? "",
356
+ };
357
+ };
358
+
359
+ const auditContent = (action: string, slug: string, resourceId: string, context: RuntimeContext) => {
360
+ trackTask(
361
+ recordAudit({
362
+ action,
363
+ resourceType: "content",
364
+ resourceCollection: slug,
365
+ resourceId,
366
+ actor: toAuditActor(context),
367
+ }),
368
+ );
369
+ };
370
+
371
+ const syncSearch = (config: CMSConfig, collection: CollectionConfig, docId: string) => {
372
+ if (!isCollectionSearchable(collection)) return;
373
+ const locales = config.locales?.supported ?? [];
374
+ trackTask(indexDocument(collection, docId, locales));
375
+ };
376
+
377
+ const removeSearch = (collection: CollectionConfig, docId: string) => {
378
+ if (!isCollectionSearchable(collection)) return;
379
+ trackTask(removeDocument(collection.slug, docId));
380
+ };
381
+
382
+ // Test-only: pauses update() before its role write, to force a concurrency test's interleaving.
383
+ export const __testHooks = { beforeRoleWrite: null as null | (() => Promise<void>) };
384
+
385
+ const getTableRefs = async (collectionSlug: string) => {
386
+ const tables = getSchema().cmsTables[collectionSlug] as {
387
+ main: any;
388
+ translations?: any;
389
+ versions?: any;
390
+ };
391
+
392
+ if (!tables) throw new Error(`No tables found for collection "${collectionSlug}".`);
393
+ return tables;
394
+ };
395
+
396
+ export const createCms = (config: CMSConfig) => {
397
+ // A partially-evaluated config here means a module cycle: cms.config.ts
398
+ // statically imported a module that itself imports the generated API (which
399
+ // imports cms.config.ts back). Fail with a diagnosis instead of a cryptic
400
+ // "reading 'collections'" crash at first use.
401
+ if (!config?.collections) {
402
+ throw new Error(
403
+ "createCms received an incomplete config — usually a module cycle: cms.config.ts statically imports " +
404
+ "a module that uses the generated cms API. Register such code lazily instead, e.g. " +
405
+ '"my.task": () => import("@/lib/handler").then((mod) => mod.run()).',
406
+ );
407
+ }
408
+ const collectionMap = getCollectionMap(config);
409
+
410
+ // Webhook `name` routes deliveries — must be unique and non-empty.
411
+ const webhookNames = (config.admin?.webhooks ?? []).map((webhook) => webhook.name.trim());
412
+ if (webhookNames.some((name) => name === "")) {
413
+ throw new Error("A webhook in admin.webhooks has a blank name — names must be unique and non-empty.");
414
+ }
415
+ const seenWebhookNames = new Set<string>();
416
+ for (const name of webhookNames) {
417
+ if (seenWebhookNames.has(name)) {
418
+ throw new Error(`Duplicate webhook name "${name}" in admin.webhooks — names must be unique.`);
419
+ }
420
+ seenWebhookNames.add(name);
421
+ }
422
+
423
+ const createCollectionApi = (slug: string) => {
424
+ const collection = ensureCollection(config, slug);
425
+
426
+ const overlayLocale = (
427
+ doc: Record<string, unknown>,
428
+ translations: Array<Record<string, unknown>>,
429
+ locale?: string | null,
430
+ ) => {
431
+ const baseDoc = { ...doc };
432
+ const translatableFields = getTranslatableFieldNames(collection);
433
+ const availableLocales = [...new Set(translations.map((translation) => String(translation._languageCode)))];
434
+
435
+ if (locale) {
436
+ const translation = translations.find((entry) => entry._languageCode === locale);
437
+ if (translation) {
438
+ for (const fieldName of translatableFields) {
439
+ if (translation[fieldName] !== undefined && translation[fieldName] !== null) {
440
+ baseDoc[fieldName] = translation[fieldName];
441
+ }
442
+ }
443
+ }
444
+ }
445
+
446
+ return {
447
+ ...baseDoc,
448
+ _availableLocales: availableLocales,
449
+ _locale: locale ?? null,
450
+ };
451
+ };
452
+
453
+ const stripSensitiveFields = (doc: Record<string, unknown>) => {
454
+ if (!collection.auth) return doc;
455
+ const { password: _password, ...rest } = doc;
456
+ return rest;
457
+ };
458
+
459
+ const hasFieldReadRules = collectionHasFieldReadRules(collection);
460
+
461
+ /** Everything a document passes through on its way out of a read. */
462
+ const finalizeRead = async (doc: Record<string, unknown>, context: RuntimeContext) => {
463
+ const stripped = stripSensitiveFields(doc);
464
+ if (!hasFieldReadRules) return stripped;
465
+ return stripUnreadableFields(collection, stripped, context);
466
+ };
467
+
468
+ /** Read guard for the document-scoped reads that bypass `findById`. */
469
+ const assertReadable = async (id: string, context: RuntimeContext) => {
470
+ if (context._system) return;
471
+ const db = await getDb();
472
+ const tables = await getTableRefs(slug);
473
+ const rows = await db.select().from(tables.main).where(eq(tables.main._id, id)).limit(1);
474
+ if (rows.length === 0) return;
475
+ const doc = deserializeFromDb(collection, rows[0] as Record<string, unknown>);
476
+ if (!(await canAccess(collection, "read", context, doc))) {
477
+ throw new Error(`Access denied for ${collection.slug}.`);
478
+ }
479
+ };
480
+
481
+ const applyPublishedSnapshot = (row: Record<string, unknown>, status: FindOptions["status"]) => {
482
+ const doc = deserializeFromDb(collection, row);
483
+ if (status === "published" && typeof row._published === "string") {
484
+ try {
485
+ const snapshot = JSON.parse(row._published);
486
+ for (const key of Object.keys(collection.fields)) {
487
+ if (key in snapshot) doc[key] = snapshot[key];
488
+ }
489
+ } catch {}
490
+ }
491
+ return doc;
492
+ };
493
+
494
+ const filterReadableDocs = async (docs: Array<Record<string, unknown>>, context: RuntimeContext) => {
495
+ if (!hasReadRule(collection) || context._system) return docs;
496
+ const filtered: Array<Record<string, unknown>> = [];
497
+ for (const doc of docs) {
498
+ if (await canAccess(collection, "read", context, doc)) filtered.push(doc);
499
+ }
500
+ return filtered;
501
+ };
502
+
503
+ return {
504
+ async find(options: FindOptions = {}, context: RuntimeContext = {}) {
505
+ const db = await getDb();
506
+ const tables = await getTableRefs(slug);
507
+ const status = options.status ?? (collection.drafts ? "published" : "any");
508
+ const filterAfterReadAccess = hasReadRule(collection) && !context._system;
509
+
510
+ const conditions: any[] = [];
511
+ if (status !== "any" && collection.drafts) {
512
+ conditions.push(eq(tables.main._status, status));
513
+ }
514
+ if (options.where) {
515
+ const translatableFields = new Set(getTranslatableFieldNames(collection));
516
+ for (const [key, value] of Object.entries(options.where)) {
517
+ if (!(key in tables.main)) continue;
518
+ if (options.locale && tables.translations && translatableFields.has(key)) {
519
+ // Translatable fields live in the translations table for non-default
520
+ // locales: match the effective (overlaid) value — the translation when
521
+ // one exists for this locale, the main-table value otherwise. Without
522
+ // this, e.g. findOne({ slug, locale: "en" }) can never match a
523
+ // translated slug.
524
+ const tr = tables.translations;
525
+ conditions.push(
526
+ sql`(EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale} AND ${tr[key]} = ${value}) OR (${tables.main[key]} = ${value} AND NOT EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale} AND ${tr[key]} IS NOT NULL)))`,
527
+ );
528
+ } else {
529
+ conditions.push(eq(tables.main[key], value));
530
+ }
531
+ }
532
+ }
533
+
534
+ if (options.search?.trim()) {
535
+ const searchTerm = `%${options.search.trim().toLowerCase()}%`;
536
+ const searchableTypes = new Set(["text", "slug", "email", "select"]);
537
+ const searchConditions = Object.entries(collection.fields)
538
+ .filter(([, field]) => searchableTypes.has(field.type))
539
+ .filter(([name]) => name in tables.main)
540
+ .map(([name]) => like(sql`lower(${tables.main[name]})`, searchTerm));
541
+ if (searchConditions.length > 0) {
542
+ conditions.push(or(...searchConditions)!);
543
+ }
544
+ }
545
+
546
+ let query = db.select().from(tables.main);
547
+ if (conditions.length > 0) {
548
+ query = query.where(conditions.length === 1 ? conditions[0] : and(...conditions)) as any;
549
+ }
550
+
551
+ if (options.sort) {
552
+ const col = tables.main[options.sort.field];
553
+ if (col) {
554
+ query = query.orderBy(options.sort.direction === "desc" ? desc(col) : asc(col)) as any;
555
+ }
556
+ }
557
+
558
+ if (!filterAfterReadAccess) {
559
+ if (options.limit) query = query.limit(options.limit) as any;
560
+ if (options.offset) query = query.offset(options.offset) as any;
561
+ }
562
+
563
+ const rows = await query;
564
+ let docs = await filterReadableDocs(
565
+ rows.map((row: Record<string, unknown>) => applyPublishedSnapshot(row, status)),
566
+ context,
567
+ );
568
+ if (filterAfterReadAccess) {
569
+ const start = options.offset ?? 0;
570
+ const end = options.limit ? start + options.limit : undefined;
571
+ docs = docs.slice(start, end);
572
+ }
573
+
574
+ if (tables.translations && (options.locale || config.locales)) {
575
+ const docIds = docs.map((doc: Record<string, unknown>) => String(doc._id));
576
+ if (docIds.length > 0) {
577
+ const allTranslations = await db
578
+ .select()
579
+ .from(tables.translations)
580
+ .where(
581
+ sql`${tables.translations._entityId} IN (${sql.join(
582
+ docIds.map((id: string) => sql`${id}`),
583
+ sql`, `,
584
+ )})`,
585
+ );
586
+
587
+ const parsedTranslations = allTranslations.map((translation: Record<string, unknown>) => {
588
+ const parsed = { ...translation };
589
+ const translatableFields = getTranslatableFieldNames(collection);
590
+ for (const fieldName of translatableFields) {
591
+ const field = collection.fields[fieldName];
592
+ if (isJsonField(field) && typeof parsed[fieldName] === "string") {
593
+ try {
594
+ parsed[fieldName] = JSON.parse(parsed[fieldName] as string);
595
+ } catch {}
596
+ }
597
+ }
598
+ return parsed;
599
+ });
600
+
601
+ return Promise.all(
602
+ docs.map((doc: Record<string, unknown>) => {
603
+ const docTranslations = parsedTranslations.filter(
604
+ (translation: Record<string, unknown>) => translation._entityId === doc._id,
605
+ );
606
+ return finalizeRead(overlayLocale(doc, docTranslations, options.locale), context);
607
+ }),
608
+ );
609
+ }
610
+ }
611
+
612
+ return Promise.all(
613
+ docs.map((doc: Record<string, unknown>) => finalizeRead(overlayLocale(doc, [], options.locale), context)),
614
+ );
615
+ },
616
+
617
+ async findOne(
618
+ filter: Record<string, unknown> & { locale?: string; status?: FindOptions["status"] },
619
+ context: RuntimeContext = {},
620
+ ) {
621
+ const docs = await this.find(
622
+ {
623
+ where: pick(filter, Object.keys(collection.fields).concat(["_id", "_status", "slug"])),
624
+ locale: filter.locale,
625
+ status: filter.status,
626
+ limit: 1,
627
+ },
628
+ context,
629
+ );
630
+ return docs[0] ?? null;
631
+ },
632
+
633
+ async findById(
634
+ id: string,
635
+ options: { locale?: string; status?: FindOptions["status"] } = {},
636
+ context: RuntimeContext = {},
637
+ ) {
638
+ const db = await getDb();
639
+ const tables = await getTableRefs(slug);
640
+ const rows = await db.select().from(tables.main).where(eq(tables.main._id, id)).limit(1);
641
+ if (rows.length === 0) return null;
642
+
643
+ const doc = deserializeFromDb(collection, rows[0] as Record<string, unknown>);
644
+ const allowed = await canAccess(collection, "read", context, doc);
645
+ if (!allowed) throw new Error(`Access denied for ${collection.slug}.`);
646
+ if (options.status && options.status !== "any" && doc._status !== options.status) return null;
647
+
648
+ const effectiveStatus = options.status ?? (collection.drafts ? "published" : "any");
649
+ if (effectiveStatus === "published" && typeof (rows[0] as any)._published === "string") {
650
+ try {
651
+ const snapshot = JSON.parse((rows[0] as any)._published);
652
+ for (const key of Object.keys(collection.fields)) {
653
+ if (key in snapshot) doc[key] = snapshot[key];
654
+ }
655
+ } catch {}
656
+ }
657
+
658
+ let translations: Array<Record<string, unknown>> = [];
659
+ if (tables.translations) {
660
+ const rawTranslations = await db
661
+ .select()
662
+ .from(tables.translations)
663
+ .where(eq(tables.translations._entityId, id));
664
+ translations = rawTranslations.map((translation: Record<string, unknown>) => {
665
+ const parsed = { ...translation };
666
+ for (const fieldName of getTranslatableFieldNames(collection)) {
667
+ const field = collection.fields[fieldName];
668
+ if (isJsonField(field) && typeof parsed[fieldName] === "string") {
669
+ try {
670
+ parsed[fieldName] = JSON.parse(parsed[fieldName] as string);
671
+ } catch {}
672
+ }
673
+ }
674
+ return parsed;
675
+ });
676
+ }
677
+
678
+ return finalizeRead(overlayLocale(doc, translations, options.locale), context);
679
+ },
680
+
681
+ async create(data: Record<string, unknown>, context: RuntimeContext = {}) {
682
+ const allowed = await canAccess(collection, "create", context);
683
+ if (!allowed) throw new Error(`Access denied for ${collection.slug}.`);
684
+
685
+ stripProtectedAuthFields(collection, data, context, "create");
686
+ await stripUnwritableFields(collection, data, context, null);
687
+
688
+ const db = await getDb();
689
+ const tables = await getTableRefs(slug);
690
+ const hookContext = getHookContext(collection, "create", context);
691
+ const preparedInput = prepareIncomingData(collection, data, undefined);
692
+
693
+ if (collection.auth && typeof preparedInput.password === "string" && preparedInput.password) {
694
+ if (!context._system && preparedInput.password.length < MIN_PASSWORD_LENGTH) {
695
+ throw new Error(`Password must be at least ${MIN_PASSWORD_LENGTH} characters.`);
696
+ }
697
+ preparedInput.password = await hashPassword(preparedInput.password);
698
+ }
699
+
700
+ const transformedInput = collection.hooks?.beforeCreate
701
+ ? await collection.hooks.beforeCreate(preparedInput, hookContext)
702
+ : preparedInput;
703
+
704
+ const createdAt = now();
705
+ const docId = typeof data._id === "string" ? String(data._id) : nanoid();
706
+ const docValues: Record<string, unknown> = {
707
+ _id: docId,
708
+ ...serializeForDb(collection, transformedInput),
709
+ };
710
+
711
+ if (collection.drafts) {
712
+ const status = data._status === "published" ? "published" : getDefaultStatus(collection);
713
+ docValues._status = status;
714
+ if (status === "published") docValues._publishedAt = createdAt;
715
+ }
716
+ if (collection.timestamps !== false) {
717
+ docValues._createdAt = createdAt;
718
+ docValues._updatedAt = createdAt;
719
+ }
720
+
721
+ await db.insert(tables.main).values(docValues);
722
+
723
+ if (collection.versions && tables.versions) {
724
+ await db.insert(tables.versions).values({
725
+ _id: nanoid(),
726
+ _docId: docId,
727
+ _version: 1,
728
+ _snapshot: JSON.stringify({ ...transformedInput, _status: docValues._status }),
729
+ _createdAt: createdAt,
730
+ });
731
+ }
732
+
733
+ const result = await this.findById(docId, {}, context);
734
+ await collection.hooks?.afterCreate?.(result!, hookContext);
735
+ auditContent("content.create", slug, docId, context);
736
+ if (!context._skipSearch) syncSearch(config, collection, docId);
737
+ dispatchWebhooks(config, "create", slug, result!, context.user);
738
+ return result!;
739
+ },
740
+
741
+ // Create many documents sequentially (avoids DB write contention). Runs the
742
+ // full per-document path — hooks, versions, search, audit, webhooks.
743
+ async createMany(items: Array<Record<string, unknown>>, context: RuntimeContext = {}) {
744
+ const created: Record<string, unknown>[] = [];
745
+ for (const item of items) created.push(await this.create(item, context));
746
+ return created;
747
+ },
748
+
749
+ // Upsert by _id: update when a row with data._id already exists, else create.
750
+ // Pairs with create()'s caller-supplied _id to make imports idempotent
751
+ // (re-runnable) without a wipe-first step.
752
+ async upsert(data: Record<string, unknown>, context: RuntimeContext = {}) {
753
+ const id = typeof data._id === "string" && data._id ? data._id : undefined;
754
+ if (id) {
755
+ const db = await getDb();
756
+ const tables = await getTableRefs(slug);
757
+ const existing = await db
758
+ .select({ _id: tables.main._id })
759
+ .from(tables.main)
760
+ .where(eq(tables.main._id, id))
761
+ .limit(1);
762
+ if (existing.length) {
763
+ const { _id: _ignored, ...rest } = data;
764
+ return this.update(id, rest, context);
765
+ }
766
+ }
767
+ return this.create(data, context);
768
+ },
769
+
770
+ async update(id: string, data: Record<string, unknown>, context: RuntimeContext = {}) {
771
+ const db = await getDb();
772
+ const tables = await getTableRefs(slug);
773
+ const existingRows = await db.select().from(tables.main).where(eq(tables.main._id, id)).limit(1);
774
+ if (existingRows.length === 0) throw new Error(`${collection.labels.singular} not found.`);
775
+
776
+ const existing = deserializeFromDb(collection, existingRows[0] as Record<string, unknown>);
777
+ const allowed = await canAccess(collection, "update", context, existing);
778
+ if (!allowed) throw new Error(`Access denied for ${collection.slug}.`);
779
+
780
+ stripProtectedAuthFields(collection, data, context, "update", existing);
781
+ await stripUnwritableFields(collection, data, context, existing);
782
+
783
+ const hookContext = getHookContext(collection, "update", context);
784
+ const preparedInput = prepareIncomingData(collection, data, undefined, existing);
785
+
786
+ if (collection.auth && typeof preparedInput.password === "string" && preparedInput.password) {
787
+ if (!context._system && preparedInput.password.length < MIN_PASSWORD_LENGTH) {
788
+ throw new Error(`Password must be at least ${MIN_PASSWORD_LENGTH} characters.`);
789
+ }
790
+ preparedInput.password = await hashPassword(preparedInput.password);
791
+ }
792
+
793
+ const transformedInput = collection.hooks?.beforeUpdate
794
+ ? await collection.hooks.beforeUpdate(preparedInput, existing, hookContext)
795
+ : preparedInput;
796
+
797
+ if (collection.drafts && existing._status === "published" && !(existingRows[0] as any)._published) {
798
+ const snapshot: Record<string, unknown> = {};
799
+ for (const fieldName of Object.keys(collection.fields)) {
800
+ if (existing[fieldName] !== undefined) snapshot[fieldName] = existing[fieldName];
801
+ }
802
+ await db
803
+ .update(tables.main)
804
+ .set({ _published: JSON.stringify(snapshot) })
805
+ .where(eq(tables.main._id, id));
806
+ }
807
+
808
+ const updateValues: Record<string, unknown> = {
809
+ ...serializeForDb(collection, transformedInput),
810
+ };
811
+ if (collection.timestamps !== false) {
812
+ updateValues._updatedAt = now();
813
+ }
814
+
815
+ // Guarded live via WHERE, not the stale `existing.role` — a role promoted after this
816
+ // row was read but before this statement runs must still be protected.
817
+ const writesNonAdminRole =
818
+ collection.auth &&
819
+ collection.fields.role &&
820
+ transformedInput.role !== undefined &&
821
+ transformedInput.role !== "admin";
822
+ if (__testHooks.beforeRoleWrite) await __testHooks.beforeRoleWrite();
823
+ if (writesNonAdminRole) {
824
+ const applied = await db
825
+ .update(tables.main)
826
+ .set(updateValues)
827
+ .where(and(eq(tables.main._id, id), or(ne(tables.main.role, "admin"), anotherAdminExists(tables.main, id))))
828
+ .returning({ _id: tables.main._id });
829
+ if (applied.length === 0) throw new Error("Cannot demote the last remaining admin.");
830
+ } else {
831
+ await db.update(tables.main).set(updateValues).where(eq(tables.main._id, id));
832
+ }
833
+
834
+ if (collection.versions && tables.versions) {
835
+ const versionRows = await db
836
+ .select({ maxVersion: sql<number>`coalesce(max(_version), 0)` })
837
+ .from(tables.versions)
838
+ .where(eq(tables.versions._docId, id));
839
+ const nextVersion = Number(versionRows[0]?.maxVersion ?? 0) + 1;
840
+ const maxVersions = collection.versions.max;
841
+
842
+ await db.insert(tables.versions).values({
843
+ _id: nanoid(),
844
+ _docId: id,
845
+ _version: nextVersion,
846
+ _snapshot: JSON.stringify({ ...existing, ...transformedInput }),
847
+ _createdAt: now(),
848
+ });
849
+
850
+ if (maxVersions) {
851
+ const allVersions = await db
852
+ .select()
853
+ .from(tables.versions)
854
+ .where(eq(tables.versions._docId, id))
855
+ .orderBy(desc(tables.versions._version));
856
+ const toDelete = allVersions.slice(maxVersions);
857
+ for (const version of toDelete) {
858
+ await db.delete(tables.versions).where(eq(tables.versions._id, (version as any)._id));
859
+ }
860
+ }
861
+ }
862
+
863
+ const result = await this.findById(id, { status: "any" }, context);
864
+ await collection.hooks?.afterUpdate?.(result!, hookContext);
865
+ auditContent("content.update", slug, id, context);
866
+ syncSearch(config, collection, id);
867
+ dispatchWebhooks(config, "update", slug, result!, context.user);
868
+ return result!;
869
+ },
870
+
871
+ /** Returns true if a row was actually removed (false if not found, or blocked as the last admin). */
872
+ async delete(id: string, context: RuntimeContext = {}): Promise<boolean> {
873
+ const db = await getDb();
874
+ const tables = await getTableRefs(slug);
875
+ const existingRows = await db.select().from(tables.main).where(eq(tables.main._id, id)).limit(1);
876
+ if (existingRows.length === 0) return false;
877
+
878
+ const existing = deserializeFromDb(collection, existingRows[0] as Record<string, unknown>);
879
+ const allowed = await canAccess(collection, "delete", context, existing);
880
+ if (!allowed) throw new Error(`Access denied for ${collection.slug}.`);
881
+
882
+ const hookContext = getHookContext(collection, "delete", context);
883
+ await collection.hooks?.beforeDelete?.(existing, hookContext);
884
+
885
+ // Guarded atomically: removed only if it isn't the sole admin.
886
+ if (collection.auth && collection.fields.role) {
887
+ const removed = await db
888
+ .delete(tables.main)
889
+ .where(and(eq(tables.main._id, id), or(ne(tables.main.role, "admin"), anotherAdminExists(tables.main, id))))
890
+ .returning({ _id: tables.main._id });
891
+ if (removed.length === 0) {
892
+ if (existing.role === "admin") throw new Error("Cannot delete the last remaining admin.");
893
+ return false; // concurrently removed
894
+ }
895
+ } else {
896
+ await db.delete(tables.main).where(eq(tables.main._id, id));
897
+ }
898
+ if (tables.translations) await db.delete(tables.translations).where(eq(tables.translations._entityId, id));
899
+ if (tables.versions) await db.delete(tables.versions).where(eq(tables.versions._docId, id));
900
+
901
+ await collection.hooks?.afterDelete?.(existing, hookContext);
902
+ auditContent("content.delete", slug, id, context);
903
+ removeSearch(collection, id);
904
+ // `existing` is the raw row; every other event dispatches the stripped findById result.
905
+ dispatchWebhooks(config, "delete", slug, stripSensitiveFields(existing), context.user);
906
+ return true;
907
+ },
908
+
909
+ /**
910
+ * Delete every document matching `filter` (equality on top-level columns;
911
+ * empty filter clears the whole collection), along with their translation,
912
+ * version and search-index rows. Returns the number of documents removed.
913
+ *
914
+ * Bulk path by design — per-document `beforeDelete`/`afterDelete` hooks and
915
+ * webhooks are NOT fired unless the collection defines delete hooks, in
916
+ * which case it falls back to the per-document `delete()` path. Intended for
917
+ * migrations/admin bulk actions; use `delete(id)` when you need full side
918
+ * effects on a single document.
919
+ */
920
+ async deleteMany(filter: Record<string, unknown> = {}, context: RuntimeContext = {}) {
921
+ const allowed = await canAccess(collection, "delete", context);
922
+ if (!allowed) throw new Error(`Access denied for ${collection.slug}.`);
923
+
924
+ const db = await getDb();
925
+ const tables = await getTableRefs(slug);
926
+
927
+ const conditions: any[] = [];
928
+ for (const [key, value] of Object.entries(filter)) {
929
+ if (key in tables.main) conditions.push(eq(tables.main[key], value));
930
+ }
931
+ let idQuery = db.select({ _id: tables.main._id }).from(tables.main);
932
+ if (conditions.length > 0) {
933
+ idQuery = idQuery.where(conditions.length === 1 ? conditions[0] : and(...conditions)) as any;
934
+ }
935
+ const ids: string[] = (await idQuery).map((row: { _id: string }) => String(row._id));
936
+ if (ids.length === 0) return 0;
937
+
938
+ const isAuthWithRole = !!(collection.auth && collection.fields.role);
939
+
940
+ // Non-authoritative early error for the common case — the real guard is per-row below.
941
+ if (isAuthWithRole) {
942
+ let adminsInSet = 0;
943
+ for (let i = 0; i < ids.length; i += 200) {
944
+ const chunk = ids.slice(i, i + 200);
945
+ const rows = await db
946
+ .select({ _id: tables.main._id })
947
+ .from(tables.main)
948
+ .where(and(eq(tables.main.role, "admin"), inArray(tables.main._id, chunk)));
949
+ adminsInSet += rows.length;
950
+ }
951
+ if (adminsInSet > 0 && (await countAdmins(db, tables.main)) - adminsInSet < 1) {
952
+ throw new Error("Cannot delete the last remaining admin.");
953
+ }
954
+ }
955
+
956
+ // Per-document path when delete hooks must run — this.delete() already carries the guard.
957
+ if (collection.hooks?.beforeDelete || collection.hooks?.afterDelete) {
958
+ let deleted = 0;
959
+ for (const id of ids) if (await this.delete(id, context)) deleted++;
960
+ return deleted;
961
+ }
962
+
963
+ let deletedIds: string[];
964
+ if (isAuthWithRole) {
965
+ // Every row goes through the same live-checked guard — no admin/non-admin bucketing,
966
+ // or a row promoted after `ids` was built would bulk-delete unconditionally.
967
+ deletedIds = [];
968
+ for (const id of ids) {
969
+ const removed = await db
970
+ .delete(tables.main)
971
+ .where(
972
+ and(eq(tables.main._id, id), or(ne(tables.main.role, "admin"), anotherAdminExists(tables.main, id))),
973
+ )
974
+ .returning({ _id: tables.main._id });
975
+ if (removed.length > 0) deletedIds.push(id);
976
+ }
977
+ for (const id of deletedIds) {
978
+ if (tables.translations) await db.delete(tables.translations).where(eq(tables.translations._entityId, id));
979
+ if (tables.versions) await db.delete(tables.versions).where(eq(tables.versions._docId, id));
980
+ }
981
+ } else {
982
+ const CHUNK = 200; // stay well under SQLite's bound-variable limit
983
+ for (let i = 0; i < ids.length; i += CHUNK) {
984
+ const chunk = ids.slice(i, i + CHUNK);
985
+ if (tables.translations)
986
+ await db.delete(tables.translations).where(inArray(tables.translations._entityId, chunk));
987
+ if (tables.versions) await db.delete(tables.versions).where(inArray(tables.versions._docId, chunk));
988
+ await db.delete(tables.main).where(inArray(tables.main._id, chunk));
989
+ }
990
+ deletedIds = ids;
991
+ }
992
+
993
+ if (!context._skipSearch) for (const id of deletedIds) removeSearch(collection, id);
994
+ auditContent("content.deleteMany", slug, `${deletedIds.length} document(s)`, context);
995
+ void context.cache?.invalidate({ tags: [slug] });
996
+ return deletedIds.length;
997
+ },
998
+
999
+ async publish(id: string, context: RuntimeContext = {}) {
1000
+ if (!collection.drafts) throw new Error(`${collection.labels.singular} does not support draft status.`);
1001
+
1002
+ const db = await getDb();
1003
+ const tables = await getTableRefs(slug);
1004
+ const existingRows = await db.select().from(tables.main).where(eq(tables.main._id, id)).limit(1);
1005
+ if (existingRows.length === 0) throw new Error(`${collection.labels.singular} not found.`);
1006
+
1007
+ const existing = deserializeFromDb(collection, existingRows[0] as Record<string, unknown>);
1008
+ const allowed = await canAccess(collection, "publish", context, existing);
1009
+ if (!allowed) throw new Error(`Access denied for ${collection.slug}.`);
1010
+
1011
+ const hookContext = getHookContext(collection, "publish", context);
1012
+ if (collection.hooks?.beforePublish) {
1013
+ await collection.hooks.beforePublish(existing, hookContext);
1014
+ }
1015
+
1016
+ const timestamp = now();
1017
+ const updateValues: Record<string, unknown> = {
1018
+ _status: "published",
1019
+ _publishedAt: timestamp,
1020
+ _publishAt: null,
1021
+ _unpublishAt: null,
1022
+ _published: null,
1023
+ };
1024
+ if (collection.timestamps !== false) updateValues._updatedAt = timestamp;
1025
+ await db.update(tables.main).set(updateValues).where(eq(tables.main._id, id));
1026
+
1027
+ const result = await this.findById(id, { status: "any" }, context);
1028
+ await collection.hooks?.afterPublish?.(result!, hookContext);
1029
+ auditContent("content.publish", slug, id, context);
1030
+ syncSearch(config, collection, id);
1031
+ dispatchWebhooks(config, "publish", slug, result!, context.user);
1032
+ return result!;
1033
+ },
1034
+
1035
+ async unpublish(id: string, context: RuntimeContext = {}) {
1036
+ if (!collection.drafts) throw new Error(`${collection.labels.singular} does not support draft status.`);
1037
+
1038
+ const db = await getDb();
1039
+ const tables = await getTableRefs(slug);
1040
+ const existingRows = await db.select().from(tables.main).where(eq(tables.main._id, id)).limit(1);
1041
+ if (existingRows.length === 0) throw new Error(`${collection.labels.singular} not found.`);
1042
+
1043
+ const existing = deserializeFromDb(collection, existingRows[0] as Record<string, unknown>);
1044
+ const allowed = await canAccess(collection, "publish", context, existing);
1045
+ if (!allowed) throw new Error(`Access denied for ${collection.slug}.`);
1046
+ const hookContext = getHookContext(collection, "unpublish", context);
1047
+ if (collection.hooks?.beforeUnpublish) {
1048
+ await collection.hooks.beforeUnpublish(existing, hookContext);
1049
+ }
1050
+
1051
+ const updateValues: Record<string, unknown> = {
1052
+ _status: "draft",
1053
+ _publishedAt: null,
1054
+ _publishAt: null,
1055
+ _unpublishAt: null,
1056
+ _published: null,
1057
+ };
1058
+ if (collection.timestamps !== false) updateValues._updatedAt = now();
1059
+ await db.update(tables.main).set(updateValues).where(eq(tables.main._id, id));
1060
+
1061
+ const result = (await this.findById(id, { status: "any" }, context))!;
1062
+ await collection.hooks?.afterUnpublish?.(result, hookContext);
1063
+ auditContent("content.unpublish", slug, id, context);
1064
+ removeSearch(collection, id);
1065
+ dispatchWebhooks(config, "unpublish", slug, result, context.user);
1066
+ return result;
1067
+ },
1068
+
1069
+ async schedule(id: string, publishAt: string, unpublishAt?: string | null, context: RuntimeContext = {}) {
1070
+ if (!collection.drafts) throw new Error(`${collection.labels.singular} does not support draft status.`);
1071
+
1072
+ const db = await getDb();
1073
+ const tables = await getTableRefs(slug);
1074
+ const existingRows = await db.select().from(tables.main).where(eq(tables.main._id, id)).limit(1);
1075
+ if (existingRows.length === 0) throw new Error(`${collection.labels.singular} not found.`);
1076
+
1077
+ const existing = deserializeFromDb(collection, existingRows[0] as Record<string, unknown>);
1078
+ const scheduleAllowed = await canAccess(collection, "schedule", context, existing);
1079
+ const publishAllowed = collection.access?.schedule
1080
+ ? scheduleAllowed
1081
+ : await canAccess(collection, "publish", context, existing);
1082
+ if (!scheduleAllowed && !publishAllowed) throw new Error(`Access denied for ${collection.slug}.`);
1083
+
1084
+ const hookContext = getHookContext(collection, "schedule", context);
1085
+ if (collection.hooks?.beforeSchedule) {
1086
+ await collection.hooks.beforeSchedule(existing, hookContext);
1087
+ }
1088
+
1089
+ const updateValues: Record<string, unknown> = {
1090
+ _status: "scheduled",
1091
+ _publishAt: publishAt,
1092
+ _unpublishAt: unpublishAt ?? null,
1093
+ };
1094
+ if (collection.timestamps !== false) updateValues._updatedAt = now();
1095
+ await db.update(tables.main).set(updateValues).where(eq(tables.main._id, id));
1096
+
1097
+ const result = (await this.findById(id, { status: "any" }, context))!;
1098
+ await collection.hooks?.afterSchedule?.(result, hookContext);
1099
+ auditContent("content.schedule", slug, id, context);
1100
+ removeSearch(collection, id);
1101
+ return result;
1102
+ },
1103
+
1104
+ async discardDraft(id: string, context: RuntimeContext = {}) {
1105
+ if (!collection.drafts) throw new Error(`${collection.labels.singular} does not support draft status.`);
1106
+
1107
+ const db = await getDb();
1108
+ const tables = await getTableRefs(slug);
1109
+ const existingRows = await db.select().from(tables.main).where(eq(tables.main._id, id)).limit(1);
1110
+ if (existingRows.length === 0) throw new Error(`${collection.labels.singular} not found.`);
1111
+
1112
+ const existing = deserializeFromDb(collection, existingRows[0] as Record<string, unknown>);
1113
+ const allowed = await canAccess(collection, "update", context, existing);
1114
+ if (!allowed) throw new Error(`Access denied for ${collection.slug}.`);
1115
+
1116
+ const rawPublished = (existingRows[0] as any)._published;
1117
+ if (!rawPublished) return (await this.findById(id, { status: "any" }, context))!;
1118
+
1119
+ const snapshot = JSON.parse(rawPublished);
1120
+ const restoreValues: Record<string, unknown> = { _published: null };
1121
+ for (const [fieldName, field] of Object.entries(collection.fields)) {
1122
+ if (fieldName in snapshot) {
1123
+ restoreValues[fieldName] =
1124
+ isJsonField(field) && snapshot[fieldName] !== null
1125
+ ? JSON.stringify(snapshot[fieldName])
1126
+ : snapshot[fieldName];
1127
+ }
1128
+ }
1129
+
1130
+ await db.update(tables.main).set(restoreValues).where(eq(tables.main._id, id));
1131
+ return (await this.findById(id, { status: "any" }, context))!;
1132
+ },
1133
+
1134
+ async count(filter: Omit<FindOptions, "limit" | "offset" | "sort"> = {}, context: RuntimeContext = {}) {
1135
+ const db = await getDb();
1136
+ const tables = await getTableRefs(slug);
1137
+ const status = filter.status ?? (collection.drafts ? "published" : "any");
1138
+
1139
+ const conditions: any[] = [];
1140
+ if (status !== "any" && collection.drafts) {
1141
+ conditions.push(eq(tables.main._status, status));
1142
+ }
1143
+ if (filter.where) {
1144
+ for (const [key, value] of Object.entries(filter.where)) {
1145
+ if (key in tables.main) {
1146
+ conditions.push(eq(tables.main[key], value));
1147
+ }
1148
+ }
1149
+ }
1150
+ if (filter.search?.trim()) {
1151
+ const searchTerm = `%${filter.search.trim().toLowerCase()}%`;
1152
+ const searchableTypes = new Set(["text", "slug", "email", "select"]);
1153
+ const searchConditions = Object.entries(collection.fields)
1154
+ .filter(([, field]) => searchableTypes.has(field.type))
1155
+ .filter(([name]) => name in tables.main)
1156
+ .map(([name]) => like(sql`lower(${tables.main[name]})`, searchTerm));
1157
+ if (searchConditions.length > 0) {
1158
+ conditions.push(or(...searchConditions)!);
1159
+ }
1160
+ }
1161
+
1162
+ if (hasReadRule(collection) && !context._system) {
1163
+ let rowsQuery = db.select().from(tables.main);
1164
+ if (conditions.length > 0) {
1165
+ rowsQuery = rowsQuery.where(conditions.length === 1 ? conditions[0] : and(...conditions)) as any;
1166
+ }
1167
+ const rows = await rowsQuery;
1168
+ const docs = await filterReadableDocs(
1169
+ rows.map((row: Record<string, unknown>) => applyPublishedSnapshot(row, status)),
1170
+ context,
1171
+ );
1172
+ return docs.length;
1173
+ }
1174
+
1175
+ let query = db.select({ total: sql<number>`count(*)` }).from(tables.main);
1176
+ if (conditions.length > 0) {
1177
+ query = query.where(conditions.length === 1 ? conditions[0] : and(...conditions)) as any;
1178
+ }
1179
+
1180
+ const result = await query;
1181
+ return Number((result[0] as any)?.total ?? 0);
1182
+ },
1183
+
1184
+ async versions(id: string, context: RuntimeContext = {}) {
1185
+ await assertReadable(id, context);
1186
+ const tables = await getTableRefs(slug);
1187
+ if (!tables.versions) return [];
1188
+ const db = await getDb();
1189
+ const rows = await db
1190
+ .select()
1191
+ .from(tables.versions)
1192
+ .where(eq(tables.versions._docId, id))
1193
+ .orderBy(desc(tables.versions._version));
1194
+ return rows.map((row: Record<string, unknown>) => {
1195
+ const snapshot = typeof row._snapshot === "string" ? JSON.parse(row._snapshot) : row._snapshot;
1196
+ return {
1197
+ version: row._version as number,
1198
+ createdAt: row._createdAt as string,
1199
+ // Snapshots come from the raw row, so they carry the password hash.
1200
+ snapshot: snapshot && typeof snapshot === "object" ? stripSensitiveFields(snapshot) : snapshot,
1201
+ };
1202
+ });
1203
+ },
1204
+
1205
+ async restore(id: string, versionNumber: number, context: RuntimeContext = {}) {
1206
+ const versionList = await this.versions(id);
1207
+ const version = versionList.find((entry: { version: number }) => entry.version === versionNumber);
1208
+ if (!version) throw new Error(`Version ${versionNumber} not found.`);
1209
+ return this.update(id, version.snapshot, context);
1210
+ },
1211
+
1212
+ async getTranslations(id: string, context: RuntimeContext = {}) {
1213
+ await assertReadable(id, context);
1214
+ const tables = await getTableRefs(slug);
1215
+ if (!tables.translations) return {};
1216
+ const db = await getDb();
1217
+ const rows = await db.select().from(tables.translations).where(eq(tables.translations._entityId, id));
1218
+
1219
+ const result: Record<string, Record<string, unknown>> = {};
1220
+ for (const row of rows) {
1221
+ const translation = row as Record<string, unknown>;
1222
+ const locale = String(translation._languageCode);
1223
+ const values: Record<string, unknown> = {};
1224
+
1225
+ for (const fieldName of getTranslatableFieldNames(collection)) {
1226
+ const field = collection.fields[fieldName];
1227
+ let value = translation[fieldName];
1228
+ if (isJsonField(field) && typeof value === "string") {
1229
+ try {
1230
+ value = JSON.parse(value);
1231
+ } catch {}
1232
+ }
1233
+ values[fieldName] = value;
1234
+ }
1235
+
1236
+ result[locale] = values;
1237
+ }
1238
+
1239
+ return result;
1240
+ },
1241
+
1242
+ async upsertTranslation(id: string, locale: string, data: Record<string, unknown>, context: RuntimeContext = {}) {
1243
+ const db = await getDb();
1244
+ const tables = await getTableRefs(slug);
1245
+ if (!tables.translations) throw new Error(`Collection "${slug}" does not support translations.`);
1246
+
1247
+ const existingRows = await db.select().from(tables.main).where(eq(tables.main._id, id)).limit(1);
1248
+ if (existingRows.length === 0) throw new Error(`${collection.labels.singular} not found.`);
1249
+
1250
+ const existing = deserializeFromDb(collection, existingRows[0] as Record<string, unknown>);
1251
+ const allowed = await canAccess(collection, "update", context, existing);
1252
+ if (!allowed) throw new Error(`Access denied for ${collection.slug}.`);
1253
+
1254
+ const translatableFields = getTranslatableFieldNames(collection);
1255
+ const translatedValues = prepareIncomingData(collection, data, locale, existing);
1256
+ const filtered = pick(translatedValues, translatableFields);
1257
+
1258
+ const hookContext = getHookContext(collection, "update", context);
1259
+ const transformedFiltered = collection.hooks?.beforeUpsertTranslation
1260
+ ? await collection.hooks.beforeUpsertTranslation(filtered, locale, existing, hookContext)
1261
+ : filtered;
1262
+ const serialized = serializeForDb(collection, transformedFiltered);
1263
+
1264
+ const existingTranslation = await db
1265
+ .select()
1266
+ .from(tables.translations)
1267
+ .where(and(eq(tables.translations._entityId, id), eq(tables.translations._languageCode, locale)))
1268
+ .limit(1);
1269
+
1270
+ if (existingTranslation.length > 0) {
1271
+ await db
1272
+ .update(tables.translations)
1273
+ .set(serialized)
1274
+ .where(and(eq(tables.translations._entityId, id), eq(tables.translations._languageCode, locale)));
1275
+ } else {
1276
+ await db.insert(tables.translations).values({
1277
+ _id: nanoid(),
1278
+ _entityId: id,
1279
+ _languageCode: locale,
1280
+ ...serialized,
1281
+ });
1282
+ }
1283
+
1284
+ if (collection.timestamps !== false) {
1285
+ await db.update(tables.main).set({ _updatedAt: now() }).where(eq(tables.main._id, id));
1286
+ }
1287
+
1288
+ if (collection.versions && tables.versions) {
1289
+ const versionRows = await db
1290
+ .select({ maxVersion: sql<number>`coalesce(max(_version), 0)` })
1291
+ .from(tables.versions)
1292
+ .where(eq(tables.versions._docId, id));
1293
+ const nextVersion = Number(versionRows[0]?.maxVersion ?? 0) + 1;
1294
+ await db.insert(tables.versions).values({
1295
+ _id: nanoid(),
1296
+ _docId: id,
1297
+ _version: nextVersion,
1298
+ _snapshot: JSON.stringify({ ...existing, _translations: { [locale]: filtered } }),
1299
+ _createdAt: now(),
1300
+ });
1301
+ }
1302
+
1303
+ syncSearch(config, collection, id);
1304
+ return (await this.findById(id, { locale, status: "any" }, context))!;
1305
+ },
1306
+ };
1307
+ };
1308
+
1309
+ const collectionApiEntries = Object.keys(collectionMap).map((slug) => [slug, createCollectionApi(slug)]);
1310
+
1311
+ return {
1312
+ ...Object.fromEntries(collectionApiEntries),
1313
+ meta: {
1314
+ getCollections: () =>
1315
+ config.collections.map((collection) => ({
1316
+ slug: collection.slug,
1317
+ labels: collection.labels,
1318
+ pathPrefix: collection.pathPrefix,
1319
+ drafts: !!collection.drafts,
1320
+ versions: collection.versions?.max ?? 0,
1321
+ })),
1322
+ getFields: (slug: string) => ensureCollection(config, slug).fields,
1323
+ getCollection: (slug: string) => ensureCollection(config, slug),
1324
+ getRouteForDocument: (slug: string, doc: Record<string, unknown>) => {
1325
+ const collection = ensureCollection(config, slug);
1326
+ const slugValue = String(doc.slug ?? "");
1327
+ return collection.pathPrefix
1328
+ ? `/${collection.pathPrefix}/${slugValue}`
1329
+ : `/${slugValue === "home" ? "" : slugValue}`;
1330
+ },
1331
+ getConfig: () => config,
1332
+ getLocales: () => config.locales,
1333
+ isTranslatableField: (slug: string, fieldName: string) => {
1334
+ const collection = ensureCollection(config, slug);
1335
+ const field = collection.fields[fieldName];
1336
+ return !!field?.translatable && !isStructuralField(field);
1337
+ },
1338
+ },
1339
+ scheduled: {
1340
+ async processPublishing(cache?: { invalidate: (opts: { tags: string[] }) => void | Promise<void> }) {
1341
+ const db = await getDb();
1342
+ const timestamp = now();
1343
+ let published = 0;
1344
+ let unpublished = 0;
1345
+
1346
+ for (const collection of config.collections) {
1347
+ if (!collection.drafts) continue;
1348
+
1349
+ const tables = await getTableRefs(collection.slug);
1350
+ const collectionApiInstance = createCollectionApi(collection.slug);
1351
+ const ctx: RuntimeContext = { cache, _system: true };
1352
+
1353
+ const toPublish = await db
1354
+ .select()
1355
+ .from(tables.main)
1356
+ .where(and(eq(tables.main._status, "scheduled"), lte(tables.main._publishAt, timestamp)));
1357
+
1358
+ for (const row of toPublish) {
1359
+ const doc = row as Record<string, unknown>;
1360
+ await collectionApiInstance.publish(String(doc._id), ctx);
1361
+ published++;
1362
+ }
1363
+
1364
+ const toUnpublish = await db
1365
+ .select()
1366
+ .from(tables.main)
1367
+ .where(
1368
+ and(
1369
+ eq(tables.main._status, "published"),
1370
+ sql`${tables.main._unpublishAt} IS NOT NULL`,
1371
+ lte(tables.main._unpublishAt, timestamp),
1372
+ ),
1373
+ );
1374
+
1375
+ for (const row of toUnpublish) {
1376
+ const doc = row as Record<string, unknown>;
1377
+ await collectionApiInstance.unpublish(String(doc._id), ctx);
1378
+ unpublished++;
1379
+ }
1380
+ }
1381
+
1382
+ return { published, unpublished };
1383
+ },
1384
+ },
1385
+ tasks: {
1386
+ enqueue: (type: string, payload?: unknown, options?: EnqueueTaskOptions) => enqueueTask(type, payload, options),
1387
+ drain: (limit?: number) => drainTasks(config, limit),
1388
+ tick: () => tickSchedules(config),
1389
+ prune: (olderThanMs?: number) => pruneTasks(olderThanMs),
1390
+ },
1391
+ };
1392
+ };