@kidecms/core 0.1.10 → 0.13.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 (182) 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 +84 -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 +625 -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 +26 -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.data.ts +7 -0
  90. package/internals/seed.ts +11 -0
  91. package/internals/upgrade.ts +776 -0
  92. package/{virtual.d.ts → internals/virtual.d.ts} +39 -5
  93. package/middleware/auth.ts +130 -17
  94. package/middleware/push.ts +121 -0
  95. package/package.json +55 -67
  96. package/platform/cloudflare/cf-env.ts +60 -0
  97. package/platform/cloudflare/database.ts +28 -0
  98. package/platform/cloudflare/globals.d.ts +5 -0
  99. package/platform/cloudflare/storage.ts +33 -0
  100. package/platform/cloudflare/uploads-route.ts +37 -0
  101. package/platform/node/database.ts +39 -0
  102. package/platform/node/storage.ts +52 -0
  103. package/routes/admin/[...path].astro +71 -0
  104. package/routes/{pages/admin → admin}/assets/[id].astro +25 -19
  105. package/routes/admin/assets/index.astro +90 -0
  106. package/routes/admin/forgot-password.astro +60 -0
  107. package/routes/{pages/admin → admin}/invite.astro +7 -6
  108. package/routes/admin/login.astro +103 -0
  109. package/routes/admin/reset-password.astro +73 -0
  110. package/routes/{pages/admin → admin}/setup.astro +32 -8
  111. package/routes/api/{cms/[collection] → [collection]}/[...path].ts +66 -14
  112. package/routes/api/admin/search.ts +89 -0
  113. package/routes/api/{cms/assets → assets}/[id].ts +24 -14
  114. package/routes/api/{cms/assets → assets}/index.ts +4 -2
  115. package/routes/api/assets/upload.ts +147 -0
  116. package/routes/api/auth/forgot-password.ts +77 -0
  117. package/routes/api/{cms/auth → auth}/invite.ts +41 -9
  118. package/routes/api/auth/login.ts +167 -0
  119. package/routes/api/{cms/auth → auth}/logout.ts +11 -2
  120. package/routes/api/auth/reset-password.ts +85 -0
  121. package/routes/api/auth/setup.ts +110 -0
  122. package/routes/api/auth/sso/[provider]/start.ts +34 -0
  123. package/routes/api/collaboration/index.ts +106 -0
  124. package/routes/api/cron/_authorize.ts +25 -0
  125. package/routes/api/{cms/cron → cron}/publish.ts +3 -9
  126. package/routes/api/cron/tasks.ts +33 -0
  127. package/routes/api/forms/submit/[slug].ts +143 -0
  128. package/routes/api/img/[...path].ts +65 -0
  129. package/routes/api/{cms/preview → preview}/render.ts +8 -3
  130. package/routes/api/{cms/references → references}/[collection]/[id].ts +31 -1
  131. package/routes/api/webhooks/[provider].ts +54 -0
  132. package/README.md +0 -28
  133. package/dist/admin.d.ts +0 -33
  134. package/dist/admin.js +0 -92
  135. package/dist/ai.d.ts +0 -15
  136. package/dist/ai.js +0 -70
  137. package/dist/api.d.ts +0 -14
  138. package/dist/api.js +0 -833
  139. package/dist/assets.d.ts +0 -51
  140. package/dist/assets.js +0 -163
  141. package/dist/auth.d.ts +0 -30
  142. package/dist/auth.js +0 -132
  143. package/dist/content.d.ts +0 -3
  144. package/dist/content.js +0 -29
  145. package/dist/create-admin.d.ts +0 -5
  146. package/dist/create-admin.js +0 -23
  147. package/dist/define.d.ts +0 -254
  148. package/dist/define.js +0 -36
  149. package/dist/generator.d.ts +0 -9
  150. package/dist/generator.js +0 -370
  151. package/dist/image.d.ts +0 -9
  152. package/dist/image.js +0 -69
  153. package/dist/index.d.ts +0 -28
  154. package/dist/index.js +0 -16
  155. package/dist/integration.d.ts +0 -14
  156. package/dist/integration.js +0 -327
  157. package/dist/locks.d.ts +0 -7
  158. package/dist/locks.js +0 -37
  159. package/dist/richtext.d.ts +0 -1
  160. package/dist/richtext.js +0 -1
  161. package/dist/runtime.d.ts +0 -24
  162. package/dist/runtime.js +0 -26
  163. package/dist/schema.d.ts +0 -17
  164. package/dist/schema.js +0 -13
  165. package/dist/seed.d.ts +0 -2
  166. package/dist/seed.js +0 -84
  167. package/dist/values.d.ts +0 -8
  168. package/dist/values.js +0 -102
  169. package/dist/webhooks.d.ts +0 -2
  170. package/dist/webhooks.js +0 -73
  171. package/routes/api/cms/assets/upload.ts +0 -112
  172. package/routes/api/cms/auth/login.ts +0 -124
  173. package/routes/api/cms/auth/setup.ts +0 -77
  174. package/routes/api/cms/img/[...path].ts +0 -24
  175. package/routes/pages/admin/[...path].astro +0 -1107
  176. package/routes/pages/admin/assets/index.astro +0 -63
  177. package/routes/pages/admin/login.astro +0 -57
  178. /package/routes/api/{cms/ai → ai}/alt-text.ts +0 -0
  179. /package/routes/api/{cms/ai → ai}/seo.ts +0 -0
  180. /package/routes/api/{cms/ai → ai}/translate.ts +0 -0
  181. /package/routes/api/{cms/assets → assets}/folders.ts +0 -0
  182. /package/routes/api/{cms/locks → locks}/[...path].ts +0 -0
