@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,481 @@
1
+ import type { AstroIntegration } from "astro";
2
+ import { execFileSync } from "node:child_process";
3
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, watch, writeFileSync } from "node:fs";
4
+ import { createRequire } from "node:module";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+
8
+ // All runtime files resolve relative to this module, never the project root, so
9
+ // the integration works identically embedded (workspace package in the project
10
+ // tree) and installed from the registry. realpath because pnpm links packages
11
+ // via symlinks and Vite/Tailwind watch real paths.
12
+ const packageDir = realpathSync(path.dirname(fileURLToPath(import.meta.url)));
13
+ const packageRoot = path.dirname(packageDir);
14
+ const packagePath = (...segments: string[]) => path.join(packageRoot, ...segments);
15
+ const requireFromPackage = createRequire(import.meta.url);
16
+
17
+ // Locate a file inside a dependency without going through its exports map
18
+ // (needed for CSS-only packages whose exports have no importable condition).
19
+ const resolvePackageFile = (pkg: string, file: string) => {
20
+ for (const base of requireFromPackage.resolve.paths(pkg) ?? []) {
21
+ const candidate = path.join(base, pkg, file);
22
+ if (existsSync(candidate)) return candidate;
23
+ }
24
+ throw new Error(`[kide] Could not locate ${file} in package "${pkg}".`);
25
+ };
26
+
27
+ export interface CmsIntegrationOptions {
28
+ /** Path to the CMS config file (default: "src/cms/cms.config") */
29
+ configPath?: string;
30
+ /** Path to the CMS runtime file (default: "src/cms/runtime") */
31
+ runtimePath?: string;
32
+ /** Path to the generated output directory (default: "src/cms/.generated") */
33
+ generatedPath?: string;
34
+ /** Path to the adapters directory (default: "src/cms/adapters") */
35
+ adaptersPath?: string;
36
+ /** Absolute path to the generator script (default: the package's own generator) */
37
+ generatorPath?: string;
38
+ /** Runtime target — selects the platform profile (database/storage). Default "node". */
39
+ platform?: "node" | "cloudflare";
40
+ }
41
+
42
+ // The runner scripts live in this package but read the project from cwd. tsx is
43
+ // a dependency of this package, so resolve its entry absolutely — the project
44
+ // itself may not depend on it.
45
+ const tsxEntry = requireFromPackage.resolve("tsx");
46
+
47
+ function runScript(cwd: string, scriptPath: string) {
48
+ execFileSync(process.execPath, ["--import", tsxEntry, scriptPath], {
49
+ stdio: "inherit",
50
+ cwd,
51
+ });
52
+ }
53
+
54
+ // D1 dev syncs via drizzle-kit against miniflare's sqlite (located by the CF drizzle
55
+ // config); the Node target goes through the guarded cms:push script — same gates as CI/deploy.
56
+ function pushSchema(cwd: string, d1 = false) {
57
+ if (d1) {
58
+ execFileSync("npx", ["drizzle-kit", "push", "--force"], { stdio: "inherit", cwd });
59
+ } else {
60
+ runScript(cwd, packagePath("internals", "push.ts"));
61
+ }
62
+ }
63
+
64
+ function isCloudflareD1(cwd: string): boolean {
65
+ const wranglerPath = path.join(cwd, "wrangler.toml");
66
+ if (!existsSync(wranglerPath)) return false;
67
+ try {
68
+ const content = readFileSync(wranglerPath, "utf-8");
69
+ return content.includes("[[d1_databases]]");
70
+ } catch {
71
+ return false;
72
+ }
73
+ }
74
+
75
+ function hasLocalD1Database(cwd: string): boolean {
76
+ const dir = path.join(cwd, ".wrangler/state/v3/d1/miniflare-D1DatabaseObject");
77
+ try {
78
+ return readdirSync(dir).some((file) => file.endsWith(".sqlite") && file !== "*.sqlite");
79
+ } catch {
80
+ return false;
81
+ }
82
+ }
83
+
84
+ function getD1DatabaseName(cwd: string): string | null {
85
+ const wranglerPath = path.join(cwd, "wrangler.toml");
86
+ try {
87
+ const content = readFileSync(wranglerPath, "utf-8");
88
+ const match = content.match(/database_name\s*=\s*"([^"]+)"/);
89
+ return match ? match[1] : null;
90
+ } catch {
91
+ return null;
92
+ }
93
+ }
94
+
95
+ function initLocalD1(cwd: string) {
96
+ const dbName = getD1DatabaseName(cwd);
97
+ if (!dbName) throw new Error("No database_name found in wrangler.toml");
98
+ execFileSync("npx", ["wrangler", "d1", "execute", dbName, "--local", "--command=SELECT 1"], {
99
+ stdio: "pipe",
100
+ cwd,
101
+ });
102
+ }
103
+
104
+ export default function cmsIntegration(options?: CmsIntegrationOptions): AstroIntegration {
105
+ const configPath = options?.configPath ?? "src/cms/cms.config";
106
+ const runtimePath = options?.runtimePath ?? "src/cms/runtime";
107
+ const generatedPath = options?.generatedPath ?? "src/cms/.generated";
108
+ const adaptersPath = options?.adaptersPath ?? "src/cms/adapters";
109
+ const generatorPath = options?.generatorPath ?? packagePath("internals", "generator.ts");
110
+ const platform = options?.platform ?? "node";
111
+
112
+ return {
113
+ name: "kide-cms",
114
+ hooks: {
115
+ "astro:config:setup": ({ command, updateConfig, injectRoute, injectScript, addMiddleware }) => {
116
+ const root = process.cwd();
117
+
118
+ // Generate a wrapper CSS that adds @source directives and imports user's admin CSS
119
+ const adminDir = packagePath("admin");
120
+ const routesDir = packagePath("routes");
121
+ // tw-animate-css is a CSS-only package (exports only a "style" condition),
122
+ // so Node resolution can't reach into it — walk the module paths instead.
123
+ const twAnimateCssPath = resolvePackageFile("tw-animate-css", "dist/tw-animate.css");
124
+ const userAdminCss = path.resolve(root, "src/styles/admin.css");
125
+ const generatedDir = path.join(root, "node_modules", ".kide");
126
+ mkdirSync(generatedDir, { recursive: true });
127
+ const wrapperCss = path.join(generatedDir, "admin.css");
128
+ writeFileSync(
129
+ wrapperCss,
130
+ [
131
+ `@source "${adminDir}";`,
132
+ `@source "${routesDir}";`,
133
+ `@import "${twAnimateCssPath}";`,
134
+ `@import "${userAdminCss}";`,
135
+ "",
136
+ "/* shadcn component styles (accordion, state variants) */",
137
+ "@theme inline {",
138
+ " @keyframes accordion-down { from { height: 0 } to { height: var(--radix-accordion-content-height, var(--accordion-panel-height, auto)) } }",
139
+ " @keyframes accordion-up { from { height: var(--radix-accordion-content-height, var(--accordion-panel-height, auto)) } to { height: 0 } }",
140
+ "}",
141
+ '@custom-variant data-open { &:where([data-state="open"]), &:where([data-open]:not([data-open="false"])) { @slot; } }',
142
+ '@custom-variant data-closed { &:where([data-state="closed"]), &:where([data-closed]:not([data-closed="false"])) { @slot; } }',
143
+ '@custom-variant data-checked { &:where([data-state="checked"]), &:where([data-checked]:not([data-checked="false"])) { @slot; } }',
144
+ '@custom-variant data-unchecked { &:where([data-state="unchecked"]), &:where([data-unchecked]:not([data-unchecked="false"])) { @slot; } }',
145
+ '@custom-variant data-selected { &:where([data-selected="true"]) { @slot; } }',
146
+ '@custom-variant data-disabled { &:where([data-disabled="true"]), &:where([data-disabled]:not([data-disabled="false"])) { @slot; } }',
147
+ '@custom-variant data-active { &:where([data-state="active"]), &:where([data-active]:not([data-active="false"])) { @slot; } }',
148
+ '@custom-variant data-horizontal { &:where([data-orientation="horizontal"]) { @slot; } }',
149
+ '@custom-variant data-vertical { &:where([data-orientation="vertical"]) { @slot; } }',
150
+ "@utility no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; &::-webkit-scrollbar { display: none; } }",
151
+ "",
152
+ ].join("\n"),
153
+ );
154
+
155
+ // Generate custom field components barrel (user-authored fields live
156
+ // project-side in src/cms/fields/, outside the managed runtime dirs)
157
+ const customFieldsDir = path.resolve(root, "src/cms/fields");
158
+ const customFieldsBarrel = path.join(generatedDir, "custom-fields.ts");
159
+ const generateFieldsBarrel = () => {
160
+ if (existsSync(customFieldsDir)) {
161
+ const files = readdirSync(customFieldsDir).filter((f) => f.endsWith(".tsx"));
162
+ const imports = files.map((f) => {
163
+ const name = f.replace(".tsx", "");
164
+ return ` "${name}": (await import("${path.join(customFieldsDir, f)}")).default,`;
165
+ });
166
+ writeFileSync(
167
+ customFieldsBarrel,
168
+ `export const customFields: Record<string, any> = {\n${imports.join("\n")}\n};\n`,
169
+ );
170
+ } else {
171
+ writeFileSync(customFieldsBarrel, "export const customFields: Record<string, any> = {};\n");
172
+ }
173
+ };
174
+ generateFieldsBarrel();
175
+
176
+ // Virtual module aliases — resolve route imports to the user's app files
177
+ updateConfig({
178
+ vite: {
179
+ resolve: {
180
+ alias: {
181
+ "virtual:kide/config": path.resolve(root, configPath),
182
+ "virtual:kide/api": path.resolve(root, generatedPath, "api"),
183
+ "virtual:kide/schema": path.resolve(root, generatedPath, "schema"),
184
+ "virtual:kide/runtime": path.resolve(root, runtimePath),
185
+ "virtual:kide/db": path.resolve(root, adaptersPath, "db"),
186
+ "virtual:kide/email": path.resolve(root, adaptersPath, "email"),
187
+ "virtual:kide/block-renderer": path.resolve(root, "src/components/BlockRenderer.astro"),
188
+ "virtual:kide/content-renderer": path.resolve(root, "src/components/ContentRenderer.astro"),
189
+ "virtual:kide/admin-css": wrapperCss,
190
+ "virtual:kide/custom-fields": customFieldsBarrel,
191
+ },
192
+ // Two React copies (project + package) break hooks/context identity.
193
+ dedupe: ["react", "react-dom"],
194
+ },
195
+ // The package ships TypeScript/Astro source — Vite must compile it
196
+ // rather than treat it as an external Node dependency in SSR.
197
+ ssr: {
198
+ noExternal: ["@kidecms/core"],
199
+ },
200
+ // Pre-bundle admin component deps.
201
+ //
202
+ // Admin components live under src/cms/admin/ but are only reached via injected
203
+ // routes, so Vite's default dep scanner (which starts from index.html) skips
204
+ // them entirely. Without pre-bundling, packages like @tiptap/react are served
205
+ // raw to the browser; their CJS sub-deps (use-sync-external-store/shim) break
206
+ // ESM imports; React hydration silently fails; fields render but don't respond
207
+ // to clicks (and appear to "disappear" when interacted with).
208
+ //
209
+ // `entries` points the dep scanner directly at every admin source file. We
210
+ // include admin/, the injected routes, .generated/ (api.ts, schema.ts), and
211
+ // client/ — all paths that can introduce a browser-side dep. If any one is
212
+ // missing and a request hits a code path with an undiscovered dep, Vite
213
+ // re-optimizes mid-session, which 504s in-flight chunk requests with
214
+ // "Outdated Optimize Dep" and breaks hydration on whatever tab is open
215
+ // (appears as random "React fields stop working" failures).
216
+ //
217
+ // We intentionally do NOT set `force: true` here. Forcing re-optimization on
218
+ // every dev start regenerates chunk hashes, which 504s any browser tab opened
219
+ // before the restart. Vite's content-based hash already invalidates correctly
220
+ // when deps change. For the rare case where the pre-bundle cache is genuinely
221
+ // corrupt, run `pnpm dev:clean` to nuke and rebuild.
222
+ optimizeDeps: {
223
+ entries: [
224
+ path.join(adminDir, "**/*.{ts,tsx,astro}"),
225
+ path.join(routesDir, "admin/**/*.astro"),
226
+ path.resolve(root, generatedPath, "**/*.ts"),
227
+ packagePath("client", "**/*.ts"),
228
+ ],
229
+ },
230
+ },
231
+ });
232
+
233
+ // Inject admin pages
234
+ injectRoute({ pattern: "/admin/login", entrypoint: new URL("../routes/admin/login.astro", import.meta.url) });
235
+ injectRoute({
236
+ pattern: "/admin/forgot-password",
237
+ entrypoint: new URL("../routes/admin/forgot-password.astro", import.meta.url),
238
+ });
239
+ injectRoute({
240
+ pattern: "/admin/reset-password",
241
+ entrypoint: new URL("../routes/admin/reset-password.astro", import.meta.url),
242
+ });
243
+ injectRoute({ pattern: "/admin/setup", entrypoint: new URL("../routes/admin/setup.astro", import.meta.url) });
244
+ injectRoute({ pattern: "/admin/invite", entrypoint: new URL("../routes/admin/invite.astro", import.meta.url) });
245
+ injectRoute({
246
+ pattern: "/admin/assets",
247
+ entrypoint: new URL("../routes/admin/assets/index.astro", import.meta.url),
248
+ });
249
+ injectRoute({
250
+ pattern: "/admin/assets/[id]",
251
+ entrypoint: new URL("../routes/admin/assets/[id].astro", import.meta.url),
252
+ });
253
+ injectRoute({
254
+ pattern: "/admin/[...path]",
255
+ entrypoint: new URL("../routes/admin/[...path].astro", import.meta.url),
256
+ });
257
+
258
+ // Cloudflare serves /uploads/* from R2 through a route (Node uses static files).
259
+ if (platform === "cloudflare") {
260
+ injectRoute({
261
+ pattern: "/uploads/[...path]",
262
+ entrypoint: new URL("../platform/cloudflare/uploads-route.ts", import.meta.url),
263
+ });
264
+ }
265
+
266
+ // Inject API routes
267
+ injectRoute({
268
+ pattern: "/api/cms/auth/login",
269
+ entrypoint: new URL("../routes/api/auth/login.ts", import.meta.url),
270
+ });
271
+ injectRoute({
272
+ pattern: "/api/cms/auth/forgot-password",
273
+ entrypoint: new URL("../routes/api/auth/forgot-password.ts", import.meta.url),
274
+ });
275
+ injectRoute({
276
+ pattern: "/api/cms/auth/reset-password",
277
+ entrypoint: new URL("../routes/api/auth/reset-password.ts", import.meta.url),
278
+ });
279
+ injectRoute({
280
+ pattern: "/api/cms/auth/sso/[provider]/start",
281
+ entrypoint: new URL("../routes/api/auth/sso/[provider]/start.ts", import.meta.url),
282
+ });
283
+ injectRoute({
284
+ pattern: "/api/cms/auth/logout",
285
+ entrypoint: new URL("../routes/api/auth/logout.ts", import.meta.url),
286
+ });
287
+ injectRoute({
288
+ pattern: "/api/cms/auth/setup",
289
+ entrypoint: new URL("../routes/api/auth/setup.ts", import.meta.url),
290
+ });
291
+ injectRoute({
292
+ pattern: "/api/cms/auth/invite",
293
+ entrypoint: new URL("../routes/api/auth/invite.ts", import.meta.url),
294
+ });
295
+ injectRoute({
296
+ pattern: "/api/cms/assets/upload",
297
+ entrypoint: new URL("../routes/api/assets/upload.ts", import.meta.url),
298
+ });
299
+ injectRoute({
300
+ pattern: "/api/cms/assets/folders",
301
+ entrypoint: new URL("../routes/api/assets/folders.ts", import.meta.url),
302
+ });
303
+ injectRoute({
304
+ pattern: "/api/cms/assets/[id]",
305
+ entrypoint: new URL("../routes/api/assets/[id].ts", import.meta.url),
306
+ });
307
+ injectRoute({
308
+ pattern: "/api/cms/assets",
309
+ entrypoint: new URL("../routes/api/assets/index.ts", import.meta.url),
310
+ });
311
+ injectRoute({
312
+ pattern: "/api/cms/collaboration",
313
+ entrypoint: new URL("../routes/api/collaboration/index.ts", import.meta.url),
314
+ });
315
+ injectRoute({
316
+ pattern: "/api/cms/ai/alt-text",
317
+ entrypoint: new URL("../routes/api/ai/alt-text.ts", import.meta.url),
318
+ });
319
+ injectRoute({ pattern: "/api/cms/ai/seo", entrypoint: new URL("../routes/api/ai/seo.ts", import.meta.url) });
320
+ injectRoute({
321
+ pattern: "/api/cms/ai/translate",
322
+ entrypoint: new URL("../routes/api/ai/translate.ts", import.meta.url),
323
+ });
324
+ injectRoute({
325
+ pattern: "/api/cms/cron/publish",
326
+ entrypoint: new URL("../routes/api/cron/publish.ts", import.meta.url),
327
+ });
328
+ injectRoute({
329
+ pattern: "/api/cms/cron/tasks",
330
+ entrypoint: new URL("../routes/api/cron/tasks.ts", import.meta.url),
331
+ });
332
+ injectRoute({
333
+ pattern: "/api/cms/webhooks/[provider]",
334
+ entrypoint: new URL("../routes/api/webhooks/[provider].ts", import.meta.url),
335
+ });
336
+ injectRoute({
337
+ pattern: "/api/cms/forms/submit/[slug]",
338
+ entrypoint: new URL("../routes/api/forms/submit/[slug].ts", import.meta.url),
339
+ });
340
+ injectRoute({
341
+ pattern: "/api/cms/locks/[...path]",
342
+ entrypoint: new URL("../routes/api/locks/[...path].ts", import.meta.url),
343
+ });
344
+ // Preview render route uses Astro Container API which depends on Vite internals.
345
+ // Only inject in dev mode — production builds (especially Cloudflare Workers) can't bundle it.
346
+ if (command === "dev") {
347
+ injectRoute({
348
+ pattern: "/api/cms/preview/render",
349
+ entrypoint: new URL("../routes/api/preview/render.ts", import.meta.url),
350
+ });
351
+ }
352
+ injectRoute({
353
+ pattern: "/api/cms/references/[collection]/[id]",
354
+ entrypoint: new URL("../routes/api/references/[collection]/[id].ts", import.meta.url),
355
+ });
356
+ injectRoute({
357
+ pattern: "/api/cms/img/[...path]",
358
+ entrypoint: new URL("../routes/api/img/[...path].ts", import.meta.url),
359
+ });
360
+ injectRoute({
361
+ pattern: "/api/cms/admin/search",
362
+ entrypoint: new URL("../routes/api/admin/search.ts", import.meta.url),
363
+ });
364
+ injectRoute({
365
+ pattern: "/api/cms/[collection]/[...path]",
366
+ entrypoint: new URL("../routes/api/[collection]/[...path].ts", import.meta.url),
367
+ });
368
+
369
+ // Inject auth middleware
370
+ addMiddleware({ entrypoint: new URL("../middleware/auth.ts", import.meta.url), order: "pre" });
371
+
372
+ // Inject live-preview client script (no-op unless ?preview is in the URL)
373
+ const previewClient = packagePath("client", "preview.ts");
374
+ injectScript("page", `import ${JSON.stringify(previewClient)};`);
375
+
376
+ // Generate schema, types, validators, and API
377
+ console.log(" [cms] Generating schema, types, validators, and API...");
378
+ try {
379
+ runScript(root, generatorPath);
380
+ } catch (error) {
381
+ console.error(" [cms] Generator failed:", (error as Error).message);
382
+ }
383
+
384
+ if (command === "dev") {
385
+ const useD1 = isCloudflareD1(root);
386
+
387
+ if (useD1) {
388
+ const isFirstRun = !hasLocalD1Database(root);
389
+ if (isFirstRun) {
390
+ console.log(" \x1b[36m[cms]\x1b[0m First run — setting up database...");
391
+ try {
392
+ initLocalD1(root);
393
+ } catch (error) {
394
+ console.error(" \x1b[31m[cms]\x1b[0m Failed to initialize D1:", (error as Error).message);
395
+ }
396
+ }
397
+
398
+ try {
399
+ pushSchema(root, true);
400
+ if (isFirstRun) {
401
+ console.log(" \x1b[36m[cms]\x1b[0m Database ready. Open /admin to create your admin account.");
402
+ }
403
+ } catch (error) {
404
+ console.error(" \x1b[31m[cms]\x1b[0m Database setup failed:", (error as Error).message);
405
+ console.error(" \x1b[31m[cms]\x1b[0m Try running: npx drizzle-kit push --force");
406
+ }
407
+ } else {
408
+ const dbPath = path.join(root, "data", "cms.db");
409
+ const isFirstRun = !existsSync(dbPath);
410
+ if (isFirstRun) {
411
+ console.log(" \x1b[36m[cms]\x1b[0m First run — setting up database...");
412
+ }
413
+
414
+ try {
415
+ mkdirSync(path.join(root, "data"), { recursive: true });
416
+ pushSchema(root);
417
+ if (isFirstRun) {
418
+ console.log(" \x1b[36m[cms]\x1b[0m Database ready. Open /admin to create your admin account.");
419
+ }
420
+ } catch (error) {
421
+ console.error(" \x1b[31m[cms]\x1b[0m Database setup failed:", (error as Error).message);
422
+ console.error(" \x1b[31m[cms]\x1b[0m Try running: pnpm cms:push");
423
+ }
424
+ }
425
+
426
+ const configFilePath = path.join(root, configPath.replace(/\/?$/, ".ts"));
427
+ let debounceTimer: ReturnType<typeof setTimeout> | null = null;
428
+ // macOS fs.watch on a single file also fires for sibling writes in the
429
+ // same directory tree — including the generator's own .generated/*
430
+ // output, which would loop regeneration forever. Only act when the
431
+ // config file's content actually changed.
432
+ let lastConfigContent: string | null = null;
433
+ try {
434
+ lastConfigContent = readFileSync(configFilePath, "utf-8");
435
+ } catch {
436
+ /* watch still registers; first event will populate it */
437
+ }
438
+
439
+ watch(configFilePath, () => {
440
+ if (debounceTimer) clearTimeout(debounceTimer);
441
+ debounceTimer = setTimeout(() => {
442
+ let content: string;
443
+ try {
444
+ content = readFileSync(configFilePath, "utf-8");
445
+ } catch {
446
+ return;
447
+ }
448
+ if (content === lastConfigContent) return;
449
+ lastConfigContent = content;
450
+ console.log(" [cms] Config changed, regenerating...");
451
+ try {
452
+ runScript(root, generatorPath);
453
+ pushSchema(root, useD1);
454
+ console.log(" [cms] Schema updated.");
455
+ } catch (error) {
456
+ console.error(" [cms] Regeneration failed:", (error as Error).message);
457
+ }
458
+ }, 500);
459
+ });
460
+ }
461
+ },
462
+ "astro:server:start": ({ address }) => {
463
+ const host = address.family === "IPv6" ? `[${address.address}]` : address.address;
464
+ const base = `http://${host === "[::1]" || host === "127.0.0.1" || host === "[::]" ? "localhost" : host}:${address.port}`;
465
+ console.log(` \x1b[36m[cms]\x1b[0m Admin panel: \x1b[36m${base}/admin\x1b[0m`);
466
+ },
467
+ "astro:build:done": () => {
468
+ const entryPath = path.join(process.cwd(), "dist/server/entry.mjs");
469
+ if (!existsSync(entryPath)) return;
470
+
471
+ let content = readFileSync(entryPath, "utf-8");
472
+ content = content.replace(
473
+ /export\s*\{\s*(\w+)\s+as\s+default\s*\}/,
474
+ (_, name) =>
475
+ `const _astroWorker = ${name};\nexport default {\n fetch: (...args) => _astroWorker.fetch(...args),\n async scheduled(event, env, ctx) {\n const headers = env.CRON_SECRET ? { Authorization: "Bearer " + env.CRON_SECRET } : {};\n for (const path of ["/api/cms/cron/publish", "/api/cms/cron/tasks"]) {\n const res = await _astroWorker.fetch(new Request("https://dummy" + path, { headers }), env, ctx);\n if (!res.ok) console.error("Cron " + path + " failed:", res.status, await res.text());\n else console.log("Cron " + path + ":", await res.text());\n }\n }\n};`,
476
+ );
477
+ writeFileSync(entryPath, content);
478
+ },
479
+ },
480
+ };
481
+ }