@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
@@ -0,0 +1,397 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { z } from "zod";
4
+
5
+ import { assets, closeDb, describeModel, folders } from "../core";
6
+ import type { CollectionConfig } from "../core";
7
+ import { loadGeneratedApi, loadProjectConfig } from "./project";
8
+
9
+ const { cms } = await loadGeneratedApi();
10
+ const config = await loadProjectConfig();
11
+
12
+ const server = new McpServer({
13
+ name: "kide-cms",
14
+ version: "0.1.0",
15
+ });
16
+
17
+ const cmsRuntime = cms as Record<string, any> & { meta: typeof cms.meta };
18
+ const model = describeModel(config);
19
+
20
+ const statusSchema = z.enum(["draft", "published", "scheduled", "any"]);
21
+ const sortSchema = z.object({
22
+ field: z.string().min(1),
23
+ direction: z.enum(["asc", "desc"]),
24
+ });
25
+ const jsonObjectSchema = z.record(z.string(), z.unknown());
26
+
27
+ const actor = {
28
+ id: process.env.KIDE_MCP_USER_ID || "mcp-local",
29
+ role: process.env.KIDE_MCP_USER_ROLE || "admin",
30
+ email: process.env.KIDE_MCP_USER_EMAIL || "mcp@local",
31
+ };
32
+
33
+ const runtimeContext = () => ({ user: actor });
34
+
35
+ const toResult = (value: unknown) => ({
36
+ structuredContent: { result: value },
37
+ content: [{ type: "text" as const, text: JSON.stringify(value, null, 2) }],
38
+ });
39
+
40
+ const getCollection = (slug: string): CollectionConfig => {
41
+ const collection = config.collections.find((entry) => entry.slug === slug);
42
+ if (!collection) {
43
+ const available = config.collections.map((entry) => entry.slug).join(", ");
44
+ throw new Error(`Unknown collection "${slug}". Available collections: ${available}`);
45
+ }
46
+ return collection;
47
+ };
48
+
49
+ const getCollectionApi = (slug: string) => {
50
+ getCollection(slug);
51
+ const collectionApi = cmsRuntime[slug];
52
+ if (!collectionApi) throw new Error(`No API found for collection "${slug}".`);
53
+ return collectionApi;
54
+ };
55
+
56
+ const ensureMutableCollection = (collection: CollectionConfig) => {
57
+ if (collection.auth && process.env.KIDE_MCP_ALLOW_AUTH_COLLECTIONS !== "true") {
58
+ throw new Error(
59
+ `Collection "${collection.slug}" is an auth collection. Set KIDE_MCP_ALLOW_AUTH_COLLECTIONS=true to allow MCP mutations.`,
60
+ );
61
+ }
62
+ };
63
+
64
+ const pickCollectionFields = (collection: CollectionConfig, input: Record<string, unknown>) => {
65
+ const allowed = new Set(Object.keys(collection.fields));
66
+ return Object.fromEntries(Object.entries(input).filter(([key]) => allowed.has(key)));
67
+ };
68
+
69
+ const pickTranslatableFields = (collection: CollectionConfig, input: Record<string, unknown>) => {
70
+ return Object.fromEntries(
71
+ Object.entries(input).filter(([key]) => cms.meta.isTranslatableField(collection.slug, key)),
72
+ );
73
+ };
74
+
75
+ const collectionModel = (slug: string) => {
76
+ getCollection(slug);
77
+ const described = model.collections.find((collection) => collection.slug === slug);
78
+ if (!described) throw new Error(`No model manifest found for collection "${slug}".`);
79
+ return described;
80
+ };
81
+
82
+ server.registerResource(
83
+ "kide-model",
84
+ "kide://model",
85
+ {
86
+ title: "Kide content model",
87
+ description: "Machine-readable Kide CMS collection, field, locale, and content AST metadata.",
88
+ mimeType: "application/json",
89
+ },
90
+ async (uri) => ({
91
+ contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify(model, null, 2) }],
92
+ }),
93
+ );
94
+
95
+ server.registerTool(
96
+ "kide_list_collections",
97
+ {
98
+ title: "List collections",
99
+ description: "List all Kide collections and their high-level metadata.",
100
+ inputSchema: {},
101
+ },
102
+ async () => toResult(cms.meta.getCollections()),
103
+ );
104
+
105
+ server.registerTool(
106
+ "kide_describe_collection",
107
+ {
108
+ title: "Describe collection",
109
+ description:
110
+ "Return the schema, field value shapes, translatable fields, and publishing settings for a collection.",
111
+ inputSchema: {
112
+ collection: z.string().min(1),
113
+ },
114
+ },
115
+ async ({ collection }) => toResult(collectionModel(collection)),
116
+ );
117
+
118
+ server.registerTool(
119
+ "kide_list_documents",
120
+ {
121
+ title: "List documents",
122
+ description:
123
+ "List documents in a collection with optional filters, search, sort, locale, status, limit, and offset.",
124
+ inputSchema: {
125
+ collection: z.string().min(1),
126
+ where: jsonObjectSchema.optional(),
127
+ search: z.string().optional(),
128
+ sort: sortSchema.optional(),
129
+ limit: z.number().int().min(1).max(100).default(20),
130
+ offset: z.number().int().min(0).default(0),
131
+ status: statusSchema.optional(),
132
+ locale: z.string().min(1).optional(),
133
+ },
134
+ },
135
+ async ({ collection, where, search, sort, limit, offset, status, locale }) => {
136
+ const collectionApi = getCollectionApi(collection);
137
+ const options = { where, search, sort, limit, offset, status, locale };
138
+ const [docs, totalDocs] = await Promise.all([
139
+ collectionApi.find(options, runtimeContext()),
140
+ collectionApi.count({ where, search, status, locale }, runtimeContext()),
141
+ ]);
142
+
143
+ return toResult({ docs, totalDocs, limit, offset });
144
+ },
145
+ );
146
+
147
+ server.registerTool(
148
+ "kide_count_documents",
149
+ {
150
+ title: "Count documents",
151
+ description: "Count documents in a collection with optional filters, search, locale, and status.",
152
+ inputSchema: {
153
+ collection: z.string().min(1),
154
+ where: jsonObjectSchema.optional(),
155
+ search: z.string().optional(),
156
+ status: statusSchema.optional(),
157
+ locale: z.string().min(1).optional(),
158
+ },
159
+ },
160
+ async ({ collection, where, search, status, locale }) => {
161
+ const collectionApi = getCollectionApi(collection);
162
+ const totalDocs = await collectionApi.count({ where, search, status, locale }, runtimeContext());
163
+ return toResult({ totalDocs });
164
+ },
165
+ );
166
+
167
+ server.registerTool(
168
+ "kide_get_document",
169
+ {
170
+ title: "Get document",
171
+ description: "Get one document by id, optionally overlaying a locale and selecting status.",
172
+ inputSchema: {
173
+ collection: z.string().min(1),
174
+ id: z.string().min(1),
175
+ status: statusSchema.optional(),
176
+ locale: z.string().min(1).optional(),
177
+ },
178
+ },
179
+ async ({ collection, id, status, locale }) => {
180
+ const collectionApi = getCollectionApi(collection);
181
+ const doc = await collectionApi.findById(id, { status, locale }, runtimeContext());
182
+ if (!doc) throw new Error(`No document found for "${collection}/${id}".`);
183
+ return toResult(doc);
184
+ },
185
+ );
186
+
187
+ server.registerTool(
188
+ "kide_create_document",
189
+ {
190
+ title: "Create document",
191
+ description:
192
+ "Create a document. Only declared collection fields are accepted; system fields are ignored. Draft-enabled collections create drafts by default.",
193
+ inputSchema: {
194
+ collection: z.string().min(1),
195
+ data: jsonObjectSchema,
196
+ },
197
+ },
198
+ async ({ collection, data }) => {
199
+ const collectionConfig = getCollection(collection);
200
+ ensureMutableCollection(collectionConfig);
201
+ const collectionApi = getCollectionApi(collection);
202
+ const cleaned = pickCollectionFields(collectionConfig, data);
203
+ const doc = await collectionApi.create(cleaned, runtimeContext());
204
+ return toResult(doc);
205
+ },
206
+ );
207
+
208
+ server.registerTool(
209
+ "kide_update_document",
210
+ {
211
+ title: "Update document",
212
+ description:
213
+ "Update a document by id. Only declared collection fields are accepted; publishing remains a separate explicit tool.",
214
+ inputSchema: {
215
+ collection: z.string().min(1),
216
+ id: z.string().min(1),
217
+ data: jsonObjectSchema,
218
+ },
219
+ },
220
+ async ({ collection, id, data }) => {
221
+ const collectionConfig = getCollection(collection);
222
+ ensureMutableCollection(collectionConfig);
223
+ const collectionApi = getCollectionApi(collection);
224
+ const cleaned = pickCollectionFields(collectionConfig, data);
225
+ if (Object.keys(cleaned).length === 0) throw new Error("No declared collection fields were provided.");
226
+ const doc = await collectionApi.update(id, cleaned, runtimeContext());
227
+ return toResult(doc);
228
+ },
229
+ );
230
+
231
+ server.registerTool(
232
+ "kide_publish_document",
233
+ {
234
+ title: "Publish document",
235
+ description: "Publish a draft-enabled document by id.",
236
+ inputSchema: {
237
+ collection: z.string().min(1),
238
+ id: z.string().min(1),
239
+ },
240
+ },
241
+ async ({ collection, id }) => {
242
+ const collectionConfig = getCollection(collection);
243
+ ensureMutableCollection(collectionConfig);
244
+ const doc = await getCollectionApi(collection).publish(id, runtimeContext());
245
+ return toResult(doc);
246
+ },
247
+ );
248
+
249
+ server.registerTool(
250
+ "kide_unpublish_document",
251
+ {
252
+ title: "Unpublish document",
253
+ description: "Unpublish a draft-enabled document by id.",
254
+ inputSchema: {
255
+ collection: z.string().min(1),
256
+ id: z.string().min(1),
257
+ },
258
+ },
259
+ async ({ collection, id }) => {
260
+ const collectionConfig = getCollection(collection);
261
+ ensureMutableCollection(collectionConfig);
262
+ const doc = await getCollectionApi(collection).unpublish(id, runtimeContext());
263
+ return toResult(doc);
264
+ },
265
+ );
266
+
267
+ server.registerTool(
268
+ "kide_schedule_document",
269
+ {
270
+ title: "Schedule document",
271
+ description: "Schedule a draft-enabled document to publish and optionally unpublish at ISO timestamps.",
272
+ inputSchema: {
273
+ collection: z.string().min(1),
274
+ id: z.string().min(1),
275
+ publishAt: z.string().min(1),
276
+ unpublishAt: z.string().min(1).nullable().optional(),
277
+ },
278
+ },
279
+ async ({ collection, id, publishAt, unpublishAt }) => {
280
+ const collectionConfig = getCollection(collection);
281
+ ensureMutableCollection(collectionConfig);
282
+ const doc = await getCollectionApi(collection).schedule(id, publishAt, unpublishAt ?? null, runtimeContext());
283
+ return toResult(doc);
284
+ },
285
+ );
286
+
287
+ server.registerTool(
288
+ "kide_get_translations",
289
+ {
290
+ title: "Get translations",
291
+ description: "Return all stored translations for a document.",
292
+ inputSchema: {
293
+ collection: z.string().min(1),
294
+ id: z.string().min(1),
295
+ },
296
+ },
297
+ async ({ collection, id }) => {
298
+ const translations = await getCollectionApi(collection).getTranslations(id);
299
+ return toResult(translations);
300
+ },
301
+ );
302
+
303
+ server.registerTool(
304
+ "kide_upsert_translation",
305
+ {
306
+ title: "Upsert translation",
307
+ description: "Create or update a locale translation. Only translatable fields are accepted.",
308
+ inputSchema: {
309
+ collection: z.string().min(1),
310
+ id: z.string().min(1),
311
+ locale: z.string().min(1),
312
+ data: jsonObjectSchema,
313
+ },
314
+ },
315
+ async ({ collection, id, locale, data }) => {
316
+ const collectionConfig = getCollection(collection);
317
+ ensureMutableCollection(collectionConfig);
318
+ const cleaned = pickTranslatableFields(collectionConfig, data);
319
+ if (Object.keys(cleaned).length === 0) throw new Error("No translatable fields were provided.");
320
+ const doc = await getCollectionApi(collection).upsertTranslation(id, locale, cleaned, runtimeContext());
321
+ return toResult(doc);
322
+ },
323
+ );
324
+
325
+ server.registerTool(
326
+ "kide_list_assets",
327
+ {
328
+ title: "List assets",
329
+ description: "List Kide asset records, optionally scoped to a folder.",
330
+ inputSchema: {
331
+ limit: z.number().int().min(1).max(100).default(20),
332
+ offset: z.number().int().min(0).default(0),
333
+ folder: z.string().nullable().optional(),
334
+ search: z.string().optional(),
335
+ },
336
+ },
337
+ async ({ limit, offset, folder, search }) => {
338
+ const items = await assets.find({ limit, offset, folder, search });
339
+ const totalAssets = await assets.count({ folder, search });
340
+ return toResult({ items, totalAssets, limit, offset });
341
+ },
342
+ );
343
+
344
+ server.registerTool(
345
+ "kide_update_asset",
346
+ {
347
+ title: "Update asset",
348
+ description: "Update safe asset metadata such as alt text, filename, folder, or focal point.",
349
+ inputSchema: {
350
+ id: z.string().min(1),
351
+ alt: z.string().optional(),
352
+ filename: z.string().min(1).optional(),
353
+ folder: z.string().nullable().optional(),
354
+ focalX: z.number().nullable().optional(),
355
+ focalY: z.number().nullable().optional(),
356
+ },
357
+ },
358
+ async ({ id, alt, filename, folder, focalX, focalY }) => {
359
+ const updated = await assets.update(
360
+ id,
361
+ {
362
+ ...(alt !== undefined ? { alt } : {}),
363
+ ...(filename !== undefined ? { filename } : {}),
364
+ ...(folder !== undefined ? { folder } : {}),
365
+ ...(focalX !== undefined ? { focalX } : {}),
366
+ ...(focalY !== undefined ? { focalY } : {}),
367
+ },
368
+ { actor },
369
+ );
370
+ if (!updated) throw new Error(`No asset found for "${id}".`);
371
+ return toResult(updated);
372
+ },
373
+ );
374
+
375
+ server.registerTool(
376
+ "kide_list_asset_folders",
377
+ {
378
+ title: "List asset folders",
379
+ description: "List Kide asset folders.",
380
+ inputSchema: {},
381
+ },
382
+ async () => toResult(await folders.findAll()),
383
+ );
384
+
385
+ const shutdown = async () => {
386
+ await closeDb();
387
+ };
388
+
389
+ process.on("SIGINT", () => {
390
+ void shutdown().finally(() => process.exit(0));
391
+ });
392
+ process.on("SIGTERM", () => {
393
+ void shutdown().finally(() => process.exit(0));
394
+ });
395
+
396
+ await server.connect(new StdioServerTransport());
397
+ console.error("[kide:mcp] local MCP server started");
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Resolve project-owned files (cms.config, runtime, .generated) from the
3
+ * project working directory instead of static imports. These scripts must work
4
+ * identically whether the CMS runtime is embedded in the project tree or
5
+ * installed as a package dependency — a static import of a project file would
6
+ * only exist in the embedded case.
7
+ */
8
+ import path from "node:path";
9
+ import { pathToFileURL } from "node:url";
10
+
11
+ import type { CMSConfig } from "../core";
12
+
13
+ const projectRoot = process.cwd();
14
+
15
+ export const projectPath = (...segments: string[]) => path.join(projectRoot, ...segments);
16
+
17
+ const importProject = (relativePath: string) => import(pathToFileURL(projectPath(relativePath)).href);
18
+
19
+ /** Wire the runtime (DB / storage / email adapters) as a side effect. */
20
+ export const loadProjectRuntime = () => importProject("src/cms/runtime.ts");
21
+
22
+ export const loadProjectConfig = async (): Promise<CMSConfig> => (await importProject("src/cms/cms.config.ts")).default;
23
+
24
+ export const loadGeneratedApi = () => importProject("src/cms/.generated/api.ts");
25
+
26
+ export const loadGeneratedSchema = () => importProject("src/cms/.generated/schema.ts");
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Schema sync for the local SQLite dev database, runnable from scripts/CI.
3
+ *
4
+ * Applies the generated Drizzle schema (`.generated/schema.ts`) for **additive**
5
+ * changes (new tables / new columns) and FTS-safe diffs without a TTY — unlike
6
+ * `drizzle-kit push`, which the dev server shells out to and which needs a
7
+ * terminal. NOTE: a column **rename or drop** is ambiguous and drizzle-kit's
8
+ * resolver still requires a TTY (we surface a clear error below). For those,
9
+ * either DROP the affected table first (data loss — fine for a dev DB you're
10
+ * about to repopulate) and re-run, or hand-write a migration to preserve data.
11
+ *
12
+ * pnpm cms:push # generate + sync ./data/cms.db (or CMS_DATABASE_URL)
13
+ *
14
+ * For Cloudflare D1 projects, keep using `drizzle-kit push` / wrangler — this
15
+ * script targets local better-sqlite3 only.
16
+ */
17
+ import { mkdirSync } from "node:fs";
18
+ import path from "node:path";
19
+ import Database from "better-sqlite3";
20
+ import { drizzle } from "drizzle-orm/better-sqlite3";
21
+ import { pushSQLiteSchema } from "drizzle-kit/api";
22
+
23
+ import { loadGeneratedSchema } from "./project";
24
+
25
+ const schema = await loadGeneratedSchema();
26
+
27
+ const dbPath = process.env.CMS_DATABASE_URL ?? path.join(process.cwd(), "data", "cms.db");
28
+
29
+ // The FTS5 search tables are created lazily at runtime (ensureSearchSchema) and
30
+ // are not part of the Drizzle schema, so the diff always wants to drop them.
31
+ // Mirror drizzle.config's `tablesFilter: ["!cms_search_index*"]` and skip those.
32
+ const isSearchIndexStatement = (stmt: string) => /\bcms_search_index/i.test(stmt);
33
+
34
+ // Tables to drop before pushing, so a column rename/drop becomes a non-interactive
35
+ // CREATE (data loss — intended for a dev DB you're repopulating). Accepts a comma
36
+ // list of collection slugs or table names; expands to the collection's
37
+ // _translations/_versions tables too.
38
+ // RECREATE=pages,posts pnpm cms:push (or --recreate=pages,posts)
39
+ // Destructive statements abort unless explicitly approved:
40
+ // pnpm cms:push --allow-data-loss (or ALLOW_DATA_LOSS=1)
41
+ const allowDataLoss = process.argv.includes("--allow-data-loss") || process.env.ALLOW_DATA_LOSS === "1";
42
+
43
+ const parseRecreate = (): string[] => {
44
+ const arg = process.argv.find((a) => a.startsWith("--recreate="))?.slice("--recreate=".length);
45
+ const raw = process.env.RECREATE ?? arg ?? "";
46
+ const tables = new Set<string>();
47
+ for (const name of raw
48
+ .split(",")
49
+ .map((s) => s.trim())
50
+ .filter(Boolean)) {
51
+ const base = name.startsWith("cms_") ? name : `cms_${name}`;
52
+ tables.add(base);
53
+ tables.add(`${base}_translations`);
54
+ tables.add(`${base}_versions`);
55
+ }
56
+ return [...tables];
57
+ };
58
+
59
+ async function main() {
60
+ if (dbPath !== ":memory:") mkdirSync(path.dirname(path.resolve(dbPath)), { recursive: true });
61
+
62
+ const sqlite = new Database(dbPath);
63
+ sqlite.pragma("foreign_keys = OFF"); // allow dropping referenced tables for --recreate
64
+ const db = drizzle(sqlite);
65
+
66
+ const recreate = parseRecreate();
67
+ if (recreate.length) {
68
+ // Recreate drops tables before the diff runs, so it needs the same approval as any
69
+ // destructive diff — checked here, before anything is touched.
70
+ if (!allowDataLoss) {
71
+ console.error(`[cms:push] Refusing --recreate (drops ${recreate.join(", ")} — data loss).`);
72
+ console.error("[cms:push] Re-run with --allow-data-loss to apply anyway.");
73
+ sqlite.close();
74
+ process.exit(1);
75
+ }
76
+ for (const t of recreate) sqlite.exec(`DROP TABLE IF EXISTS ${t}`);
77
+ console.log(`[cms:push] dropped for recreate: ${recreate.join(", ")}`);
78
+ }
79
+
80
+ // pushSQLiteSchema().apply() assumes a libsql driver (calls .all() on DDL), so
81
+ // execute the diff statements directly against better-sqlite3 instead.
82
+ const isTtyPromptError = (error: unknown) => /TTY|Interactive prompts/i.test((error as Error).message);
83
+ let diff;
84
+ try {
85
+ diff = await pushSQLiteSchema({ ...schema }, db as never);
86
+ } catch (error) {
87
+ if (!isTtyPromptError(error)) {
88
+ sqlite.close();
89
+ throw error;
90
+ }
91
+ // The programmatic API has no tablesFilter, so when the schema CREATEs a new
92
+ // table, drizzle-kit sees the runtime-created FTS tables as deletion
93
+ // candidates and wants to ask "renamed?" interactively. Drop them (they're
94
+ // rebuilt lazily; search needs a reindex) and retry before giving up.
95
+ const ftsTables = sqlite
96
+ .prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'cms_search_index%'")
97
+ .all() as Array<{ name: string }>;
98
+ for (const { name } of ftsTables) sqlite.exec(`DROP TABLE IF EXISTS ${name}`);
99
+ if (ftsTables.length) {
100
+ console.log("[cms:push] Dropped runtime search-index tables to disambiguate the diff —");
101
+ console.log(" run `pnpm cms:reindex` afterwards to rebuild search.");
102
+ }
103
+ try {
104
+ diff = await pushSQLiteSchema({ ...schema }, db as never);
105
+ } catch (retryError) {
106
+ sqlite.close();
107
+ if (isTtyPromptError(retryError)) {
108
+ console.error(
109
+ "[cms:push] This change includes an ambiguous column rename/drop that drizzle-kit\n" +
110
+ " can only resolve interactively (no TTY here). Either DROP the affected\n" +
111
+ " table (data loss — fine for a dev DB you're repopulating) and re-run,\n" +
112
+ " or hand-write a migration to preserve the data.",
113
+ );
114
+ process.exit(1);
115
+ }
116
+ throw retryError;
117
+ }
118
+ }
119
+ const { statementsToExecute, hasDataLoss } = diff;
120
+ const statements = statementsToExecute.filter((stmt) => !isSearchIndexStatement(stmt));
121
+
122
+ // drizzle-kit's hasDataLoss misses plain DROP COLUMN — classify statement shapes too.
123
+ // (`__new_` is drizzle's table-recreate pattern: create copy, insert-select, drop old.)
124
+ const isDestructive = (stmt: string) => /\bDROP\s+TABLE\b|\bDROP\s+COLUMN\b|\bDELETE\s+FROM\b|__new_/i.test(stmt);
125
+ const losesData = hasDataLoss || statements.some(isDestructive);
126
+
127
+ if (statements.length === 0) {
128
+ console.log("[cms:push] Schema already in sync.");
129
+ } else if (losesData && !allowDataLoss) {
130
+ console.error("[cms:push] Refusing to apply — this diff loses data:");
131
+ for (const statement of statements) console.error(` ${statement.split("\n")[0]}`);
132
+ console.error("[cms:push] Re-run with --allow-data-loss to apply anyway.");
133
+ sqlite.close();
134
+ process.exit(1);
135
+ } else {
136
+ // One transaction: a mid-diff failure must not leave a half-applied schema.
137
+ sqlite.exec("BEGIN");
138
+ try {
139
+ for (const statement of statements) sqlite.exec(statement);
140
+ // FKs are OFF in this script, so verify integrity before committing.
141
+ const violations = sqlite.pragma("foreign_key_check") as Array<{ table: string; parent: string }>;
142
+ if (violations.length) {
143
+ const pairs = [...new Set(violations.map((v) => `${v.table}→${v.parent}`))].join(", ");
144
+ throw new Error(`[cms:push] foreign_key_check failed (${pairs}) — rolled back.`);
145
+ }
146
+ sqlite.exec("COMMIT");
147
+ } catch (error) {
148
+ sqlite.exec("ROLLBACK");
149
+ sqlite.close();
150
+ throw error;
151
+ }
152
+ console.log(`[cms:push] Applied ${statements.length} statement(s)${losesData ? " (includes data loss)" : ""}.`);
153
+ if (losesData)
154
+ console.log("[cms:push] Tip: run `pnpm cms:reindex` to rebuild the search index if columns changed.");
155
+ }
156
+
157
+ sqlite.close();
158
+ }
159
+
160
+ await main();
@@ -0,0 +1,11 @@
1
+ import { closeDb, reindexAll } from "../core";
2
+ import { loadProjectConfig, loadProjectRuntime } from "./project";
3
+
4
+ await loadProjectRuntime();
5
+ const config = await loadProjectConfig();
6
+
7
+ const locales = config.locales?.supported ?? [];
8
+ const { indexed } = await reindexAll(config.collections, locales);
9
+ console.log(`[search] reindexed ${indexed} document${indexed === 1 ? "" : "s"}`);
10
+ // Release the DB / local platform proxy so the process can exit (Cloudflare target).
11
+ await closeDb();