package/dist/api.js DELETED
@@ -1,833 +0,0 @@
1
- import { and, asc, desc, eq, like, lte, or, sql } from "drizzle-orm";
2
- import { nanoid } from "nanoid";
3
- import { hashPassword } from "./auth";
4
- import { getCollectionMap, getTranslatableFieldNames, isStructuralField } from "./define";
5
- import { getDb } from "./runtime";
6
- import { getSchema } from "./schema";
7
- import { cloneValue, createRichTextFromPlainText, slugify } from "./values";
8
- import { dispatchWebhooks } from "./webhooks";
9
- const now = () => new Date().toISOString();
10
- const pick = (input, keys) => Object.fromEntries(keys.filter((key) => key in input).map((key) => [key, input[key]]));
11
- const isJsonField = (field) => field.type === "richText" ||
12
- field.type === "array" ||
13
- field.type === "json" ||
14
- field.type === "blocks" ||
15
- (field.type === "relation" && field.hasMany);
16
- const ensureCollection = (config, slug) => {
17
- const collection = getCollectionMap(config)[slug];
18
- if (!collection) {
19
- const available = config.collections.map((collectionEntry) => collectionEntry.slug).join(", ");
20
- throw new Error(`Unknown collection "${slug}". Available collections: ${available}`);
21
- }
22
- return collection;
23
- };
24
- const getDefaultStatus = (collection) => (collection.drafts ? "draft" : "published");
25
- const isEmptyValue = (value) => value === undefined || value === null || value === "" || (Array.isArray(value) && value.length === 0);
26
- const coerceString = (value) => (value === null ? "" : String(value).trim());
27
- const coerceNumber = (value) => (value === "" || value === null ? undefined : Number(value));
28
- const coerceBoolean = (value) => value === true || value === "true" || value === "on" || value === 1 || value === "1";
29
- const coerceRelation = (field, value) => {
30
- if (!("hasMany" in field && field.hasMany))
31
- return value ? String(value) : "";
32
- if (Array.isArray(value))
33
- return value.map((item) => String(item));
34
- const stringValue = String(value).trim();
35
- if (stringValue.startsWith("[")) {
36
- try {
37
- const parsed = JSON.parse(stringValue);
38
- if (Array.isArray(parsed))
39
- return parsed.map((item) => String(item)).filter(Boolean);
40
- }
41
- catch {
42
- // fall through to comma split
43
- }
44
- }
45
- return stringValue
46
- .split(",")
47
- .map((item) => item.trim())
48
- .filter(Boolean);
49
- };
50
- const coerceArray = (value) => {
51
- if (Array.isArray(value))
52
- return value;
53
- if (typeof value === "string") {
54
- return value
55
- .split(/\n|,/)
56
- .map((item) => item.trim())
57
- .filter(Boolean);
58
- }
59
- return [];
60
- };
61
- const coerceJsonOrBlocks = (field, value) => {
62
- const fallback = field.defaultValue ?? (field.type === "blocks" ? [] : {});
63
- if (typeof value === "string") {
64
- const trimmed = value.trim();
65
- return trimmed ? JSON.parse(trimmed) : fallback;
66
- }
67
- return value ?? fallback;
68
- };
69
- const coerceRichText = (value) => {
70
- if (typeof value === "string") {
71
- const trimmed = value.trim();
72
- if (trimmed.startsWith("{")) {
73
- try {
74
- const parsed = JSON.parse(trimmed);
75
- if (parsed?.type === "root")
76
- return parsed;
77
- }
78
- catch { }
79
- }
80
- return createRichTextFromPlainText(value);
81
- }
82
- return value ?? createRichTextFromPlainText("");
83
- };
84
- const coerceFieldValue = (field, value) => {
85
- if (value === undefined)
86
- return undefined;
87
- switch (field.type) {
88
- case "text":
89
- case "slug":
90
- case "email":
91
- case "image":
92
- case "date":
93
- return coerceString(value);
94
- case "number":
95
- return coerceNumber(value);
96
- case "boolean":
97
- return coerceBoolean(value);
98
- case "select":
99
- return value === "" || value === null ? "" : String(value);
100
- case "relation":
101
- return coerceRelation(field, value);
102
- case "array":
103
- return coerceArray(value);
104
- case "json":
105
- case "blocks":
106
- return coerceJsonOrBlocks(field, value);
107
- case "richText":
108
- return coerceRichText(value);
109
- default:
110
- return value;
111
- }
112
- };
113
- const prepareIncomingData = (collection, input, locale, existing) => {
114
- const data = {};
115
- const translatableFields = new Set(getTranslatableFieldNames(collection));
116
- for (const [fieldName, field] of Object.entries(collection.fields)) {
117
- if (locale && !translatableFields.has(fieldName))
118
- continue;
119
- if (!locale && translatableFields.has(fieldName) && input[fieldName] === undefined && existing)
120
- continue;
121
- const rawValue = input[fieldName];
122
- const coercedValue = coerceFieldValue(field, rawValue);
123
- if (coercedValue === undefined) {
124
- if (!existing && field.defaultValue !== undefined) {
125
- data[fieldName] = cloneValue(field.defaultValue);
126
- }
127
- continue;
128
- }
129
- data[fieldName] = coercedValue;
130
- }
131
- for (const [fieldName, field] of Object.entries(collection.fields)) {
132
- if (field.type !== "slug")
133
- continue;
134
- if (!isEmptyValue(data[fieldName])) {
135
- data[fieldName] = slugify(String(data[fieldName]));
136
- continue;
137
- }
138
- const sourceField = field.from;
139
- const sourceValue = sourceField ? (data[sourceField] ?? input[sourceField]) : undefined;
140
- if (sourceValue)
141
- data[fieldName] = slugify(String(sourceValue));
142
- }
143
- for (const [fieldName, field] of Object.entries(collection.fields)) {
144
- if (!field.required)
145
- continue;
146
- const candidate = data[fieldName] ?? existing?.[fieldName];
147
- if (isEmptyValue(candidate))
148
- throw new Error(`Field "${fieldName}" is required.`);
149
- }
150
- return data;
151
- };
152
- const serializeForDb = (collection, data) => {
153
- const result = {};
154
- for (const [key, value] of Object.entries(data)) {
155
- const field = collection.fields[key];
156
- result[key] = field && isJsonField(field) && value !== undefined && value !== null ? JSON.stringify(value) : value;
157
- }
158
- return result;
159
- };
160
- const deserializeFromDb = (collection, row) => {
161
- const result = { ...row };
162
- for (const [key, field] of Object.entries(collection.fields)) {
163
- if (isJsonField(field) && typeof result[key] === "string") {
164
- try {
165
- result[key] = JSON.parse(result[key]);
166
- }
167
- catch {
168
- // leave as string if not valid JSON
169
- }
170
- }
171
- }
172
- return result;
173
- };
174
- const canAccess = async (collection, operation, context, doc) => {
175
- if (context._system)
176
- return true;
177
- const rule = collection.access?.[operation];
178
- if (!rule)
179
- return true;
180
- return rule({ user: context.user ?? null, doc: doc ?? null, operation, collection: collection.slug });
181
- };
182
- const getHookContext = (collection, operation, context) => ({
183
- user: context.user ?? null,
184
- operation,
185
- collection: collection.slug,
186
- timestamp: now(),
187
- cache: context.cache,
188
- });
189
- const getTableRefs = async (collectionSlug) => {
190
- const tables = getSchema().cmsTables[collectionSlug];
191
- if (!tables)
192
- throw new Error(`No tables found for collection "${collectionSlug}".`);
193
- return tables;
194
- };
195
- export const createCms = (config) => {
196
- const collectionMap = getCollectionMap(config);
197
- const createCollectionApi = (slug) => {
198
- const collection = ensureCollection(config, slug);
199
- const overlayLocale = (doc, translations, locale) => {
200
- const baseDoc = { ...doc };
201
- const translatableFields = getTranslatableFieldNames(collection);
202
- const availableLocales = [...new Set(translations.map((translation) => String(translation._languageCode)))];
203
- if (locale) {
204
- const translation = translations.find((entry) => entry._languageCode === locale);
205
- if (translation) {
206
- for (const fieldName of translatableFields) {
207
- if (translation[fieldName] !== undefined && translation[fieldName] !== null) {
208
- baseDoc[fieldName] = translation[fieldName];
209
- }
210
- }
211
- }
212
- }
213
- return {
214
- ...baseDoc,
215
- _availableLocales: availableLocales,
216
- _locale: locale ?? null,
217
- };
218
- };
219
- const stripSensitiveFields = (doc) => {
220
- if (!collection.auth)
221
- return doc;
222
- const { password: _password, ...rest } = doc;
223
- return rest;
224
- };
225
- return {
226
- async find(options = {}, context = {}) {
227
- const allowed = await canAccess(collection, "read", context);
228
- if (!allowed)
229
- throw new Error(`Access denied for ${collection.slug}.`);
230
- const db = await getDb();
231
- const tables = await getTableRefs(slug);
232
- const status = options.status ?? (collection.drafts ? "published" : "any");
233
- const conditions = [];
234
- if (status !== "any" && collection.drafts) {
235
- conditions.push(eq(tables.main._status, status));
236
- }
237
- if (options.where) {
238
- for (const [key, value] of Object.entries(options.where)) {
239
- if (key in tables.main) {
240
- conditions.push(eq(tables.main[key], value));
241
- }
242
- }
243
- }
244
- if (options.search?.trim()) {
245
- const searchTerm = `%${options.search.trim().toLowerCase()}%`;
246
- const searchableTypes = new Set(["text", "slug", "email", "select"]);
247
- const searchConditions = Object.entries(collection.fields)
248
- .filter(([, field]) => searchableTypes.has(field.type))
249
- .filter(([name]) => name in tables.main)
250
- .map(([name]) => like(sql `lower(${tables.main[name]})`, searchTerm));
251
- if (searchConditions.length > 0) {
252
- conditions.push(or(...searchConditions));
253
- }
254
- }
255
- let query = db.select().from(tables.main);
256
- if (conditions.length > 0) {
257
- query = query.where(conditions.length === 1 ? conditions[0] : and(...conditions));
258
- }
259
- if (options.sort) {
260
- const col = tables.main[options.sort.field];
261
- if (col) {
262
- query = query.orderBy(options.sort.direction === "desc" ? desc(col) : asc(col));
263
- }
264
- }
265
- if (options.limit)
266
- query = query.limit(options.limit);
267
- if (options.offset)
268
- query = query.offset(options.offset);
269
- const rows = await query;
270
- const docs = rows.map((row) => {
271
- const doc = deserializeFromDb(collection, row);
272
- if (status === "published" && typeof row._published === "string") {
273
- try {
274
- const snapshot = JSON.parse(row._published);
275
- for (const key of Object.keys(collection.fields)) {
276
- if (key in snapshot)
277
- doc[key] = snapshot[key];
278
- }
279
- }
280
- catch { }
281
- }
282
- return doc;
283
- });
284
- if (tables.translations && (options.locale || config.locales)) {
285
- const docIds = docs.map((doc) => String(doc._id));
286
- if (docIds.length > 0) {
287
- const allTranslations = await db
288
- .select()
289
- .from(tables.translations)
290
- .where(sql `${tables.translations._entityId} IN (${sql.join(docIds.map((id) => sql `${id}`), sql `, `)})`);
291
- const parsedTranslations = allTranslations.map((translation) => {
292
- const parsed = { ...translation };
293
- const translatableFields = getTranslatableFieldNames(collection);
294
- for (const fieldName of translatableFields) {
295
- const field = collection.fields[fieldName];
296
- if (isJsonField(field) && typeof parsed[fieldName] === "string") {
297
- try {
298
- parsed[fieldName] = JSON.parse(parsed[fieldName]);
299
- }
300
- catch { }
301
- }
302
- }
303
- return parsed;
304
- });
305
- return docs.map((doc) => {
306
- const docTranslations = parsedTranslations.filter((translation) => translation._entityId === doc._id);
307
- return stripSensitiveFields(overlayLocale(doc, docTranslations, options.locale));
308
- });
309
- }
310
- }
311
- return docs.map((doc) => stripSensitiveFields(overlayLocale(doc, [], options.locale)));
312
- },
313
- async findOne(filter, context = {}) {
314
- const docs = await this.find({
315
- where: pick(filter, Object.keys(collection.fields).concat(["_id", "_status", "slug"])),
316
- locale: filter.locale,
317
- status: filter.status,
318
- limit: 1,
319
- }, context);
320
- return docs[0] ?? null;
321
- },
322
- async findById(id, options = {}, context = {}) {
323
- const db = await getDb();
324
- const tables = await getTableRefs(slug);
325
- const rows = await db.select().from(tables.main).where(eq(tables.main._id, id)).limit(1);
326
- if (rows.length === 0)
327
- return null;
328
- const doc = deserializeFromDb(collection, rows[0]);
329
- const allowed = await canAccess(collection, "read", context, doc);
330
- if (!allowed)
331
- throw new Error(`Access denied for ${collection.slug}.`);
332
- if (options.status && options.status !== "any" && doc._status !== options.status)
333
- return null;
334
- const effectiveStatus = options.status ?? (collection.drafts ? "published" : "any");
335
- if (effectiveStatus === "published" && typeof rows[0]._published === "string") {
336
- try {
337
- const snapshot = JSON.parse(rows[0]._published);
338
- for (const key of Object.keys(collection.fields)) {
339
- if (key in snapshot)
340
- doc[key] = snapshot[key];
341
- }
342
- }
343
- catch { }
344
- }
345
- let translations = [];
346
- if (tables.translations) {
347
- const rawTranslations = await db
348
- .select()
349
- .from(tables.translations)
350
- .where(eq(tables.translations._entityId, id));
351
- translations = rawTranslations.map((translation) => {
352
- const parsed = { ...translation };
353
- for (const fieldName of getTranslatableFieldNames(collection)) {
354
- const field = collection.fields[fieldName];
355
- if (isJsonField(field) && typeof parsed[fieldName] === "string") {
356
- try {
357
- parsed[fieldName] = JSON.parse(parsed[fieldName]);
358
- }
359
- catch { }
360
- }
361
- }
362
- return parsed;
363
- });
364
- }
365
- return stripSensitiveFields(overlayLocale(doc, translations, options.locale));
366
- },
367
- async create(data, context = {}) {
368
- const allowed = await canAccess(collection, "create", context);
369
- if (!allowed)
370
- throw new Error(`Access denied for ${collection.slug}.`);
371
- const db = await getDb();
372
- const tables = await getTableRefs(slug);
373
- const hookContext = getHookContext(collection, "create", context);
374
- const preparedInput = prepareIncomingData(collection, data, undefined);
375
- if (collection.auth && typeof preparedInput.password === "string" && preparedInput.password) {
376
- preparedInput.password = await hashPassword(preparedInput.password);
377
- }
378
- const transformedInput = collection.hooks?.beforeCreate
379
- ? await collection.hooks.beforeCreate(preparedInput, hookContext)
380
- : preparedInput;
381
- const createdAt = now();
382
- const docId = typeof data._id === "string" ? String(data._id) : nanoid();
383
- const docValues = {
384
- _id: docId,
385
- ...serializeForDb(collection, transformedInput),
386
- };
387
- if (collection.drafts) {
388
- const status = data._status === "published" ? "published" : getDefaultStatus(collection);
389
- docValues._status = status;
390
- if (status === "published")
391
- docValues._publishedAt = createdAt;
392
- }
393
- if (collection.timestamps !== false) {
394
- docValues._createdAt = createdAt;
395
- docValues._updatedAt = createdAt;
396
- }
397
- await db.insert(tables.main).values(docValues);
398
- if (collection.versions && tables.versions) {
399
- await db.insert(tables.versions).values({
400
- _id: nanoid(),
401
- _docId: docId,
402
- _version: 1,
403
- _snapshot: JSON.stringify({ ...transformedInput, _status: docValues._status }),
404
- _createdAt: createdAt,
405
- });
406
- }
407
- const result = await this.findById(docId, {}, context);
408
- await collection.hooks?.afterCreate?.(result, hookContext);
409
- dispatchWebhooks(config, "create", slug, result, context.user);
410
- return result;
411
- },
412
- async update(id, data, context = {}) {
413
- const db = await getDb();
414
- const tables = await getTableRefs(slug);
415
- const existingRows = await db.select().from(tables.main).where(eq(tables.main._id, id)).limit(1);
416
- if (existingRows.length === 0)
417
- throw new Error(`${collection.labels.singular} not found.`);
418
- const existing = deserializeFromDb(collection, existingRows[0]);
419
- const allowed = await canAccess(collection, "update", context, existing);
420
- if (!allowed)
421
- throw new Error(`Access denied for ${collection.slug}.`);
422
- const accessCtx = { user: context.user ?? null, doc: existing, operation: "update", collection: slug };
423
- for (const [fieldName, field] of Object.entries(collection.fields)) {
424
- if (field.access?.update && data[fieldName] !== undefined) {
425
- const fieldAllowed = await field.access.update(accessCtx);
426
- if (!fieldAllowed)
427
- delete data[fieldName];
428
- }
429
- }
430
- const hookContext = getHookContext(collection, "update", context);
431
- const preparedInput = prepareIncomingData(collection, data, undefined, existing);
432
- if (collection.auth && typeof preparedInput.password === "string" && preparedInput.password) {
433
- preparedInput.password = await hashPassword(preparedInput.password);
434
- }
435
- const transformedInput = collection.hooks?.beforeUpdate
436
- ? await collection.hooks.beforeUpdate(preparedInput, existing, hookContext)
437
- : preparedInput;
438
- if (collection.drafts && existing._status === "published" && !existingRows[0]._published) {
439
- const snapshot = {};
440
- for (const fieldName of Object.keys(collection.fields)) {
441
- if (existing[fieldName] !== undefined)
442
- snapshot[fieldName] = existing[fieldName];
443
- }
444
- await db
445
- .update(tables.main)
446
- .set({ _published: JSON.stringify(snapshot) })
447
- .where(eq(tables.main._id, id));
448
- }
449
- const updateValues = {
450
- ...serializeForDb(collection, transformedInput),
451
- };
452
- if (collection.timestamps !== false) {
453
- updateValues._updatedAt = now();
454
- }
455
- await db.update(tables.main).set(updateValues).where(eq(tables.main._id, id));
456
- if (collection.versions && tables.versions) {
457
- const versionRows = await db
458
- .select({ maxVersion: sql `coalesce(max(_version), 0)` })
459
- .from(tables.versions)
460
- .where(eq(tables.versions._docId, id));
461
- const nextVersion = Number(versionRows[0]?.maxVersion ?? 0) + 1;
462
- const maxVersions = collection.versions.max;
463
- await db.insert(tables.versions).values({
464
- _id: nanoid(),
465
- _docId: id,
466
- _version: nextVersion,
467
- _snapshot: JSON.stringify({ ...existing, ...transformedInput }),
468
- _createdAt: now(),
469
- });
470
- if (maxVersions) {
471
- const allVersions = await db
472
- .select()
473
- .from(tables.versions)
474
- .where(eq(tables.versions._docId, id))
475
- .orderBy(desc(tables.versions._version));
476
- const toDelete = allVersions.slice(maxVersions);
477
- for (const version of toDelete) {
478
- await db.delete(tables.versions).where(eq(tables.versions._id, version._id));
479
- }
480
- }
481
- }
482
- const result = await this.findById(id, { status: "any" }, context);
483
- await collection.hooks?.afterUpdate?.(result, hookContext);
484
- dispatchWebhooks(config, "update", slug, result, context.user);
485
- return result;
486
- },
487
- async delete(id, context = {}) {
488
- const db = await getDb();
489
- const tables = await getTableRefs(slug);
490
- const existingRows = await db.select().from(tables.main).where(eq(tables.main._id, id)).limit(1);
491
- if (existingRows.length === 0)
492
- return;
493
- const existing = deserializeFromDb(collection, existingRows[0]);
494
- const allowed = await canAccess(collection, "delete", context, existing);
495
- if (!allowed)
496
- throw new Error(`Access denied for ${collection.slug}.`);
497
- const hookContext = getHookContext(collection, "delete", context);
498
- await collection.hooks?.beforeDelete?.(existing, hookContext);
499
- if (tables.translations)
500
- await db.delete(tables.translations).where(eq(tables.translations._entityId, id));
501
- if (tables.versions)
502
- await db.delete(tables.versions).where(eq(tables.versions._docId, id));
503
- await db.delete(tables.main).where(eq(tables.main._id, id));
504
- await collection.hooks?.afterDelete?.(existing, hookContext);
505
- dispatchWebhooks(config, "delete", slug, existing, context.user);
506
- },
507
- async publish(id, context = {}) {
508
- if (!collection.drafts)
509
- throw new Error(`${collection.labels.singular} does not support draft status.`);
510
- const db = await getDb();
511
- const tables = await getTableRefs(slug);
512
- const existingRows = await db.select().from(tables.main).where(eq(tables.main._id, id)).limit(1);
513
- if (existingRows.length === 0)
514
- throw new Error(`${collection.labels.singular} not found.`);
515
- const existing = deserializeFromDb(collection, existingRows[0]);
516
- const allowed = await canAccess(collection, "publish", context, existing);
517
- if (!allowed)
518
- throw new Error(`Access denied for ${collection.slug}.`);
519
- const hookContext = getHookContext(collection, "publish", context);
520
- if (collection.hooks?.beforePublish) {
521
- await collection.hooks.beforePublish(existing, hookContext);
522
- }
523
- const timestamp = now();
524
- const updateValues = {
525
- _status: "published",
526
- _publishedAt: timestamp,
527
- _publishAt: null,
528
- _unpublishAt: null,
529
- _published: null,
530
- };
531
- if (collection.timestamps !== false)
532
- updateValues._updatedAt = timestamp;
533
- await db.update(tables.main).set(updateValues).where(eq(tables.main._id, id));
534
- const result = await this.findById(id, { status: "any" }, context);
535
- await collection.hooks?.afterPublish?.(result, hookContext);
536
- dispatchWebhooks(config, "publish", slug, result, context.user);
537
- return result;
538
- },
539
- async unpublish(id, context = {}) {
540
- if (!collection.drafts)
541
- throw new Error(`${collection.labels.singular} does not support draft status.`);
542
- const db = await getDb();
543
- const tables = await getTableRefs(slug);
544
- const existingRows = await db.select().from(tables.main).where(eq(tables.main._id, id)).limit(1);
545
- if (existingRows.length === 0)
546
- throw new Error(`${collection.labels.singular} not found.`);
547
- const existing = deserializeFromDb(collection, existingRows[0]);
548
- const allowed = await canAccess(collection, "publish", context, existing);
549
- if (!allowed)
550
- throw new Error(`Access denied for ${collection.slug}.`);
551
- const hookContext = getHookContext(collection, "unpublish", context);
552
- if (collection.hooks?.beforeUnpublish) {
553
- await collection.hooks.beforeUnpublish(existing, hookContext);
554
- }
555
- const updateValues = {
556
- _status: "draft",
557
- _publishedAt: null,
558
- _publishAt: null,
559
- _unpublishAt: null,
560
- _published: null,
561
- };
562
- if (collection.timestamps !== false)
563
- updateValues._updatedAt = now();
564
- await db.update(tables.main).set(updateValues).where(eq(tables.main._id, id));
565
- const result = (await this.findById(id, { status: "any" }, context));
566
- await collection.hooks?.afterUnpublish?.(result, hookContext);
567
- dispatchWebhooks(config, "unpublish", slug, result, context.user);
568
- return result;
569
- },
570
- async schedule(id, publishAt, unpublishAt, context = {}) {
571
- if (!collection.drafts)
572
- throw new Error(`${collection.labels.singular} does not support draft status.`);
573
- const db = await getDb();
574
- const tables = await getTableRefs(slug);
575
- const existingRows = await db.select().from(tables.main).where(eq(tables.main._id, id)).limit(1);
576
- if (existingRows.length === 0)
577
- throw new Error(`${collection.labels.singular} not found.`);
578
- const existing = deserializeFromDb(collection, existingRows[0]);
579
- const scheduleAllowed = await canAccess(collection, "schedule", context, existing);
580
- const publishAllowed = collection.access?.schedule
581
- ? scheduleAllowed
582
- : await canAccess(collection, "publish", context, existing);
583
- if (!scheduleAllowed && !publishAllowed)
584
- throw new Error(`Access denied for ${collection.slug}.`);
585
- const hookContext = getHookContext(collection, "schedule", context);
586
- if (collection.hooks?.beforeSchedule) {
587
- await collection.hooks.beforeSchedule(existing, hookContext);
588
- }
589
- const updateValues = {
590
- _status: "scheduled",
591
- _publishAt: publishAt,
592
- _unpublishAt: unpublishAt ?? null,
593
- };
594
- if (collection.timestamps !== false)
595
- updateValues._updatedAt = now();
596
- await db.update(tables.main).set(updateValues).where(eq(tables.main._id, id));
597
- const result = (await this.findById(id, { status: "any" }, context));
598
- await collection.hooks?.afterSchedule?.(result, hookContext);
599
- return result;
600
- },
601
- async discardDraft(id, context = {}) {
602
- if (!collection.drafts)
603
- throw new Error(`${collection.labels.singular} does not support draft status.`);
604
- const db = await getDb();
605
- const tables = await getTableRefs(slug);
606
- const existingRows = await db.select().from(tables.main).where(eq(tables.main._id, id)).limit(1);
607
- if (existingRows.length === 0)
608
- throw new Error(`${collection.labels.singular} not found.`);
609
- const existing = deserializeFromDb(collection, existingRows[0]);
610
- const allowed = await canAccess(collection, "update", context, existing);
611
- if (!allowed)
612
- throw new Error(`Access denied for ${collection.slug}.`);
613
- const rawPublished = existingRows[0]._published;
614
- if (!rawPublished)
615
- return (await this.findById(id, { status: "any" }, context));
616
- const snapshot = JSON.parse(rawPublished);
617
- const restoreValues = { _published: null };
618
- for (const [fieldName, field] of Object.entries(collection.fields)) {
619
- if (fieldName in snapshot) {
620
- restoreValues[fieldName] =
621
- isJsonField(field) && snapshot[fieldName] !== null
622
- ? JSON.stringify(snapshot[fieldName])
623
- : snapshot[fieldName];
624
- }
625
- }
626
- await db.update(tables.main).set(restoreValues).where(eq(tables.main._id, id));
627
- return (await this.findById(id, { status: "any" }, context));
628
- },
629
- async count(filter = {}, context = {}) {
630
- const allowed = await canAccess(collection, "read", context);
631
- if (!allowed)
632
- throw new Error(`Access denied for ${collection.slug}.`);
633
- const db = await getDb();
634
- const tables = await getTableRefs(slug);
635
- const status = filter.status ?? (collection.drafts ? "published" : "any");
636
- const conditions = [];
637
- if (status !== "any" && collection.drafts) {
638
- conditions.push(eq(tables.main._status, status));
639
- }
640
- if (filter.where) {
641
- for (const [key, value] of Object.entries(filter.where)) {
642
- if (key in tables.main) {
643
- conditions.push(eq(tables.main[key], value));
644
- }
645
- }
646
- }
647
- if (filter.search?.trim()) {
648
- const searchTerm = `%${filter.search.trim().toLowerCase()}%`;
649
- const searchableTypes = new Set(["text", "slug", "email", "select"]);
650
- const searchConditions = Object.entries(collection.fields)
651
- .filter(([, field]) => searchableTypes.has(field.type))
652
- .filter(([name]) => name in tables.main)
653
- .map(([name]) => like(sql `lower(${tables.main[name]})`, searchTerm));
654
- if (searchConditions.length > 0) {
655
- conditions.push(or(...searchConditions));
656
- }
657
- }
658
- let query = db.select({ total: sql `count(*)` }).from(tables.main);
659
- if (conditions.length > 0) {
660
- query = query.where(conditions.length === 1 ? conditions[0] : and(...conditions));
661
- }
662
- const result = await query;
663
- return Number(result[0]?.total ?? 0);
664
- },
665
- async versions(id) {
666
- const tables = await getTableRefs(slug);
667
- if (!tables.versions)
668
- return [];
669
- const db = await getDb();
670
- const rows = await db
671
- .select()
672
- .from(tables.versions)
673
- .where(eq(tables.versions._docId, id))
674
- .orderBy(desc(tables.versions._version));
675
- return rows.map((row) => ({
676
- version: row._version,
677
- createdAt: row._createdAt,
678
- snapshot: typeof row._snapshot === "string" ? JSON.parse(row._snapshot) : row._snapshot,
679
- }));
680
- },
681
- async restore(id, versionNumber, context = {}) {
682
- const versionList = await this.versions(id);
683
- const version = versionList.find((entry) => entry.version === versionNumber);
684
- if (!version)
685
- throw new Error(`Version ${versionNumber} not found.`);
686
- return this.update(id, version.snapshot, context);
687
- },
688
- async getTranslations(id) {
689
- const tables = await getTableRefs(slug);
690
- if (!tables.translations)
691
- return {};
692
- const db = await getDb();
693
- const rows = await db.select().from(tables.translations).where(eq(tables.translations._entityId, id));
694
- const result = {};
695
- for (const row of rows) {
696
- const translation = row;
697
- const locale = String(translation._languageCode);
698
- const values = {};
699
- for (const fieldName of getTranslatableFieldNames(collection)) {
700
- const field = collection.fields[fieldName];
701
- let value = translation[fieldName];
702
- if (isJsonField(field) && typeof value === "string") {
703
- try {
704
- value = JSON.parse(value);
705
- }
706
- catch { }
707
- }
708
- values[fieldName] = value;
709
- }
710
- result[locale] = values;
711
- }
712
- return result;
713
- },
714
- async upsertTranslation(id, locale, data, context = {}) {
715
- const db = await getDb();
716
- const tables = await getTableRefs(slug);
717
- if (!tables.translations)
718
- throw new Error(`Collection "${slug}" does not support translations.`);
719
- const existingRows = await db.select().from(tables.main).where(eq(tables.main._id, id)).limit(1);
720
- if (existingRows.length === 0)
721
- throw new Error(`${collection.labels.singular} not found.`);
722
- const existing = deserializeFromDb(collection, existingRows[0]);
723
- const allowed = await canAccess(collection, "update", context, existing);
724
- if (!allowed)
725
- throw new Error(`Access denied for ${collection.slug}.`);
726
- const translatableFields = getTranslatableFieldNames(collection);
727
- const translatedValues = prepareIncomingData(collection, data, locale, existing);
728
- const filtered = pick(translatedValues, translatableFields);
729
- const serialized = serializeForDb(collection, filtered);
730
- const existingTranslation = await db
731
- .select()
732
- .from(tables.translations)
733
- .where(and(eq(tables.translations._entityId, id), eq(tables.translations._languageCode, locale)))
734
- .limit(1);
735
- if (existingTranslation.length > 0) {
736
- await db
737
- .update(tables.translations)
738
- .set(serialized)
739
- .where(and(eq(tables.translations._entityId, id), eq(tables.translations._languageCode, locale)));
740
- }
741
- else {
742
- await db.insert(tables.translations).values({
743
- _id: nanoid(),
744
- _entityId: id,
745
- _languageCode: locale,
746
- ...serialized,
747
- });
748
- }
749
- if (collection.timestamps !== false) {
750
- await db.update(tables.main).set({ _updatedAt: now() }).where(eq(tables.main._id, id));
751
- }
752
- if (collection.versions && tables.versions) {
753
- const versionRows = await db
754
- .select({ maxVersion: sql `coalesce(max(_version), 0)` })
755
- .from(tables.versions)
756
- .where(eq(tables.versions._docId, id));
757
- const nextVersion = Number(versionRows[0]?.maxVersion ?? 0) + 1;
758
- await db.insert(tables.versions).values({
759
- _id: nanoid(),
760
- _docId: id,
761
- _version: nextVersion,
762
- _snapshot: JSON.stringify({ ...existing, _translations: { [locale]: filtered } }),
763
- _createdAt: now(),
764
- });
765
- }
766
- return (await this.findById(id, { locale, status: "any" }, context));
767
- },
768
- };
769
- };
770
- const collectionApiEntries = Object.keys(collectionMap).map((slug) => [slug, createCollectionApi(slug)]);
771
- return {
772
- ...Object.fromEntries(collectionApiEntries),
773
- meta: {
774
- getCollections: () => config.collections.map((collection) => ({
775
- slug: collection.slug,
776
- labels: collection.labels,
777
- pathPrefix: collection.pathPrefix,
778
- drafts: !!collection.drafts,
779
- versions: collection.versions?.max ?? 0,
780
- })),
781
- getFields: (slug) => ensureCollection(config, slug).fields,
782
- getCollection: (slug) => ensureCollection(config, slug),
783
- getRouteForDocument: (slug, doc) => {
784
- const collection = ensureCollection(config, slug);
785
- const slugValue = String(doc.slug ?? "");
786
- return collection.pathPrefix
787
- ? `/${collection.pathPrefix}/${slugValue}`
788
- : `/${slugValue === "home" ? "" : slugValue}`;
789
- },
790
- getConfig: () => config,
791
- getLocales: () => config.locales,
792
- isTranslatableField: (slug, fieldName) => {
793
- const collection = ensureCollection(config, slug);
794
- const field = collection.fields[fieldName];
795
- return !!field?.translatable && !isStructuralField(field);
796
- },
797
- },
798
- scheduled: {
799
- async processPublishing(cache) {
800
- const db = await getDb();
801
- const timestamp = now();
802
- let published = 0;
803
- let unpublished = 0;
804
- for (const collection of config.collections) {
805
- if (!collection.drafts)
806
- continue;
807
- const tables = await getTableRefs(collection.slug);
808
- const collectionApiInstance = createCollectionApi(collection.slug);
809
- const ctx = { cache, _system: true };
810
- const toPublish = await db
811
- .select()
812
- .from(tables.main)
813
- .where(and(eq(tables.main._status, "scheduled"), lte(tables.main._publishAt, timestamp)));
814
- for (const row of toPublish) {
815
- const doc = row;
816
- await collectionApiInstance.publish(String(doc._id), ctx);
817
- published++;
818
- }
819
- const toUnpublish = await db
820
- .select()
821
- .from(tables.main)
822
- .where(and(eq(tables.main._status, "published"), sql `${tables.main._unpublishAt} IS NOT NULL`, lte(tables.main._unpublishAt, timestamp)));
823
- for (const row of toUnpublish) {
824
- const doc = row;
825
- await collectionApiInstance.unpublish(String(doc._id), ctx);
826
- unpublished++;
827
- }
828
- }
829
- return { published, unpublished };
830
- },
831
- },
832
- };
833
- };