@kidecms/core 0.34.0 → 0.36.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.
package/core/api.ts CHANGED
@@ -1691,9 +1691,29 @@ export const createCms = (config: CMSConfig) => {
1691
1691
  .from(tables.main)
1692
1692
  .where(and(eq(tables.main._status, "scheduled"), lte(tables.main._publishAt, timestamp)));
1693
1693
 
1694
+ // Claim each document before publishing: when two schedulers overlap (e.g. old and new
1695
+ // container during a deploy), only one claim matches, so hooks and webhooks fire once.
1694
1696
  for (const row of toPublish) {
1695
- const doc = row as Record<string, unknown>;
1696
- await collectionApiInstance.publish(String(doc._id), ctx);
1697
+ const id = String((row as Record<string, unknown>)._id);
1698
+ const publishAt = (row as Record<string, unknown>)._publishAt as string;
1699
+ const claimed = await db
1700
+ .update(tables.main)
1701
+ .set({ _publishAt: null })
1702
+ .where(
1703
+ and(
1704
+ eq(tables.main._id, id),
1705
+ eq(tables.main._status, "scheduled"),
1706
+ eq(tables.main._publishAt, publishAt),
1707
+ ),
1708
+ )
1709
+ .returning({ _id: tables.main._id });
1710
+ if (claimed.length === 0) continue;
1711
+ try {
1712
+ await collectionApiInstance.publish(id, ctx);
1713
+ } catch (error) {
1714
+ await db.update(tables.main).set({ _publishAt: publishAt }).where(eq(tables.main._id, id));
1715
+ throw error;
1716
+ }
1697
1717
  published++;
1698
1718
  }
1699
1719
 
@@ -1709,8 +1729,26 @@ export const createCms = (config: CMSConfig) => {
1709
1729
  );
1710
1730
 
1711
1731
  for (const row of toUnpublish) {
1712
- const doc = row as Record<string, unknown>;
1713
- await collectionApiInstance.unpublish(String(doc._id), ctx);
1732
+ const id = String((row as Record<string, unknown>)._id);
1733
+ const unpublishAt = (row as Record<string, unknown>)._unpublishAt as string;
1734
+ const claimed = await db
1735
+ .update(tables.main)
1736
+ .set({ _unpublishAt: null })
1737
+ .where(
1738
+ and(
1739
+ eq(tables.main._id, id),
1740
+ eq(tables.main._status, "published"),
1741
+ eq(tables.main._unpublishAt, unpublishAt),
1742
+ ),
1743
+ )
1744
+ .returning({ _id: tables.main._id });
1745
+ if (claimed.length === 0) continue;
1746
+ try {
1747
+ await collectionApiInstance.unpublish(id, ctx);
1748
+ } catch (error) {
1749
+ await db.update(tables.main).set({ _unpublishAt: unpublishAt }).where(eq(tables.main._id, id));
1750
+ throw error;
1751
+ }
1714
1752
  unpublished++;
1715
1753
  }
1716
1754
  }
package/core/image.ts CHANGED
@@ -185,7 +185,11 @@ export async function transformImage(
185
185
  source = null;
186
186
  }
187
187
  if (!source) return null;
188
- const cacheDir = path.join(process.cwd(), ".cms-cache", "img");
188
+ // Set CMS_CACHE_DIR to a persistent volume so resized variants survive deploys.
189
+ const cacheRoot = process.env.CMS_CACHE_DIR
190
+ ? path.resolve(process.env.CMS_CACHE_DIR)
191
+ : path.join(process.cwd(), ".cms-cache");
192
+ const cacheDir = path.join(cacheRoot, "img");
189
193
 
190
194
  const resolvedFormat: Format = ALLOWED_FORMATS.includes(options.format as Format)
191
195
  ? (options.format as Format)
@@ -0,0 +1,13 @@
1
+ // @astrojs/node only trusts the Host / X-Forwarded-* headers for domains in `security.allowedDomains`;
2
+ // otherwise Astro.url falls back to localhost. Derive the entry from Kide's own public-origin setting.
3
+ export const allowedDomainsFromOrigin = (origin: string | undefined) => {
4
+ if (!origin) return null;
5
+ try {
6
+ const url = new URL(origin);
7
+ return [
8
+ { protocol: url.protocol.replace(/:$/, ""), hostname: url.hostname, ...(url.port ? { port: url.port } : {}) },
9
+ ];
10
+ } catch {
11
+ return null;
12
+ }
13
+ };
package/internals/cli.mjs CHANGED
@@ -10,6 +10,7 @@ import { register } from "tsx/esm/api";
10
10
  const COMMANDS = {
11
11
  generate: "./generator.ts",
12
12
  push: "./push.ts",
13
+ migrate: "./migrate.ts",
13
14
  seed: "./seed.ts",
14
15
  admin: "./create-admin.ts",
15
16
  reindex: "./reindex.ts",
@@ -4,6 +4,7 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, watch,
4
4
  import { createRequire } from "node:module";
5
5
  import path from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
+ import { allowedDomainsFromOrigin } from "./allowed-domains";
7
8
  import { analyzeSharedDeps, formatConflicts } from "./shared-deps";
8
9
 
9
10
  // All runtime files resolve relative to this module, never the project root, so
@@ -114,7 +115,7 @@ export default function cmsIntegration(options?: CmsIntegrationOptions): AstroIn
114
115
  return {
115
116
  name: "kide-cms",
116
117
  hooks: {
117
- "astro:config:setup": ({ command, updateConfig, injectRoute, injectScript, addMiddleware, logger }) => {
118
+ "astro:config:setup": ({ command, config, updateConfig, injectRoute, injectScript, addMiddleware, logger }) => {
118
119
  const root = process.cwd();
119
120
 
120
121
  // One copy per library the admin shares with the project — see shared-deps.ts.
@@ -172,6 +173,12 @@ export default function cmsIntegration(options?: CmsIntegrationOptions): AstroIn
172
173
  };
173
174
  generateFieldsBarrel();
174
175
 
176
+ // Build-time: the adapter bakes allowedDomains into the server. A project's own setting wins.
177
+ const allowedDomains = allowedDomainsFromOrigin(process.env.CMS_TRUSTED_ORIGIN);
178
+ if (allowedDomains && !config.security?.allowedDomains?.length) {
179
+ updateConfig({ security: { allowedDomains } });
180
+ }
181
+
175
182
  // Virtual module aliases — resolve route imports to the user's app files
176
183
  updateConfig({
177
184
  vite: {
@@ -351,6 +358,10 @@ export default function cmsIntegration(options?: CmsIntegrationOptions): AstroIn
351
358
  pattern: "/api/cms/ai/translate",
352
359
  entrypoint: new URL("../routes/api/ai/translate.ts", import.meta.url),
353
360
  });
361
+ injectRoute({
362
+ pattern: "/api/cms/health",
363
+ entrypoint: new URL("../routes/api/health.ts", import.meta.url),
364
+ });
354
365
  injectRoute({
355
366
  pattern: "/api/cms/cron/publish",
356
367
  entrypoint: new URL("../routes/api/cron/publish.ts", import.meta.url),
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Applies committed Drizzle migrations to the Node SQLite database (CMS_DATABASE_URL).
3
+ *
4
+ * kide migrate # apply pending migrations
5
+ * kide migrate --baseline # mark all migrations applied on a cms:push-synced database
6
+ * kide migrate --check # exit 1 if the schema has changes without a migration (CI)
7
+ *
8
+ * The server can do the apply step itself with CMS_MIGRATE_ON_BOOT=1.
9
+ */
10
+ import { mkdirSync } from "node:fs";
11
+ import path from "node:path";
12
+ import Database from "better-sqlite3";
13
+
14
+ import { applyMigrations, baselineMigrations, getMigrationsDir } from "../platform/node/migrate";
15
+ import { pendingMigrationStatements } from "./migrations-check";
16
+ import { loadGeneratedSchema } from "./project";
17
+
18
+ const dir = getMigrationsDir();
19
+ const fail = (message: string): never => {
20
+ console.error(`[kide migrate] ${message}`);
21
+ process.exit(1);
22
+ };
23
+
24
+ if (process.argv.includes("--check")) {
25
+ const statements = await pendingMigrationStatements(await loadGeneratedSchema(), dir).catch((error: Error) =>
26
+ fail(error.message),
27
+ );
28
+ if (statements.length) {
29
+ fail(`Schema has changes without a migration. Run \`pnpm db:generate\` and commit:\n ${statements.join("\n ")}`);
30
+ }
31
+ console.log("[kide migrate] Migrations match the schema.");
32
+ } else {
33
+ const dbPath = process.env.CMS_DATABASE_URL ?? path.join(process.cwd(), "data", "cms.db");
34
+ mkdirSync(path.dirname(path.resolve(dbPath)), { recursive: true });
35
+ const sqlite = new Database(dbPath);
36
+ try {
37
+ if (process.argv.includes("--baseline")) {
38
+ const count = baselineMigrations(sqlite, dir);
39
+ console.log(`[kide migrate] Baselined ${count} migration(s) on ${dbPath} without running them.`);
40
+ } else {
41
+ applyMigrations(sqlite, dir);
42
+ console.log(`[kide migrate] ${dbPath} is up to date.`);
43
+ }
44
+ } catch (error) {
45
+ fail((error as Error).message);
46
+ } finally {
47
+ sqlite.close();
48
+ }
49
+ }
@@ -0,0 +1,17 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { generateSQLiteDrizzleJson, generateSQLiteMigration } from "drizzle-kit/api";
4
+
5
+ // Diffs the generated schema against the latest committed snapshot. Any statement means a
6
+ // schema change has no migration yet (`pnpm db:generate` was forgotten).
7
+ export async function pendingMigrationStatements(schema: Record<string, unknown>, dir: string): Promise<string[]> {
8
+ const journalPath = path.join(dir, "meta", "_journal.json");
9
+ if (!existsSync(journalPath)) throw new Error(`No migrations at ${dir}.`);
10
+ const journal = JSON.parse(readFileSync(journalPath, "utf8")) as { entries: Array<{ idx: number }> };
11
+ const last = journal.entries.at(-1);
12
+ if (!last) throw new Error(`Migration journal at ${journalPath} is empty.`);
13
+ const snapshotPath = path.join(dir, "meta", `${String(last.idx).padStart(4, "0")}_snapshot.json`);
14
+ const prev = JSON.parse(readFileSync(snapshotPath, "utf8"));
15
+ const cur = await generateSQLiteDrizzleJson({ ...schema });
16
+ return generateSQLiteMigration(prev, cur);
17
+ }
@@ -344,6 +344,9 @@ const choosePacketDir = (cwd: string, fromRef: string, targetRef: string) => {
344
344
  const backupFiles = (cwd: string, packetDir: string, files: string[]) => {
345
345
  const backupDir = path.join(packetDir, "backup");
346
346
  mkdirSync(backupDir, { recursive: true });
347
+ // Snapshots are pre-upgrade copies, not project code: keep `eslint .` out of them. ESLint
348
+ // resolves config per directory, so this works whatever the project's root config says.
349
+ writeFileSync(path.join(backupDir, "eslint.config.mjs"), 'export default [{ ignores: ["**/*"] }];\n');
347
350
  const backedUp: string[] = [];
348
351
  const missing: string[] = [];
349
352
  const entries: BackupEntry[] = [];
@@ -15,6 +15,9 @@ import config from "virtual:kide/config";
15
15
  import "virtual:kide/runtime";
16
16
  import { getDb } from "virtual:kide/db";
17
17
 
18
+ import { isSameOriginRequest } from "./csrf";
19
+ import { startSchedulerOnce } from "./scheduler";
20
+
18
21
  let hasUsers: boolean | null = null;
19
22
 
20
23
  export const resetUserCache = () => {
@@ -62,6 +65,7 @@ export const onRequest = defineMiddleware(async (context, next) => {
62
65
 
63
66
  const handle = async (context: APIContext, next: MiddlewareNext) => {
64
67
  const { pathname } = context.url;
68
+ startSchedulerOnce(context);
65
69
 
66
70
  // `?preview` exposes draft content on public pages; require a session (unauth → strip it).
67
71
  if (context.url.searchParams.has("preview")) {
@@ -90,8 +94,9 @@ const handle = async (context: APIContext, next: MiddlewareNext) => {
90
94
  // Public despite the /api/cms prefix: cmsImageUrl() puts these URLs on public pages.
91
95
  // Only reads files under public/, which are served unauthenticated anyway.
92
96
  const isPublicImageApi = pathname.startsWith("/api/cms/img/");
97
+ const isHealthApi = pathname === "/api/cms/health";
93
98
 
94
- if ((!isAdminRoute && !isAdminApiRoute) || isPublicImageApi) {
99
+ if ((!isAdminRoute && !isAdminApiRoute) || isPublicImageApi || isHealthApi) {
95
100
  return next();
96
101
  }
97
102
 
@@ -127,25 +132,7 @@ const handle = async (context: APIContext, next: MiddlewareNext) => {
127
132
  pathname.startsWith("/api/cms/webhooks/") ||
128
133
  pathname.startsWith("/api/cms/forms/submit/");
129
134
  if (method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && !isMachineEndpoint) {
130
- // Compare against an explicitly configured origin when set (robust behind a proxy that
131
- // may rewrite Host); otherwise fall back to the request's own origin.
132
- const host = publicOrigin(context.request);
133
- const origin = context.request.headers.get("origin");
134
- const referer = context.request.headers.get("referer");
135
- const secFetchSite = context.request.headers.get("sec-fetch-site");
136
-
137
- let refererOk = false;
138
- if (!origin && referer) {
139
- try {
140
- refererOk = new URL(referer).origin === host;
141
- } catch {
142
- refererOk = false;
143
- }
144
- }
145
- const originOk = origin === host;
146
- // Reject an explicit cross-site Fetch-Metadata signal, or the absence of any
147
- // trustworthy same-origin signal (the hole the old `if (origin && ...)` left open).
148
- if (secFetchSite === "cross-site" || !(originOk || refererOk)) {
135
+ if (!isSameOriginRequest(context.request.headers, publicOrigin(context.request))) {
149
136
  return new Response(JSON.stringify({ error: "Forbidden" }), {
150
137
  status: 403,
151
138
  headers: { "Content-Type": "application/json" },
@@ -0,0 +1,19 @@
1
+ // Same-origin proof for a state-changing request. Fetch Metadata comes first: browsers set
2
+ // Sec-Fetch-Site themselves, and it doesn't depend on the server knowing its public origin
3
+ // (behind a proxy without CMS_TRUSTED_ORIGIN, request.url is localhost). Origin/Referer is
4
+ // the fallback for clients that don't send it.
5
+ export const isSameOriginRequest = (headers: Headers, expectedOrigin: string): boolean => {
6
+ const secFetchSite = headers.get("sec-fetch-site");
7
+ if (secFetchSite === "same-origin") return true;
8
+ if (secFetchSite && secFetchSite !== "none") return false;
9
+
10
+ const origin = headers.get("origin");
11
+ if (origin) return origin === expectedOrigin;
12
+ const referer = headers.get("referer");
13
+ if (!referer) return false;
14
+ try {
15
+ return new URL(referer).origin === expectedOrigin;
16
+ } catch {
17
+ return false;
18
+ }
19
+ };
@@ -0,0 +1,44 @@
1
+ import type { APIContext } from "astro";
2
+
3
+ import { readEnv } from "../core";
4
+ import { log } from "../core/log";
5
+ import { runPublishJob, runTasksJob } from "../routes/api/cron/_jobs";
6
+
7
+ const INTERVAL_MS = 60_000;
8
+
9
+ let started = false;
10
+
11
+ // CMS_SCHEDULER=1 runs the publish and tasks cron jobs inside a long-lived Node server, replacing an
12
+ // external cron. Starts on the first request: Astro's standalone server has no boot hook, and the
13
+ // request's cache handle is needed so publishing can invalidate cached pages. That handle only
14
+ // forwards to the app-wide cache provider, so holding it past the request is safe.
15
+ export const startSchedulerOnce = (context: APIContext) => {
16
+ if (started) return;
17
+ started = true;
18
+
19
+ const flag = readEnv("CMS_SCHEDULER")?.trim().toLowerCase();
20
+ if (flag !== "1" && flag !== "true") return;
21
+ // Workers have their own scheduled() handler and don't keep timers alive between requests.
22
+ if ((context.locals as { cfContext?: unknown }).cfContext) return;
23
+
24
+ const cache = context.cache;
25
+ let running = false;
26
+ const run = async () => {
27
+ if (running) return;
28
+ running = true;
29
+ try {
30
+ const { cms } = await import("virtual:kide/api");
31
+ await runPublishJob(cms as never, cache);
32
+ await runTasksJob(cms as never);
33
+ } catch (error) {
34
+ log.error("[kide] scheduler run failed:", error);
35
+ } finally {
36
+ running = false;
37
+ }
38
+ };
39
+
40
+ const timer = setInterval(run, INTERVAL_MS);
41
+ (timer as { unref?: () => void }).unref?.();
42
+ void run();
43
+ log.info("[kide] scheduler started (publish + tasks every 60s)");
44
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kidecms/core",
3
- "version": "0.34.0",
3
+ "version": "0.36.0",
4
4
  "description": "Kide CMS runtime — core library, admin UI, routes, and middleware for Astro. Shipped as TypeScript source.",
5
5
  "keywords": [
6
6
  "cms",
@@ -19,7 +19,7 @@
19
19
  },
20
20
  "bugs": "https://github.com/mhernesniemi/kide-cms/issues",
21
21
  "engines": {
22
- "node": ">=22.12.0"
22
+ "node": ">=22.23.4"
23
23
  },
24
24
  "bin": {
25
25
  "kide": "./internals/cli.mjs"
@@ -51,38 +51,38 @@
51
51
  "access": "public"
52
52
  },
53
53
  "dependencies": {
54
- "@ai-sdk/openai": "^3.0.114",
55
- "@base-ui/react": "^1.8.0",
56
- "@better-auth/passkey": "1.7.7",
57
- "@better-auth/utils": "0.4.2",
54
+ "@ai-sdk/openai": "^3.0.132",
55
+ "@base-ui/react": "^1.9.0",
56
+ "@better-auth/passkey": "1.7.14",
57
+ "@better-auth/utils": "0.5.1",
58
58
  "@dnd-kit/core": "^6.3.1",
59
59
  "@dnd-kit/sortable": "^10.0.0",
60
60
  "@dnd-kit/utilities": "^3.2.2",
61
- "@modelcontextprotocol/sdk": "^1.30.0",
62
- "@radix-ui/react-dropdown-menu": "^2.1.24",
63
- "@radix-ui/react-popover": "^1.1.23",
61
+ "@modelcontextprotocol/sdk": "^1.32.2",
62
+ "@radix-ui/react-dropdown-menu": "^2.2.1",
63
+ "@radix-ui/react-popover": "^1.3.1",
64
64
  "@simplewebauthn/browser": "^13.3.0",
65
65
  "@tanstack/react-table": "^8.21.3",
66
- "@tiptap/core": "3.31.3",
67
- "@tiptap/extension-image": "3.31.3",
68
- "@tiptap/extension-link": "3.31.3",
69
- "@tiptap/extension-placeholder": "3.31.3",
70
- "@tiptap/markdown": "3.31.3",
71
- "@tiptap/pm": "3.31.3",
72
- "@tiptap/react": "3.31.3",
73
- "@tiptap/starter-kit": "3.31.3",
74
- "@tiptap/suggestion": "3.31.3",
75
- "ai": "^6.0.286",
66
+ "@tiptap/core": "3.32.0",
67
+ "@tiptap/extension-image": "3.32.0",
68
+ "@tiptap/extension-link": "3.32.0",
69
+ "@tiptap/extension-placeholder": "3.32.0",
70
+ "@tiptap/markdown": "3.32.0",
71
+ "@tiptap/pm": "3.32.0",
72
+ "@tiptap/react": "3.32.0",
73
+ "@tiptap/starter-kit": "3.32.0",
74
+ "@tiptap/suggestion": "3.32.0",
75
+ "ai": "^6.0.316",
76
76
  "aws4fetch": "^1.0.20",
77
- "better-auth": "1.7.7",
77
+ "better-auth": "1.7.14",
78
78
  "class-variance-authority": "^0.7.1",
79
79
  "clsx": "^2.1.1",
80
80
  "cmdk": "^1.1.1",
81
- "drizzle-kit": "^0.31.10",
82
- "lucide-react": "^1.47.0",
83
- "nanoid": "^6.0.1",
81
+ "drizzle-kit": "^0.31.11",
82
+ "lucide-react": "^1.62.0",
83
+ "nanoid": "^6.0.2",
84
84
  "tailwind-merge": "^3.7.0",
85
- "tsx": "^4.23.13",
85
+ "tsx": "^4.23.15",
86
86
  "tw-animate-css": "^1.4.0",
87
87
  "uqr": "^0.1.3"
88
88
  },
@@ -3,6 +3,8 @@ import path from "node:path";
3
3
  import Database from "better-sqlite3";
4
4
  import { drizzle } from "drizzle-orm/better-sqlite3";
5
5
 
6
+ import { applyMigrations } from "./migrate";
7
+
6
8
  let dbInstance: ReturnType<typeof drizzle> | null = null;
7
9
  let sqliteInstance: InstanceType<typeof Database> | null = null;
8
10
 
@@ -12,10 +14,9 @@ const getDbPath = () => {
12
14
  return path.join(process.cwd(), "data", "cms.db");
13
15
  };
14
16
 
15
- // Startup does no schema work. The generated schema (from collections-as-code) is the
16
- // source of truth, and `pnpm cms:push` is the single sync mechanism on the Node target —
17
- // run it in dev and as a deploy step before `pnpm start`. (Cloudflare D1 syncs out of
18
- // band via `wrangler d1 migrations apply`; see platform/cloudflare/database.ts.)
17
+ // By default startup does no schema work: `pnpm cms:push` syncs the schema in dev and as a
18
+ // deploy step. With CMS_MIGRATE_ON_BOOT=1 the first connection applies the committed
19
+ // migrations instead (the same files D1 applies via `wrangler d1 migrations apply`).
19
20
  export const getDb = async () => {
20
21
  if (dbInstance) return dbInstance;
21
22
 
@@ -25,6 +26,15 @@ export const getDb = async () => {
25
26
  sqliteInstance = new Database(dbPath);
26
27
  sqliteInstance.pragma("journal_mode = WAL");
27
28
  sqliteInstance.pragma("foreign_keys = ON");
29
+ if (/^(1|true)$/i.test(process.env.CMS_MIGRATE_ON_BOOT ?? "")) {
30
+ try {
31
+ applyMigrations(sqliteInstance);
32
+ } catch (error) {
33
+ sqliteInstance.close();
34
+ sqliteInstance = null;
35
+ throw error;
36
+ }
37
+ }
28
38
 
29
39
  dbInstance = drizzle(sqliteInstance);
30
40
  return dbInstance;
@@ -0,0 +1,57 @@
1
+ import { existsSync } from "node:fs";
2
+ import path from "node:path";
3
+ import type Database from "better-sqlite3";
4
+ import { drizzle } from "drizzle-orm/better-sqlite3";
5
+ import { migrate } from "drizzle-orm/better-sqlite3/migrator";
6
+ import { readMigrationFiles } from "drizzle-orm/migrator";
7
+
8
+ // The same drizzle-kit output Cloudflare D1 applies with wrangler; Node tracks it in __drizzle_migrations.
9
+ export const getMigrationsDir = () =>
10
+ process.env.CMS_MIGRATIONS_DIR
11
+ ? path.resolve(process.env.CMS_MIGRATIONS_DIR)
12
+ : path.join(process.cwd(), "src", "cms", "migrations");
13
+
14
+ const hasJournal = (dir: string) => existsSync(path.join(dir, "meta", "_journal.json"));
15
+
16
+ const hasTable = (sqlite: InstanceType<typeof Database>, name: string) =>
17
+ !!sqlite.prepare("select 1 from sqlite_master where type = 'table' and name = ?").get(name);
18
+
19
+ // Runtime-only (drizzle-orm, no drizzle-kit/tsx), so it can run inside a built server image.
20
+ export function applyMigrations(sqlite: InstanceType<typeof Database>, dir = getMigrationsDir()): void {
21
+ if (!hasJournal(dir)) {
22
+ throw new Error(`No migrations at ${dir}. Generate them with \`pnpm db:generate\` and commit the folder.`);
23
+ }
24
+ if (!hasTable(sqlite, "__drizzle_migrations") && hasTable(sqlite, "cms_users")) {
25
+ throw new Error(
26
+ "Database was synced with cms:push and tracks no migrations. Once it matches the latest migration, " +
27
+ "run `kide migrate --baseline` once to mark them applied.",
28
+ );
29
+ }
30
+ // Table rebuilds (drop + recreate) must not cascade; the PRAGMA is a no-op inside the migrator's transaction.
31
+ const foreignKeys = sqlite.pragma("foreign_keys", { simple: true });
32
+ sqlite.pragma("foreign_keys = OFF");
33
+ try {
34
+ migrate(drizzle(sqlite), { migrationsFolder: dir });
35
+ } finally {
36
+ sqlite.pragma(`foreign_keys = ${foreignKeys ? "ON" : "OFF"}`);
37
+ }
38
+ }
39
+
40
+ // For a database that predates migrations (synced with cms:push): records every migration as
41
+ // applied without running it. Only correct when the database already matches the latest one.
42
+ export function baselineMigrations(sqlite: InstanceType<typeof Database>, dir = getMigrationsDir()): number {
43
+ if (!hasJournal(dir)) throw new Error(`No migrations at ${dir}.`);
44
+ if (hasTable(sqlite, "__drizzle_migrations")) {
45
+ const row = sqlite.prepare("select count(*) as n from __drizzle_migrations").get() as { n: number };
46
+ if (row.n > 0) throw new Error("Database already tracks migrations; nothing to baseline.");
47
+ }
48
+ sqlite.exec(
49
+ `CREATE TABLE IF NOT EXISTS "__drizzle_migrations" (id SERIAL PRIMARY KEY, hash text NOT NULL, created_at numeric)`,
50
+ );
51
+ const insert = sqlite.prepare(`INSERT INTO "__drizzle_migrations" ("hash", "created_at") VALUES (?, ?)`);
52
+ const migrations = readMigrationFiles({ migrationsFolder: dir });
53
+ sqlite.transaction(() => {
54
+ for (const m of migrations) insert.run(m.hash, m.folderMillis);
55
+ })();
56
+ return migrations.length;
57
+ }
@@ -0,0 +1,23 @@
1
+ import { pruneAuditLog, pruneRateLimits } from "../../../core";
2
+
3
+ type CacheInvalidator = { invalidate: (opts: { tags: string[] }) => void | Promise<void> };
4
+ type CronCms = {
5
+ scheduled: { processPublishing: (cache?: CacheInvalidator) => Promise<{ published: number; unpublished: number }> };
6
+ tasks: {
7
+ tick: () => Promise<number>;
8
+ drain: () => Promise<{ processed: number; succeeded: number; failed: number }>;
9
+ prune: () => Promise<unknown>;
10
+ };
11
+ };
12
+
13
+ // Shared by the cron endpoints and the in-process scheduler (CMS_SCHEDULER) so both run the same work.
14
+ export const runPublishJob = (cms: CronCms, cache?: CacheInvalidator) => cms.scheduled.processPublishing(cache);
15
+
16
+ export const runTasksJob = async (cms: CronCms) => {
17
+ const scheduled = await cms.tasks.tick();
18
+ const result = await cms.tasks.drain();
19
+ await cms.tasks.prune();
20
+ await pruneRateLimits();
21
+ await pruneAuditLog();
22
+ return { scheduled, ...result };
23
+ };
@@ -3,17 +3,16 @@ import type { APIRoute } from "astro";
3
3
  import { cms } from "virtual:kide/api";
4
4
 
5
5
  import { isAuthorized, unauthorized } from "./_authorize";
6
+ import { runPublishJob } from "./_jobs";
6
7
 
7
8
  export const prerender = false;
8
9
 
9
- const cmsRuntime = cms as Record<string, any> & { scheduled: typeof cms.scheduled };
10
-
11
10
  const handler: APIRoute = async ({ request, cache }) => {
12
11
  if (!isAuthorized(request)) {
13
12
  return unauthorized();
14
13
  }
15
14
 
16
- const result = await cmsRuntime.scheduled.processPublishing(cache);
15
+ const result = await runPublishJob(cms as never, cache);
17
16
 
18
17
  return Response.json({
19
18
  ok: true,
@@ -1,28 +1,22 @@
1
1
  import type { APIRoute } from "astro";
2
2
 
3
3
  import { cms } from "virtual:kide/api";
4
- import { pruneAuditLog, pruneRateLimits } from "../../../core";
5
4
 
6
5
  import { isAuthorized, unauthorized } from "./_authorize";
6
+ import { runTasksJob } from "./_jobs";
7
7
 
8
8
  export const prerender = false;
9
9
 
10
- const cmsRuntime = cms as Record<string, any> & { tasks: typeof cms.tasks };
11
-
12
10
  const handler: APIRoute = async ({ request }) => {
13
11
  if (!isAuthorized(request)) {
14
12
  return unauthorized();
15
13
  }
16
14
 
17
- const scheduled = await cmsRuntime.tasks.tick();
18
- const result = await cmsRuntime.tasks.drain();
19
- await cmsRuntime.tasks.prune();
20
- await pruneRateLimits();
21
- await pruneAuditLog();
15
+ const result = await runTasksJob(cms as never);
22
16
 
23
17
  return Response.json({
24
18
  ok: true,
25
- scheduled,
19
+ scheduled: result.scheduled,
26
20
  processed: result.processed,
27
21
  succeeded: result.succeeded,
28
22
  failed: result.failed,
@@ -0,0 +1,24 @@
1
+ import type { APIRoute } from "astro";
2
+ import { sql } from "drizzle-orm";
3
+ // Narrow imports (not the core barrel): this route compiles in the Cloudflare profile too.
4
+ import { log } from "../../core/log";
5
+ import { getDb } from "../../core/runtime";
6
+
7
+ export const prerender = false;
8
+
9
+ // Liveness + readiness for deploy healthchecks and uptime monitors. Queries a CMS table, not
10
+ // `select 1`: SQLite silently creates an empty file at a wrong path, and that must fail too.
11
+ const handler: APIRoute = async () => {
12
+ const headers = { "Cache-Control": "no-store" };
13
+ try {
14
+ const db = await getDb();
15
+ await db.all(sql`select 1 from cms_users limit 1`);
16
+ return Response.json({ ok: true }, { headers });
17
+ } catch (error) {
18
+ log.error("[kide] health check failed:", error);
19
+ return Response.json({ ok: false }, { status: 503, headers });
20
+ }
21
+ };
22
+
23
+ export const GET = handler;
24
+ export const HEAD = handler;