@korajs/cli 1.0.0-beta.12 → 1.0.0-beta.14
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/README.md +25 -107
- package/dist/bin.cjs +808 -340
- package/dist/bin.cjs.map +1 -1
- package/dist/bin.js +588 -174
- package/dist/bin.js.map +1 -1
- package/dist/{chunk-G2PBYMMA.js → chunk-7Y4J2GXP.js} +168 -153
- package/dist/chunk-7Y4J2GXP.js.map +1 -0
- package/dist/{chunk-Z7GCXMGW.js → chunk-BURFQVMV.js} +44 -9
- package/dist/chunk-BURFQVMV.js.map +1 -0
- package/dist/{chunk-4IKCHRJ6.js → chunk-TVIRMDER.js} +122 -112
- package/dist/chunk-TVIRMDER.js.map +1 -0
- package/dist/create.cjs +63 -28
- package/dist/create.cjs.map +1 -1
- package/dist/create.js +2 -2
- package/dist/index.cjs +41 -14
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +21 -1
- package/dist/index.d.ts +21 -1
- package/dist/index.js +8 -2
- package/dist/{studio-server-NIFKZI4F.js → studio-server-XLGZNGG5.js} +11 -2
- package/dist/studio-server-XLGZNGG5.js.map +1 -0
- package/dist/vite.cjs +351 -0
- package/dist/vite.cjs.map +1 -0
- package/dist/vite.d.cts +161 -0
- package/dist/vite.d.ts +161 -0
- package/dist/vite.js +321 -0
- package/dist/vite.js.map +1 -0
- package/package.json +18 -8
- package/templates/react-basic/AGENTS.md +5 -5
- package/templates/react-basic/vite.config.ts +4 -1
- package/templates/react-sync/.env.example +1 -1
- package/templates/react-sync/AGENTS.md +5 -5
- package/templates/react-sync/server.ts +8 -0
- package/templates/react-sync/src/vite-env.d.ts +1 -0
- package/templates/react-sync/vite.config.ts +4 -1
- package/templates/react-tailwind/AGENTS.md +5 -5
- package/templates/react-tailwind/vite.config.ts +10 -1
- package/templates/react-tailwind-sync/.env.example +1 -1
- package/templates/react-tailwind-sync/AGENTS.md +9 -7
- package/templates/react-tailwind-sync/server.ts +8 -0
- package/templates/react-tailwind-sync/src/App.tsx +1 -1
- package/templates/react-tailwind-sync/src/kora.ts +32 -0
- package/templates/react-tailwind-sync/src/main.tsx +1 -23
- package/templates/react-tailwind-sync/src/modules/todos/todo.mutations.ts +4 -8
- package/templates/react-tailwind-sync/src/modules/todos/todo.queries.ts +2 -2
- package/templates/react-tailwind-sync/src/modules/todos/useTodos.ts +1 -1
- package/templates/react-tailwind-sync/src/vite-env.d.ts +1 -0
- package/templates/react-tailwind-sync/vite.config.ts +10 -1
- package/templates/svelte-basic/AGENTS.md +4 -4
- package/templates/svelte-basic/package.json.hbs +6 -0
- package/templates/svelte-basic/src/App.svelte +2 -1
- package/templates/svelte-basic/vite.config.ts +4 -1
- package/templates/svelte-sync/.env.example +1 -1
- package/templates/svelte-sync/AGENTS.md +4 -4
- package/templates/svelte-sync/server.ts +8 -0
- package/templates/svelte-sync/src/App.svelte +2 -1
- package/templates/svelte-sync/vite.config.ts +4 -1
- package/templates/svelte-tailwind/AGENTS.md +4 -4
- package/templates/svelte-tailwind/package.json.hbs +7 -1
- package/templates/svelte-tailwind/src/App.svelte +2 -1
- package/templates/svelte-tailwind/vite.config.ts +10 -1
- package/templates/svelte-tailwind-sync/.env.example +1 -1
- package/templates/svelte-tailwind-sync/AGENTS.md +4 -4
- package/templates/svelte-tailwind-sync/package.json.hbs +1 -1
- package/templates/svelte-tailwind-sync/server.ts +8 -0
- package/templates/svelte-tailwind-sync/src/App.svelte +2 -1
- package/templates/svelte-tailwind-sync/vite.config.ts +10 -1
- package/templates/tauri-react/.env.example +1 -1
- package/templates/tauri-react/AGENTS.md +5 -5
- package/templates/tauri-react/README.md.hbs +2 -2
- package/templates/tauri-react/package.json.hbs +1 -1
- package/templates/tauri-react/server.ts +10 -2
- package/templates/tauri-react/src/vite-env.d.ts +1 -0
- package/templates/vue-basic/AGENTS.md +4 -4
- package/templates/vue-basic/package.json.hbs +6 -0
- package/templates/vue-basic/vite.config.ts +4 -1
- package/templates/vue-sync/.env.example +1 -1
- package/templates/vue-sync/AGENTS.md +4 -4
- package/templates/vue-sync/server.ts +8 -0
- package/templates/vue-sync/vite.config.ts +4 -1
- package/templates/vue-tailwind/AGENTS.md +4 -4
- package/templates/vue-tailwind/package.json.hbs +6 -0
- package/templates/vue-tailwind/vite.config.ts +4 -1
- package/templates/vue-tailwind-sync/.env.example +1 -1
- package/templates/vue-tailwind-sync/AGENTS.md +4 -4
- package/templates/vue-tailwind-sync/server.ts +8 -0
- package/templates/vue-tailwind-sync/vite.config.ts +4 -1
- package/dist/chunk-4IKCHRJ6.js.map +0 -1
- package/dist/chunk-G2PBYMMA.js.map +0 -1
- package/dist/chunk-Z7GCXMGW.js.map +0 -1
- package/dist/studio-server-NIFKZI4F.js.map +0 -1
package/dist/bin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/bin.ts","../src/commands/backup/backup-command.ts","../src/commands/compact/compact-command.ts","../src/commands/dev/kora-config.ts","../src/commands/dev/dev-command.ts","../src/commands/dev/process-manager.ts","../src/commands/dev/schema-watcher.ts","../src/commands/doctor/doctor-command.ts","../src/commands/doctor/doctor-checks.ts","../src/commands/generate/generate-command.ts","../src/commands/generate/hook-generator.ts","../src/commands/logs/logs-command.ts","../src/commands/migrate/migrate-command.ts","../src/commands/migrate/migration-generator.ts","../src/commands/migrate/schema-differ.ts","../src/commands/migrate/migration-runner.ts","../src/commands/migrate/operation-transform-generator.ts","../src/commands/status/status-command.ts","../src/commands/studio/studio-command.ts"],"sourcesContent":["import { defineCommand, runMain } from 'citty'\nimport { agentsCommand } from './commands/agents/agents-command'\nimport { backupCommand } from './commands/backup/backup-command'\nimport { compactCommand } from './commands/compact/compact-command'\nimport { createCommand } from './commands/create/create-command'\nimport { deployCommand } from './commands/deploy/deploy-command'\nimport { devCommand } from './commands/dev/dev-command'\nimport { doctorCommand } from './commands/doctor/doctor-command'\nimport { generateCommand } from './commands/generate/generate-command'\nimport { logsCommand } from './commands/logs/logs-command'\nimport { migrateCommand } from './commands/migrate/migrate-command'\nimport { statusCommand } from './commands/status/status-command'\nimport { studioCommand } from './commands/studio/studio-command'\n\nconst main = defineCommand({\n\tmeta: {\n\t\tname: 'kora',\n\t\tdescription: 'Kora.js, the offline-first application framework',\n\t},\n\tsubCommands: {\n\t\t'agents-md': agentsCommand,\n\t\tbackup: backupCommand,\n\t\tcompact: compactCommand,\n\t\tcreate: createCommand,\n\t\tdev: devCommand,\n\t\tdoctor: doctorCommand,\n\t\tdeploy: deployCommand,\n\t\tgenerate: generateCommand,\n\t\tlogs: logsCommand,\n\t\tmigrate: migrateCommand,\n\t\tstatus: statusCommand,\n\t\tstudio: studioCommand,\n\t},\n})\n\nrunMain(main)\n","import { readFile, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { defineCommand } from 'citty'\nimport { createLogger } from '../../utils/logger'\n\nconst DEFAULT_SYNC_PORT = 3001\n\n/**\n * The `backup` command — creates and restores Kora sync server backups.\n */\nexport const backupCommand = defineCommand({\n\tmeta: {\n\t\tname: 'backup',\n\t\tdescription: 'Backup and restore Kora sync server data',\n\t},\n\tsubCommands: {\n\t\tcreate: defineCommand({\n\t\t\tmeta: {\n\t\t\t\tname: 'create',\n\t\t\t\tdescription: 'Create a backup of the sync server',\n\t\t\t},\n\t\t\targs: {\n\t\t\t\turl: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Sync server URL (default: http://localhost:3001)',\n\t\t\t\t\tdefault: `http://localhost:${DEFAULT_SYNC_PORT}`,\n\t\t\t\t},\n\t\t\t\tout: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Output file path (default: kora-backup-<timestamp>.kora)',\n\t\t\t\t},\n\t\t\t\ttoken: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Backup token (defaults to KORA_BACKUP_TOKEN or KORA_ADMIN_TOKEN)',\n\t\t\t\t},\n\t\t\t},\n\t\t\tasync run({ args }) {\n\t\t\t\tconst logger = createLogger()\n\t\t\t\tconst url =\n\t\t\t\t\ttypeof args.url === 'string' ? args.url : `http://localhost:${DEFAULT_SYNC_PORT}`\n\t\t\t\tconst outFile = typeof args.out === 'string' ? args.out : `kora-backup-${Date.now()}.kora`\n\t\t\t\tconst token =\n\t\t\t\t\ttypeof args.token === 'string'\n\t\t\t\t\t\t? args.token\n\t\t\t\t\t\t: (process.env.KORA_BACKUP_TOKEN ?? process.env.KORA_ADMIN_TOKEN)\n\n\t\t\t\tlogger.banner()\n\t\t\t\tlogger.info(`Exporting backup from ${url}...`)\n\n\t\t\t\ttry {\n\t\t\t\t\tconst backupUrl = `${url.replace(/\\/$/, '')}/__kora/backup/export`\n\t\t\t\t\tconst response = await fetch(backupUrl, {\n\t\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\t\theaders: token ? { Authorization: `Bearer ${token}` } : undefined,\n\t\t\t\t\t})\n\n\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\tconst error = await response.json().catch(() => ({ message: response.statusText }))\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Backup failed: ${(error as { message: string }).message ?? response.statusText}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\n\t\t\t\t\tconst buffer = await response.arrayBuffer()\n\t\t\t\t\tawait writeFile(outFile, new Uint8Array(buffer))\n\n\t\t\t\t\tconst size = (buffer.byteLength / 1024).toFixed(1)\n\t\t\t\t\tlogger.success(`Backup saved to ${outFile} (${size} KB)`)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error('Backup failed')\n\t\t\t\t\tif (error instanceof Error) logger.error(error.message)\n\t\t\t\t\tlogger.blank()\n\t\t\t\t\tlogger.step('Make sure the Kora sync server is running.')\n\t\t\t\t\tprocess.exit(1)\n\t\t\t\t}\n\t\t\t},\n\t\t}),\n\n\t\trestore: defineCommand({\n\t\t\tmeta: {\n\t\t\t\tname: 'restore',\n\t\t\t\tdescription: 'Restore a backup to the sync server',\n\t\t\t},\n\t\t\targs: {\n\t\t\t\tfile: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Backup file path',\n\t\t\t\t\trequired: true,\n\t\t\t\t},\n\t\t\t\turl: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Sync server URL (default: http://localhost:3001)',\n\t\t\t\t\tdefault: `http://localhost:${DEFAULT_SYNC_PORT}`,\n\t\t\t\t},\n\t\t\t\tmerge: {\n\t\t\t\t\ttype: 'boolean',\n\t\t\t\t\tdescription: 'Merge with existing data instead of replacing',\n\t\t\t\t\tdefault: false,\n\t\t\t\t},\n\t\t\t\ttoken: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Backup token (defaults to KORA_BACKUP_TOKEN or KORA_ADMIN_TOKEN)',\n\t\t\t\t},\n\t\t\t},\n\t\t\tasync run({ args }) {\n\t\t\t\tconst logger = createLogger()\n\t\t\t\tconst filePath = typeof args.file === 'string' ? args.file : ''\n\t\t\t\tconst url =\n\t\t\t\t\ttypeof args.url === 'string' ? args.url : `http://localhost:${DEFAULT_SYNC_PORT}`\n\t\t\t\tconst merge = args.merge === true\n\t\t\t\tconst token =\n\t\t\t\t\ttypeof args.token === 'string'\n\t\t\t\t\t\t? args.token\n\t\t\t\t\t\t: (process.env.KORA_BACKUP_TOKEN ?? process.env.KORA_ADMIN_TOKEN)\n\n\t\t\t\tlogger.banner()\n\t\t\t\tlogger.info(`Restoring backup from ${filePath} to ${url}...`)\n\n\t\t\t\ttry {\n\t\t\t\t\tconst data = await readFile(filePath)\n\t\t\t\t\tconst restoreUrl = `${url.replace(/\\/$/, '')}/__kora/backup/import?merge=${merge}`\n\n\t\t\t\t\tconst response = await fetch(restoreUrl, {\n\t\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\t\theaders: token ? { Authorization: `Bearer ${token}` } : undefined,\n\t\t\t\t\t\tbody: data,\n\t\t\t\t\t})\n\n\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\tconst error = await response.json().catch(() => ({ message: response.statusText }))\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Restore failed: ${(error as { message: string }).message ?? response.statusText}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\n\t\t\t\t\tconst result = (await response.json()) as {\n\t\t\t\t\t\toperationsRestored: number\n\t\t\t\t\t\tsuccess: boolean\n\t\t\t\t\t\tduration?: number\n\t\t\t\t\t}\n\n\t\t\t\t\tif (result.success) {\n\t\t\t\t\t\tlogger.success(\n\t\t\t\t\t\t\t`Restored ${result.operationsRestored} operations${result.duration ? ` in ${result.duration}ms` : ''}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger.error('Restore completed with errors')\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error('Restore failed')\n\t\t\t\t\tif (error instanceof Error) logger.error(error.message)\n\t\t\t\t\tprocess.exit(1)\n\t\t\t\t}\n\t\t\t},\n\t\t}),\n\n\t\tinfo: defineCommand({\n\t\t\tmeta: {\n\t\t\t\tname: 'info',\n\t\t\t\tdescription: 'Show backup file information',\n\t\t\t},\n\t\t\targs: {\n\t\t\t\tfile: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Backup file path',\n\t\t\t\t\trequired: true,\n\t\t\t\t},\n\t\t\t},\n\t\t\tasync run({ args }) {\n\t\t\t\tconst logger = createLogger()\n\t\t\t\tconst filePath = typeof args.file === 'string' ? args.file : ''\n\n\t\t\t\ttry {\n\t\t\t\t\tconst data = await readFile(filePath)\n\t\t\t\t\tconst { readBackupManifest } = await import('@korajs/store')\n\n\t\t\t\t\tconst manifest = readBackupManifest(\n\t\t\t\t\t\tnew Uint8Array(data.buffer, data.byteOffset, data.byteLength),\n\t\t\t\t\t)\n\n\t\t\t\t\tlogger.banner()\n\t\t\t\t\tlogger.info(`Backup: ${filePath}`)\n\t\t\t\t\tlogger.blank()\n\t\t\t\t\tlogger.step(`Created: ${new Date(manifest.createdAt).toISOString()}`)\n\t\t\t\t\tlogger.step(`Node ID: ${manifest.nodeId}`)\n\t\t\t\t\tlogger.step(`Schema: v${manifest.schemaVersion}`)\n\t\t\t\t\tlogger.step(`Operations: ${manifest.operationCount.toLocaleString()}`)\n\t\t\t\t\tlogger.step(`Collections: ${manifest.collections.join(', ') || '(none)'}`)\n\t\t\t\t\tlogger.step(`Checksum: ${manifest.checksum.slice(0, 16)}...`)\n\t\t\t\t\tlogger.blank()\n\t\t\t\t\tlogger.step(`Format version: ${manifest.version}`)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error('Failed to read backup file')\n\t\t\t\t\tif (error instanceof Error) logger.error(error.message)\n\t\t\t\t\tprocess.exit(1)\n\t\t\t\t}\n\t\t\t},\n\t\t}),\n\t},\n})\n","import { resolve } from 'node:path'\nimport { defineCommand } from 'citty'\nimport { InvalidProjectError } from '../../errors'\nimport { findProjectRoot } from '../../utils/fs-helpers'\nimport { createLogger } from '../../utils/logger'\nimport { loadKoraConfig } from '../dev/kora-config'\nimport { loadSchemaDefinition } from '../migrate/schema-loader'\n\n/**\n * Compact the local client operation log (materialized rows are the baseline).\n */\nexport const compactCommand = defineCommand({\n\tmeta: {\n\t\tname: 'compact',\n\t\tdescription: 'Compact the local Kora operation log after server ack',\n\t},\n\targs: {\n\t\tdb: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Path to the local SQLite database (required)',\n\t\t},\n\t\tschema: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Path to schema file',\n\t\t},\n\t\tstrategy: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Compaction strategy: after-ack | after-days | never',\n\t\t\tdefault: 'after-ack',\n\t\t},\n\t\tdays: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Age threshold when strategy is after-days',\n\t\t\tdefault: '30',\n\t\t},\n\t},\n\tasync run({ args }) {\n\t\tconst logger = createLogger()\n\t\tconst projectRoot = await findProjectRoot()\n\t\tif (!projectRoot) {\n\t\t\tthrow new InvalidProjectError(process.cwd())\n\t\t}\n\n\t\tconst dbPath = typeof args.db === 'string' ? resolve(projectRoot, args.db) : undefined\n\t\tif (!dbPath) {\n\t\t\tthrow new Error('Missing --db <path> to the local SQLite database file.')\n\t\t}\n\n\t\tconst config = await loadKoraConfig(projectRoot)\n\t\tconst schemaPath =\n\t\t\ttypeof args.schema === 'string'\n\t\t\t\t? resolve(projectRoot, args.schema)\n\t\t\t\t: typeof config?.schema === 'string'\n\t\t\t\t\t? resolve(projectRoot, config.schema)\n\t\t\t\t\t: undefined\n\t\tif (!schemaPath) {\n\t\t\tthrow new Error('Could not resolve schema path. Pass --schema <path>.')\n\t\t}\n\n\t\tconst schema = await loadSchemaDefinition(schemaPath, projectRoot)\n\t\tconst { BetterSqlite3Adapter } = await import('@korajs/store/better-sqlite3')\n\t\tconst { Store } = await import('@korajs/store')\n\n\t\tconst strategyName = typeof args.strategy === 'string' ? args.strategy : 'after-ack'\n\t\tconst days = Number.parseInt(typeof args.days === 'string' ? args.days : '30', 10)\n\n\t\tconst store = new Store({\n\t\t\tschema,\n\t\t\tadapter: new BetterSqlite3Adapter(dbPath),\n\t\t})\n\t\tawait store.open()\n\n\t\tlet result: { deletedCount: number; watermark: Map<string, number> }\n\t\tif (strategyName === 'never') {\n\t\t\tresult = await store.compact({ mode: 'never' })\n\t\t} else if (strategyName === 'after-days') {\n\t\t\tresult = await store.compact({ mode: 'after-days', days })\n\t\t} else if (strategyName === 'after-ack') {\n\t\t\tresult = await store.compact({ mode: 'after-ack' })\n\t\t} else {\n\t\t\tawait store.close()\n\t\t\tthrow new Error(`Unknown strategy \"${strategyName}\". Use after-ack, after-days, or never.`)\n\t\t}\n\n\t\tawait store.close()\n\n\t\tlogger.banner()\n\t\tlogger.success(`Compacted ${result.deletedCount} operation log entries.`)\n\t\tfor (const [nodeId, seq] of result.watermark) {\n\t\t\tlogger.step(` ${nodeId}: seq <= ${seq}`)\n\t\t}\n\t},\n})\n","import { spawn } from 'node:child_process'\nimport { access } from 'node:fs/promises'\nimport { extname, join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { hasTsxInstalled } from '../../utils/fs-helpers'\n\nexport interface KoraConfigFile {\n\tschema?: string\n\tdev?: {\n\t\tport?: number\n\t\tsync?:\n\t\t\t| boolean\n\t\t\t| {\n\t\t\t\t\tenabled?: boolean\n\t\t\t\t\tport?: number\n\t\t\t\t\tstore?:\n\t\t\t\t\t\t| 'memory'\n\t\t\t\t\t\t| 'sqlite'\n\t\t\t\t\t\t| 'postgres'\n\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\ttype: 'memory'\n\t\t\t\t\t\t }\n\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\ttype: 'sqlite'\n\t\t\t\t\t\t\t\tfilename?: string\n\t\t\t\t\t\t }\n\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\ttype: 'postgres'\n\t\t\t\t\t\t\t\tconnectionString: string\n\t\t\t\t\t\t }\n\t\t\t }\n\t\twatch?:\n\t\t\t| boolean\n\t\t\t| {\n\t\t\t\t\tenabled?: boolean\n\t\t\t\t\tdebounceMs?: number\n\t\t\t }\n\t}\n}\n\nconst CONFIG_CANDIDATES = [\n\t'kora.config.ts',\n\t'kora.config.mts',\n\t'kora.config.cts',\n\t'kora.config.js',\n\t'kora.config.mjs',\n\t'kora.config.cjs',\n]\n\n/**\n * Loads `kora.config.*` from the project root if present.\n */\nexport async function loadKoraConfig(projectRoot: string): Promise<KoraConfigFile | null> {\n\tconst configPath = await findKoraConfigFile(projectRoot)\n\tif (!configPath) return null\n\n\tconst ext = extname(configPath)\n\tif (ext === '.ts' || ext === '.mts' || ext === '.cts') {\n\t\tconst loaded = await loadTypeScriptConfig(configPath, projectRoot)\n\t\treturn toConfigObject(loaded)\n\t}\n\n\tconst loaded = await import(pathToFileURL(configPath).href)\n\treturn toConfigObject(loaded)\n}\n\nasync function findKoraConfigFile(projectRoot: string): Promise<string | null> {\n\tfor (const file of CONFIG_CANDIDATES) {\n\t\tconst candidate = join(projectRoot, file)\n\t\ttry {\n\t\t\tawait access(candidate)\n\t\t\treturn candidate\n\t\t} catch {\n\t\t\t// continue\n\t\t}\n\t}\n\n\treturn null\n}\n\nasync function loadTypeScriptConfig(configPath: string, projectRoot: string): Promise<unknown> {\n\tif (!(await hasTsxInstalled(projectRoot))) {\n\t\tthrow new Error(\n\t\t\t`Found TypeScript config at ${configPath}, but \"tsx\" is not installed in this project. Install tsx or use kora.config.js.`,\n\t\t)\n\t}\n\n\t// Use process.execPath (node) + --import tsx to avoid .cmd shim issues on Windows.\n\t// Use dynamic import() with .then() since --eval may run as CJS (no top-level await).\n\tconst script =\n\t\t'const configPath = process.argv[process.argv.length - 1];' +\n\t\t\"import('node:url').then(u => import(u.pathToFileURL(configPath).href))\" +\n\t\t'.then(mod => { const v = mod.default ?? mod; process.stdout.write(JSON.stringify(v)) })' +\n\t\t'.catch(e => { process.stderr.write(String(e)); process.exit(1) })'\n\n\tconst output = await runCommand(\n\t\tprocess.execPath,\n\t\t['--import', 'tsx', '--eval', script, configPath],\n\t\tprojectRoot,\n\t)\n\n\ttry {\n\t\treturn JSON.parse(output)\n\t} catch {\n\t\tthrow new Error(`Failed to parse ${configPath} output as JSON.`)\n\t}\n}\n\nasync function runCommand(command: string, args: string[], cwd: string): Promise<string> {\n\treturn await new Promise<string>((resolve, reject) => {\n\t\tconst child = spawn(command, args, {\n\t\t\tcwd,\n\t\t\tstdio: ['ignore', 'pipe', 'pipe'],\n\t\t\tenv: process.env,\n\t\t})\n\n\t\tlet stdout = ''\n\t\tlet stderr = ''\n\n\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\tstdout += chunk.toString('utf-8')\n\t\t})\n\n\t\tchild.stderr?.on('data', (chunk: Buffer) => {\n\t\t\tstderr += chunk.toString('utf-8')\n\t\t})\n\n\t\tchild.on('error', (error) => {\n\t\t\treject(error)\n\t\t})\n\n\t\tchild.on('exit', (code) => {\n\t\t\tif (code === 0) {\n\t\t\t\tresolve(stdout.trim())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\treject(new Error(`Failed to load kora config (exit ${code ?? 'unknown'}): ${stderr.trim()}`))\n\t\t})\n\t})\n}\n\nfunction toConfigObject(mod: unknown): KoraConfigFile {\n\tif (typeof mod !== 'object' || mod === null) {\n\t\tthrow new Error('kora config must export an object.')\n\t}\n\n\tconst value = (mod as Record<string, unknown>).default ?? mod\n\tif (typeof value !== 'object' || value === null || Array.isArray(value)) {\n\t\tthrow new Error('kora config must export an object.')\n\t}\n\n\treturn value as KoraConfigFile\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { access } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { resolve } from 'node:path'\nimport { defineCommand } from 'citty'\nimport { DevServerError, InvalidProjectError } from '../../errors'\nimport {\n\tfindProjectRoot,\n\tfindSchemaFile,\n\thasTsxInstalled,\n\tresolveProjectBinaryEntryPoint,\n} from '../../utils/fs-helpers'\nimport { createLogger } from '../../utils/logger'\nimport { loadKoraConfig } from './kora-config'\nimport type { KoraConfigFile } from './kora-config'\nimport { ProcessManager } from './process-manager'\nimport type { ManagedProcessConfig } from './process-manager'\nimport { SchemaWatcher } from './schema-watcher'\n\ninterface ManagedSyncStoreConfig {\n\ttype: 'memory' | 'sqlite' | 'postgres'\n\tfilename?: string\n\tconnectionString?: string\n}\n\n/**\n * The `dev` command — starts the Kora development environment.\n */\nexport const devCommand = defineCommand({\n\tmeta: {\n\t\tname: 'dev',\n\t\tdescription: 'Start the Kora development environment',\n\t},\n\targs: {\n\t\tport: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Vite dev server port',\n\t\t},\n\t\t'sync-port': {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Kora sync server port',\n\t\t},\n\t\t'no-sync': {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Disable sync server startup',\n\t\t\tdefault: false,\n\t\t},\n\t\t'no-watch': {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Disable schema file watching',\n\t\t\tdefault: false,\n\t\t},\n\t},\n\tasync run({ args }) {\n\t\tconst logger = createLogger()\n\n\t\tconst projectRoot = await findProjectRoot()\n\t\tif (!projectRoot) {\n\t\t\tthrow new InvalidProjectError(process.cwd())\n\t\t}\n\n\t\tloadProjectEnv(projectRoot)\n\n\t\tconst config = await loadKoraConfig(projectRoot)\n\t\tconst vitePort = typeof args.port === 'string' ? args.port : String(config?.dev?.port ?? 5173)\n\t\tconst syncPortFromConfig =\n\t\t\ttypeof config?.dev?.sync === 'object' && typeof config.dev.sync.port === 'number'\n\t\t\t\t? config.dev.sync.port\n\t\t\t\t: 3001\n\t\tconst syncPort =\n\t\t\ttypeof args['sync-port'] === 'string' ? args['sync-port'] : String(syncPortFromConfig)\n\n\t\tconst configSyncEnabled =\n\t\t\tconfig?.dev?.sync === undefined ||\n\t\t\tconfig.dev.sync === true ||\n\t\t\t(typeof config.dev.sync === 'object' && config.dev.sync.enabled !== false)\n\n\t\tconst configWatchEnabled =\n\t\t\tconfig?.dev?.watch === undefined ||\n\t\t\tconfig.dev.watch === true ||\n\t\t\t(typeof config.dev.watch === 'object' && config.dev.watch.enabled !== false)\n\n\t\tconst watchDebounceMs =\n\t\t\ttypeof config?.dev?.watch === 'object' && typeof config.dev.watch.debounceMs === 'number'\n\t\t\t\t? config.dev.watch.debounceMs\n\t\t\t\t: 300\n\n\t\tconst viteEntryPoint = await resolveProjectBinaryEntryPoint(projectRoot, 'vite', 'vite')\n\t\tif (!viteEntryPoint) {\n\t\t\tthrow new DevServerError('vite', join(projectRoot, 'node_modules', '.bin', 'vite'))\n\t\t}\n\n\t\tconst syncServerFile = await findSyncServerFile(projectRoot)\n\t\tlet managedSyncStore = normalizeManagedSyncStore(config, projectRoot)\n\t\tconst postgresEnvRequested = isPostgresEnvRequested(config)\n\t\tconst syncAllowed = args['no-sync'] !== true && configSyncEnabled\n\t\tlet shouldStartSync = syncAllowed && (syncServerFile !== null || managedSyncStore !== null)\n\n\t\tlet hasTsx = false\n\t\tif (shouldStartSync && syncServerFile !== null) {\n\t\t\thasTsx = await hasTsxInstalled(projectRoot)\n\t\t\tif (!hasTsx) {\n\t\t\t\tlogger.warn('Sync server detected, but \"tsx\" is not installed. Skipping sync.')\n\t\t\t}\n\t\t}\n\n\t\tif (shouldStartSync && syncServerFile === null && managedSyncStore) {\n\t\t\tconst hasServerPackage = await fileExists(\n\t\t\t\tjoin(projectRoot, 'node_modules', '@korajs', 'server', 'package.json'),\n\t\t\t)\n\t\t\tif (!hasServerPackage) {\n\t\t\t\tlogger.warn(\n\t\t\t\t\t'Managed sync is configured, but @korajs/server is not installed. Install it or add server.ts.',\n\t\t\t\t)\n\t\t\t\tmanagedSyncStore = null\n\t\t\t\tshouldStartSync = syncAllowed && (syncServerFile !== null || managedSyncStore !== null)\n\t\t\t}\n\t\t}\n\n\t\tif (\n\t\t\tsyncAllowed &&\n\t\t\tsyncServerFile === null &&\n\t\t\tmanagedSyncStore === null &&\n\t\t\tpostgresEnvRequested\n\t\t) {\n\t\t\tlogger.warn(\n\t\t\t\t'Managed postgres sync requested but no connection string found. Set dev.sync.store.connectionString or DATABASE_URL.',\n\t\t\t)\n\t\t}\n\n\t\tlet configuredSchemaPath: string | null = null\n\t\tif (typeof config?.schema === 'string') {\n\t\t\tconst candidate = resolve(projectRoot, config.schema)\n\t\t\tif (await fileExists(candidate)) {\n\t\t\t\tconfiguredSchemaPath = candidate\n\t\t\t} else {\n\t\t\t\tlogger.warn(\n\t\t\t\t\t`Configured schema file not found: ${candidate}. Falling back to auto-detection.`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tconst schemaPath = configuredSchemaPath ?? (await findSchemaFile(projectRoot))\n\t\tconst watchEnabled = args['no-watch'] !== true && configWatchEnabled && schemaPath !== null\n\n\t\tconst processManager = new ProcessManager()\n\t\tlet schemaWatcher: SchemaWatcher | null = null\n\t\tlet shuttingDown = false\n\t\tlet resolveFinished: (() => void) | undefined\n\t\tconst finished = new Promise<void>((resolve) => {\n\t\t\tresolveFinished = resolve\n\t\t})\n\n\t\tconst onManagedProcessExit = () => {\n\t\t\tif (!processManager.hasRunning() && !shuttingDown) {\n\t\t\t\tresolveFinished?.()\n\t\t\t}\n\t\t}\n\n\t\tconst shutdown = async () => {\n\t\t\tif (shuttingDown) return\n\t\t\tshuttingDown = true\n\t\t\tschemaWatcher?.stop()\n\t\t\tawait processManager.shutdownAll()\n\t\t\tresolveFinished?.()\n\t\t}\n\n\t\tconst onSigInt = () => {\n\t\t\tvoid shutdown()\n\t\t}\n\t\tconst onSigTerm = () => {\n\t\t\tvoid shutdown()\n\t\t}\n\n\t\tprocess.on('SIGINT', onSigInt)\n\t\tprocess.on('SIGTERM', onSigTerm)\n\n\t\tlogger.banner()\n\t\tlogger.info('Starting development environment:')\n\t\tlogger.blank()\n\t\tlogger.step(` Vite dev server on port ${vitePort}`)\n\t\tif (shouldStartSync && hasTsx && syncServerFile) {\n\t\t\tlogger.step(` Sync server on port ${syncPort}`)\n\t\t} else if (shouldStartSync && syncServerFile === null && managedSyncStore !== null) {\n\t\t\tlogger.step(` Managed sync server on port ${syncPort} (${managedSyncStore.type})`)\n\t\t} else if (syncAllowed && syncServerFile === null) {\n\t\t\tlogger.step(' Sync server configured but no server.ts/server.js or managed store found')\n\t\t} else if (!syncAllowed) {\n\t\t\tlogger.step(' Sync server disabled via --no-sync')\n\t\t}\n\n\t\tif (watchEnabled && schemaPath) {\n\t\t\tlogger.step(` Schema watcher enabled (${schemaPath})`)\n\t\t} else if (args['no-watch'] === true) {\n\t\t\tlogger.step(' Schema watcher disabled via --no-watch')\n\t\t} else {\n\t\t\tlogger.step(' Schema watcher disabled (schema.ts not found)')\n\t\t}\n\t\tlogger.blank()\n\n\t\tlogger.step(\n\t\t\t' Kora DevTools overlay: Ctrl+Shift+K (Cmd+Shift+K on macOS) when devtools is enabled',\n\t\t)\n\n\t\tprocessManager.spawn({\n\t\t\tlabel: 'vite',\n\t\t\tcommand: process.execPath,\n\t\t\targs: [viteEntryPoint, '--port', String(vitePort)],\n\t\t\tcwd: projectRoot,\n\t\t\tenv: {\n\t\t\t\tKORA_DEV: '1',\n\t\t\t},\n\t\t\tonExit: onManagedProcessExit,\n\t\t})\n\n\t\tconst syncProcessConfig: ManagedProcessConfig | null =\n\t\t\tshouldStartSync && hasTsx && syncServerFile\n\t\t\t\t? {\n\t\t\t\t\t\tlabel: 'sync',\n\t\t\t\t\t\tcommand: process.execPath,\n\t\t\t\t\t\targs: ['--import', 'tsx', syncServerFile],\n\t\t\t\t\t\tcwd: projectRoot,\n\t\t\t\t\t\tenv: {\n\t\t\t\t\t\t\tPORT: String(syncPort),\n\t\t\t\t\t\t\tKORA_SYNC_PORT: String(syncPort),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tonExit: onManagedProcessExit,\n\t\t\t\t\t}\n\t\t\t\t: shouldStartSync && syncServerFile === null && managedSyncStore !== null\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tlabel: 'sync',\n\t\t\t\t\t\t\tcommand: process.execPath,\n\t\t\t\t\t\t\targs: ['--input-type=module', '--eval', MANAGED_SYNC_BOOTSTRAP_SCRIPT],\n\t\t\t\t\t\t\tcwd: projectRoot,\n\t\t\t\t\t\t\tenv: {\n\t\t\t\t\t\t\t\tKORA_DEV_SYNC_CONFIG: JSON.stringify({\n\t\t\t\t\t\t\t\t\tport: Number(syncPort),\n\t\t\t\t\t\t\t\t\tstore: managedSyncStore,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tonExit: onManagedProcessExit,\n\t\t\t\t\t\t}\n\t\t\t\t\t: null\n\n\t\tif (syncProcessConfig) {\n\t\t\tprocessManager.spawn(syncProcessConfig)\n\t\t}\n\n\t\tif (watchEnabled && schemaPath) {\n\t\t\tschemaWatcher = new SchemaWatcher({\n\t\t\t\tschemaPath,\n\t\t\t\tprojectRoot,\n\t\t\t\tdebounceMs: watchDebounceMs,\n\t\t\t\tonRegenerate: () => {\n\t\t\t\t\tlogger.success('Regenerated types from schema changes')\n\t\t\t\t},\n\t\t\t\tonSchemaVersionChange: ({ previous, next }) => {\n\t\t\t\t\tif (!syncProcessConfig) {\n\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t`Schema version changed from ${previous} to ${next}; restart your sync server before clients can sync.`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tlogger.warn(`Schema version changed from ${previous} to ${next}; restarting sync server.`)\n\t\t\t\t\tvoid processManager.restart(syncProcessConfig)\n\t\t\t\t},\n\t\t\t\tonError: (error) => {\n\t\t\t\t\tlogger.error(`Schema watcher error: ${error.message}`)\n\t\t\t\t},\n\t\t\t})\n\t\t\tschemaWatcher.start()\n\t\t}\n\n\t\tawait finished\n\t\tprocess.off('SIGINT', onSigInt)\n\t\tprocess.off('SIGTERM', onSigTerm)\n\t},\n})\n\nasync function findSyncServerFile(projectRoot: string): Promise<string | null> {\n\tconst candidates = [join(projectRoot, 'server.ts'), join(projectRoot, 'server.js')]\n\n\tfor (const candidate of candidates) {\n\t\ttry {\n\t\t\tawait access(candidate)\n\t\t\treturn candidate\n\t\t} catch {\n\t\t\t// continue\n\t\t}\n\t}\n\n\treturn null\n}\n\nasync function fileExists(path: string): Promise<boolean> {\n\ttry {\n\t\tawait access(path)\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n\nfunction loadProjectEnv(projectRoot: string, mode = 'development'): void {\n\tconst files = ['.env', '.env.local', `.env.${mode}`, `.env.${mode}.local`]\n\tconst existingKeys = new Set(Object.keys(process.env))\n\tfor (const file of files) {\n\t\tconst path = join(projectRoot, file)\n\t\tif (!existsSync(path)) continue\n\t\tconst parsed = parseEnvFile(readFileSync(path, 'utf8'))\n\t\tfor (const [key, value] of Object.entries(parsed)) {\n\t\t\tif (!existingKeys.has(key)) {\n\t\t\t\tprocess.env[key] = value\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction parseEnvFile(contents: string): Record<string, string> {\n\tconst env: Record<string, string> = {}\n\n\tfor (const rawLine of contents.split(/\\r?\\n/)) {\n\t\tconst line = rawLine.trim()\n\t\tif (!line || line.startsWith('#')) continue\n\n\t\tconst normalized = line.startsWith('export ') ? line.slice('export '.length).trim() : line\n\t\tconst equalsIndex = normalized.indexOf('=')\n\t\tif (equalsIndex <= 0) continue\n\n\t\tconst key = normalized.slice(0, equalsIndex).trim()\n\t\tif (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue\n\n\t\tenv[key] = parseEnvValue(normalized.slice(equalsIndex + 1).trim())\n\t}\n\n\treturn env\n}\n\nfunction parseEnvValue(value: string): string {\n\tconst quote = value[0]\n\tif ((quote === '\"' || quote === \"'\") && value[value.length - 1] === quote) {\n\t\tconst inner = value.slice(1, -1)\n\t\treturn quote === '\"' ? inner.replace(/\\\\n/g, '\\n').replace(/\\\\r/g, '\\r') : inner\n\t}\n\n\tconst commentIndex = value.search(/\\s#/)\n\treturn (commentIndex >= 0 ? value.slice(0, commentIndex) : value).trim()\n}\n\nfunction normalizeManagedSyncStore(\n\tconfig: KoraConfigFile | null,\n\tprojectRoot: string,\n): ManagedSyncStoreConfig | null {\n\tconst sync = config?.dev?.sync\n\tif (typeof sync !== 'object' || sync === null) return null\n\n\tconst store = sync.store\n\tif (store === undefined) return { type: 'memory' }\n\n\tif (store === 'memory') return { type: 'memory' }\n\tif (store === 'sqlite') return { type: 'sqlite', filename: join(projectRoot, 'kora-sync.db') }\n\tif (store === 'postgres') {\n\t\tconst connectionString = process.env.DATABASE_URL\n\t\tif (!connectionString) return null\n\t\treturn { type: 'postgres', connectionString }\n\t}\n\n\tif (typeof store === 'object' && store !== null) {\n\t\tif (store.type === 'memory') return { type: 'memory' }\n\t\tif (store.type === 'sqlite') {\n\t\t\tconst filename =\n\t\t\t\ttypeof store.filename === 'string' && store.filename.length > 0\n\t\t\t\t\t? resolve(projectRoot, store.filename)\n\t\t\t\t\t: join(projectRoot, 'kora-sync.db')\n\t\t\treturn { type: 'sqlite', filename }\n\t\t}\n\t\tif (store.type === 'postgres' && typeof store.connectionString === 'string') {\n\t\t\treturn { type: 'postgres', connectionString: store.connectionString }\n\t\t}\n\t}\n\n\treturn null\n}\n\nfunction isPostgresEnvRequested(config: KoraConfigFile | null): boolean {\n\tconst sync = config?.dev?.sync\n\tif (typeof sync !== 'object' || sync === null) return false\n\tif (sync.store === 'postgres') return true\n\tif (typeof sync.store === 'object' && sync.store !== null && sync.store.type === 'postgres')\n\t\treturn true\n\treturn false\n}\n\nconst MANAGED_SYNC_BOOTSTRAP_SCRIPT = `\nconst config = JSON.parse(process.env.KORA_DEV_SYNC_CONFIG ?? '{}');\nconst {\n createKoraServer,\n MemoryServerStore,\n createSqliteServerStore,\n createPostgresServerStore,\n} = await import('@korajs/server');\nconst storeConfig = config.store ?? { type: 'memory' };\nlet store;\nif (storeConfig.type === 'memory') {\n store = new MemoryServerStore();\n} else if (storeConfig.type === 'sqlite') {\n const filename = typeof storeConfig.filename === 'string' && storeConfig.filename.length > 0\n ? storeConfig.filename\n : './kora-sync.db';\n store = createSqliteServerStore({ filename });\n} else if (storeConfig.type === 'postgres') {\n if (typeof storeConfig.connectionString !== 'string' || storeConfig.connectionString.length === 0) {\n throw new Error('Managed postgres sync requires a connectionString');\n }\n store = await createPostgresServerStore({\n connectionString: storeConfig.connectionString,\n });\n} else {\n throw new Error('Unsupported managed sync store type: ' + String(storeConfig.type));\n}\nconst server = createKoraServer({ store, port: Number(config.port ?? 3001) });\nconst shutdown = async () => {\n try {\n await server.stop();\n } catch {\n }\n process.exit(0);\n};\nprocess.on('SIGINT', () => {\n void shutdown();\n});\nprocess.on('SIGTERM', () => {\n void shutdown();\n});\nawait server.start();\nprocess.stdout.write('Managed sync server running on ws://localhost:' + String(config.port ?? 3001) + '\\\\n');\nawait new Promise(() => {});\n`\n","import { spawn as spawnChild } from 'node:child_process'\nimport type { ChildProcess, SpawnOptions } from 'node:child_process'\n\nexport interface ManagedProcessConfig {\n\tlabel: string\n\tcommand: string\n\targs: string[]\n\tcwd: string\n\tenv?: Record<string, string>\n\tonExit?: (code: number | null, signal: NodeJS.Signals | null) => void\n}\n\ninterface RunningProcess {\n\tchild: ChildProcess\n\texitPromise: Promise<void>\n\tstdoutBuffer: string\n\tstderrBuffer: string\n}\n\n/**\n * Manages long-running child processes for the dev command.\n */\nexport class ProcessManager {\n\tprivate readonly processes = new Map<string, RunningProcess>()\n\n\tspawn(config: ManagedProcessConfig): void {\n\t\tthis.processes.get(config.label)?.child.kill('SIGTERM')\n\t\tconst options: SpawnOptions = {\n\t\t\tcwd: config.cwd,\n\t\t\tenv: { ...process.env, ...config.env },\n\t\t\tstdio: ['ignore', 'pipe', 'pipe'],\n\t\t}\n\n\t\tconst child = spawnChild(config.command, config.args, options)\n\t\tlet resolveExit: (() => void) | undefined\n\n\t\tconst runningProcess: RunningProcess = {\n\t\t\tchild,\n\t\t\texitPromise: new Promise<void>((resolve) => {\n\t\t\t\tresolveExit = resolve\n\t\t\t}),\n\t\t\tstdoutBuffer: '',\n\t\t\tstderrBuffer: '',\n\t\t}\n\n\t\tthis.processes.set(config.label, runningProcess)\n\n\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\trunningProcess.stdoutBuffer = this.writeChunk(\n\t\t\t\tconfig.label,\n\t\t\t\trunningProcess.stdoutBuffer,\n\t\t\t\tchunk,\n\t\t\t\tfalse,\n\t\t\t)\n\t\t})\n\n\t\tchild.stderr?.on('data', (chunk: Buffer) => {\n\t\t\trunningProcess.stderrBuffer = this.writeChunk(\n\t\t\t\tconfig.label,\n\t\t\t\trunningProcess.stderrBuffer,\n\t\t\t\tchunk,\n\t\t\t\ttrue,\n\t\t\t)\n\t\t})\n\n\t\tchild.on('exit', (code, signal) => {\n\t\t\tthis.flushBuffer(config.label, runningProcess.stdoutBuffer, false)\n\t\t\tthis.flushBuffer(config.label, runningProcess.stderrBuffer, true)\n\t\t\tthis.processes.delete(config.label)\n\t\t\tconfig.onExit?.(code, signal)\n\t\t\tresolveExit?.()\n\t\t})\n\t}\n\n\thasRunning(): boolean {\n\t\treturn this.processes.size > 0\n\t}\n\n\tasync restart(config: ManagedProcessConfig): Promise<void> {\n\t\tawait this.stop(config.label)\n\t\tthis.spawn(config)\n\t}\n\n\tasync stop(label: string): Promise<void> {\n\t\tconst running = this.processes.get(label)\n\t\tif (!running) return\n\t\trunning.child.kill('SIGTERM')\n\t\tawait Promise.race([running.exitPromise, delay(5000)])\n\t\tconst remaining = this.processes.get(label)\n\t\tif (!remaining) return\n\t\tremaining.child.kill('SIGKILL')\n\t\tawait remaining.exitPromise\n\t}\n\n\tasync shutdownAll(): Promise<void> {\n\t\tconst running = Array.from(this.processes.values())\n\t\tif (running.length === 0) return\n\n\t\tfor (const processEntry of running) {\n\t\t\tprocessEntry.child.kill('SIGTERM')\n\t\t}\n\n\t\tawait Promise.race([Promise.all(running.map((entry) => entry.exitPromise)), delay(5000)])\n\n\t\tconst remaining = Array.from(this.processes.values())\n\t\tif (remaining.length === 0) return\n\n\t\tfor (const processEntry of remaining) {\n\t\t\tprocessEntry.child.kill('SIGKILL')\n\t\t}\n\n\t\tawait Promise.all(remaining.map((entry) => entry.exitPromise))\n\t}\n\n\tprivate writeChunk(label: string, buffer: string, chunk: Buffer, isError: boolean): string {\n\t\tconst combined = `${buffer}${chunk.toString('utf-8')}`\n\t\tconst lines = combined.split(/\\r?\\n/)\n\t\tconst remaining = lines.pop() ?? ''\n\n\t\tfor (const line of lines) {\n\t\t\tthis.writeLine(label, line, isError)\n\t\t}\n\n\t\treturn remaining\n\t}\n\n\tprivate flushBuffer(label: string, buffer: string, isError: boolean): void {\n\t\tif (!buffer) return\n\t\tthis.writeLine(label, buffer, isError)\n\t}\n\n\tprivate writeLine(label: string, line: string, isError: boolean): void {\n\t\tconst stream = isError ? process.stderr : process.stdout\n\t\tstream.write(`[${label}] ${line}\\n`)\n\t}\n}\n\nfunction delay(ms: number): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tsetTimeout(resolve, ms)\n\t})\n}\n","import { spawn } from 'node:child_process'\nimport { watch } from 'node:fs'\nimport type { FSWatcher } from 'node:fs'\nimport { join } from 'node:path'\nimport { hasTsxInstalled } from '../../utils/fs-helpers'\nimport { loadSchemaDefinition } from '../migrate/schema-loader'\n\nexport interface SchemaWatcherConfig {\n\tschemaPath: string\n\tprojectRoot: string\n\tdebounceMs?: number\n\tonRegenerate?: () => void\n\tonSchemaVersionChange?: (change: { previous: number; next: number }) => void\n\tonError?: (error: Error) => void\n}\n\n/**\n * Watches a schema file and regenerates types when it changes.\n */\nexport class SchemaWatcher {\n\tprivate readonly debounceMs: number\n\tprivate watcher: FSWatcher | null = null\n\tprivate debounceTimer: NodeJS.Timeout | null = null\n\tprivate schemaVersion: number | null = null\n\n\tconstructor(private readonly config: SchemaWatcherConfig) {\n\t\tthis.debounceMs = config.debounceMs ?? 300\n\t}\n\n\tstart(): void {\n\t\tif (this.watcher) return\n\n\t\tthis.watcher = watch(this.config.schemaPath, () => {\n\t\t\tthis.scheduleRegeneration()\n\t\t})\n\n\t\tthis.watcher.on('error', (error) => {\n\t\t\tthis.config.onError?.(toError(error))\n\t\t})\n\n\t\tvoid this.refreshSchemaVersion().catch((error) => {\n\t\t\tthis.config.onError?.(toError(error))\n\t\t})\n\t}\n\n\tstop(): void {\n\t\tif (this.debounceTimer) {\n\t\t\tclearTimeout(this.debounceTimer)\n\t\t\tthis.debounceTimer = null\n\t\t}\n\n\t\tthis.watcher?.close()\n\t\tthis.watcher = null\n\t}\n\n\tasync regenerate(): Promise<void> {\n\t\t// Use process.execPath (node) + --import tsx to run kora generate,\n\t\t// avoiding .cmd shim issues on Windows with paths containing spaces.\n\t\tconst koraBinJs = join(\n\t\t\tthis.config.projectRoot,\n\t\t\t'node_modules',\n\t\t\t'@korajs',\n\t\t\t'cli',\n\t\t\t'dist',\n\t\t\t'bin.js',\n\t\t)\n\t\tconst hasTsx = await hasTsxInstalled(this.config.projectRoot)\n\n\t\tconst command = process.execPath\n\t\tconst args = hasTsx\n\t\t\t? ['--import', 'tsx', koraBinJs, 'generate', 'types', '--schema', this.config.schemaPath]\n\t\t\t: [koraBinJs, 'generate', 'types', '--schema', this.config.schemaPath]\n\n\t\tawait spawnCommand(command, args, this.config.projectRoot)\n\t\tthis.config.onRegenerate?.()\n\t\tawait this.refreshSchemaVersion()\n\t}\n\n\tprivate async refreshSchemaVersion(): Promise<void> {\n\t\tconst schema = await loadSchemaDefinition(this.config.schemaPath, this.config.projectRoot)\n\t\tconst previous = this.schemaVersion\n\t\tthis.schemaVersion = schema.version\n\t\tif (previous !== null && previous !== schema.version) {\n\t\t\tthis.config.onSchemaVersionChange?.({ previous, next: schema.version })\n\t\t}\n\t}\n\n\tprivate scheduleRegeneration(): void {\n\t\tif (this.debounceTimer) {\n\t\t\tclearTimeout(this.debounceTimer)\n\t\t}\n\n\t\tthis.debounceTimer = setTimeout(() => {\n\t\t\tthis.debounceTimer = null\n\t\t\tvoid this.regenerate().catch((error) => {\n\t\t\t\tthis.config.onError?.(toError(error))\n\t\t\t})\n\t\t}, this.debounceMs)\n\t}\n}\n\nasync function spawnCommand(command: string, args: string[], cwd: string): Promise<void> {\n\tawait new Promise<void>((resolve, reject) => {\n\t\tconst child = spawn(command, args, {\n\t\t\tcwd,\n\t\t\tstdio: ['ignore', 'pipe', 'pipe'],\n\t\t\tenv: process.env,\n\t\t})\n\n\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\twritePrefixedLines(chunk, false)\n\t\t})\n\n\t\tchild.stderr?.on('data', (chunk: Buffer) => {\n\t\t\twritePrefixedLines(chunk, true)\n\t\t})\n\n\t\tchild.on('error', (error) => {\n\t\t\treject(error)\n\t\t})\n\n\t\tchild.on('exit', (code) => {\n\t\t\tif (code === 0) {\n\t\t\t\tresolve()\n\t\t\t\treturn\n\t\t\t}\n\t\t\treject(new Error(`Type generation exited with code ${code ?? 'unknown'}.`))\n\t\t})\n\t})\n}\n\nfunction writePrefixedLines(chunk: Buffer, isError: boolean): void {\n\tconst text = chunk.toString('utf-8')\n\tconst lines = text.split(/\\r?\\n/).filter((line) => line.length > 0)\n\tconst stream = isError ? process.stderr : process.stdout\n\n\tfor (const line of lines) {\n\t\tstream.write(`[kora] ${line}\\n`)\n\t}\n}\n\nfunction toError(error: unknown): Error {\n\tif (error instanceof Error) return error\n\treturn new Error(String(error))\n}\n","import { defineCommand } from 'citty'\nimport { InvalidProjectError } from '../../errors'\nimport { findProjectRoot } from '../../utils/fs-helpers'\nimport { createLogger } from '../../utils/logger'\nimport { doctorHasFailures, runDoctorChecks } from './doctor-checks'\n\n/**\n * Diagnose common Kora project setup issues (schema, worker, sync, versions).\n */\nexport const doctorCommand = defineCommand({\n\tmeta: {\n\t\tname: 'doctor',\n\t\tdescription: 'Check Kora project setup (schema, worker, sync server, versions)',\n\t},\n\targs: {\n\t\turl: {\n\t\t\ttype: 'string',\n\t\t\tdescription:\n\t\t\t\t'Sync server HTTP base URL for status probe (default: from .env or localhost:3001)',\n\t\t},\n\t\t'skip-network': {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Skip sync server and schema version network checks',\n\t\t\tdefault: false,\n\t\t},\n\t},\n\tasync run({ args }) {\n\t\tconst logger = createLogger()\n\t\tconst projectRoot = await findProjectRoot()\n\t\tif (!projectRoot) {\n\t\t\tthrow new InvalidProjectError(process.cwd())\n\t\t}\n\n\t\tconst syncHttpUrl = typeof args.url === 'string' ? args.url : undefined\n\t\tconst skipNetwork = args['skip-network'] === true\n\n\t\tlogger.banner()\n\t\tlogger.info(`Checking project at ${projectRoot}`)\n\t\tlogger.blank()\n\n\t\tconst results = await runDoctorChecks({\n\t\t\tprojectRoot,\n\t\t\tsyncHttpUrl,\n\t\t\tskipNetwork,\n\t\t})\n\n\t\tfor (const check of results) {\n\t\t\tconst prefix =\n\t\t\t\tcheck.status === 'pass'\n\t\t\t\t\t? 'success'\n\t\t\t\t\t: check.status === 'warn'\n\t\t\t\t\t\t? 'warn'\n\t\t\t\t\t\t: check.status === 'fail'\n\t\t\t\t\t\t\t? 'error'\n\t\t\t\t\t\t\t: 'step'\n\t\t\tlogger[prefix](`${check.title}: ${check.message}`)\n\t\t\tif (check.fix && check.status !== 'pass' && check.status !== 'skip') {\n\t\t\t\tlogger.step(` Fix: ${check.fix}`)\n\t\t\t}\n\t\t}\n\n\t\tlogger.blank()\n\t\tif (doctorHasFailures(results)) {\n\t\t\tlogger.error('Doctor found blocking issues.')\n\t\t\tprocess.exitCode = 1\n\t\t\treturn\n\t\t}\n\n\t\tconst warnings = results.filter((r) => r.status === 'warn').length\n\t\tif (warnings > 0) {\n\t\t\tlogger.warn(`Doctor finished with ${warnings} warning(s).`)\n\t\t} else {\n\t\t\tlogger.success('All checks passed.')\n\t\t}\n\t},\n})\n","import { access, readFile } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport type { SchemaDefinition } from '@korajs/core'\nimport { findSchemaFile } from '../../utils/fs-helpers'\nimport { loadKoraConfig } from '../dev/kora-config'\nimport { loadSchemaDefinition } from '../migrate/schema-loader'\n\nexport type DoctorCheckStatus = 'pass' | 'warn' | 'fail' | 'skip'\n\nexport interface DoctorCheckResult {\n\tid: string\n\ttitle: string\n\tstatus: DoctorCheckStatus\n\tmessage: string\n\tfix?: string\n}\n\nexport interface DoctorRunOptions {\n\tprojectRoot: string\n\t/** HTTP base URL for sync status probe (e.g. http://localhost:3001) */\n\tsyncHttpUrl?: string\n\t/** Skip network checks */\n\tskipNetwork?: boolean\n}\n\nconst STATUS_ENDPOINT = '/__kora/status'\n\n/**\n * Run all static and optional network diagnostics for a Kora project.\n */\nexport async function runDoctorChecks(options: DoctorRunOptions): Promise<DoctorCheckResult[]> {\n\tconst { projectRoot } = options\n\tconst results: DoctorCheckResult[] = []\n\n\tresults.push({\n\t\tid: 'project-root',\n\t\ttitle: 'Project root',\n\t\tstatus: 'pass',\n\t\tmessage: projectRoot,\n\t})\n\n\tconst config = await loadKoraConfig(projectRoot)\n\tif (!config) {\n\t\tresults.push({\n\t\t\tid: 'kora-config',\n\t\t\ttitle: 'kora.config',\n\t\t\tstatus: 'warn',\n\t\t\tmessage: 'No kora.config.* file found.',\n\t\t\tfix: 'Add kora.config.ts with schema path and dev settings (see create-kora-app templates).',\n\t\t})\n\t} else {\n\t\tresults.push({\n\t\t\tid: 'kora-config',\n\t\t\ttitle: 'kora.config',\n\t\t\tstatus: 'pass',\n\t\t\tmessage: 'Configuration file loaded.',\n\t\t})\n\t}\n\n\tconst schemaPath = await resolveSchemaPath(projectRoot, config?.schema)\n\tif (!schemaPath) {\n\t\tresults.push({\n\t\t\tid: 'schema',\n\t\t\ttitle: 'Schema',\n\t\t\tstatus: 'fail',\n\t\t\tmessage: 'Could not find schema.ts in src/ or project root.',\n\t\t\tfix: 'Add src/schema.ts or set schema in kora.config.ts.',\n\t\t})\n\t} else {\n\t\ttry {\n\t\t\tconst schema = await loadSchemaDefinition(schemaPath, projectRoot)\n\t\t\tresults.push({\n\t\t\t\tid: 'schema',\n\t\t\t\ttitle: 'Schema',\n\t\t\t\tstatus: 'pass',\n\t\t\t\tmessage: `Loaded schema v${schema.version} (${Object.keys(schema.collections).length} collection(s)).`,\n\t\t\t})\n\n\t\t\tconst workerCheck = await checkWorkerFile(projectRoot)\n\t\t\tresults.push(workerCheck)\n\n\t\t\tconst depsCheck = await checkDependencies(projectRoot)\n\t\t\tresults.push(depsCheck)\n\n\t\t\tresults.push(opfsBrowserNote())\n\n\t\t\tif (!options.skipNetwork) {\n\t\t\t\tconst syncUrl = options.syncHttpUrl ?? (await resolveSyncHttpUrl(projectRoot, config))\n\t\t\t\tconst syncChecks = await checkSyncServer(syncUrl, schema)\n\t\t\t\tresults.push(...syncChecks)\n\t\t\t} else {\n\t\t\t\tresults.push({\n\t\t\t\t\tid: 'sync-server',\n\t\t\t\t\ttitle: 'Sync server',\n\t\t\t\t\tstatus: 'skip',\n\t\t\t\t\tmessage: 'Network checks skipped.',\n\t\t\t\t})\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tresults.push({\n\t\t\t\tid: 'schema',\n\t\t\t\ttitle: 'Schema',\n\t\t\t\tstatus: 'fail',\n\t\t\t\tmessage: `Failed to load schema: ${message}`,\n\t\t\t\tfix: 'Ensure the schema exports defineSchema() as default and TypeScript can be evaluated (install tsx).',\n\t\t\t})\n\t\t}\n\t}\n\n\treturn results\n}\n\nasync function resolveSchemaPath(\n\tprojectRoot: string,\n\tconfigSchema?: string,\n): Promise<string | null> {\n\tif (typeof configSchema === 'string') {\n\t\tconst resolved = resolve(projectRoot, configSchema)\n\t\ttry {\n\t\t\tawait access(resolved)\n\t\t\treturn resolved\n\t\t} catch {\n\t\t\t// fall through to search\n\t\t}\n\t}\n\treturn findSchemaFile(projectRoot)\n}\n\nasync function checkWorkerFile(projectRoot: string): Promise<DoctorCheckResult> {\n\tconst candidates = [\n\t\tjoin(projectRoot, 'src', 'kora-worker.ts'),\n\t\tjoin(projectRoot, 'src', 'kora-worker.js'),\n\t]\n\n\tfor (const path of candidates) {\n\t\ttry {\n\t\t\tawait access(path)\n\t\t\treturn {\n\t\t\t\tid: 'worker',\n\t\t\t\ttitle: 'SQLite WASM worker',\n\t\t\t\tstatus: 'pass',\n\t\t\t\tmessage: `Found ${path.replace(projectRoot, '.')}.`,\n\t\t\t}\n\t\t} catch {\n\t\t\t// try next\n\t\t}\n\t}\n\n\treturn {\n\t\tid: 'worker',\n\t\ttitle: 'SQLite WASM worker',\n\t\tstatus: 'warn',\n\t\tmessage: 'No src/kora-worker.ts found.',\n\t\tfix: 'Add kora-worker.ts and pass store.workerUrl from Vite (?worker&url) in createApp().',\n\t}\n}\n\nasync function checkDependencies(projectRoot: string): Promise<DoctorCheckResult> {\n\ttry {\n\t\tconst raw = await readFile(join(projectRoot, 'package.json'), 'utf-8')\n\t\tconst pkg = JSON.parse(raw) as {\n\t\t\tdependencies?: Record<string, string>\n\t\t\tdevDependencies?: Record<string, string>\n\t\t}\n\t\tconst deps = { ...pkg.dependencies, ...pkg.devDependencies }\n\t\tconst hasKora = Boolean(deps.korajs || deps.kora)\n\t\tconst hasStore = Boolean(deps['@korajs/store'])\n\t\tif (hasKora || hasStore) {\n\t\t\treturn {\n\t\t\t\tid: 'dependencies',\n\t\t\t\ttitle: 'Dependencies',\n\t\t\t\tstatus: 'pass',\n\t\t\t\tmessage: hasKora\n\t\t\t\t\t? 'korajs is listed in package.json.'\n\t\t\t\t\t: '@korajs/store is listed in package.json.',\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tid: 'dependencies',\n\t\t\ttitle: 'Dependencies',\n\t\t\tstatus: 'fail',\n\t\t\tmessage: 'No korajs or @korajs/store dependency found.',\n\t\t\tfix: 'Run pnpm add korajs @korajs/react (or your package manager equivalent).',\n\t\t}\n\t} catch {\n\t\treturn {\n\t\t\tid: 'dependencies',\n\t\t\ttitle: 'Dependencies',\n\t\t\tstatus: 'fail',\n\t\t\tmessage: 'Could not read package.json.',\n\t\t\tfix: 'Run this command from a Kora app directory with a valid package.json.',\n\t\t}\n\t}\n}\n\nfunction opfsBrowserNote(): DoctorCheckResult {\n\treturn {\n\t\tid: 'opfs',\n\t\ttitle: 'OPFS persistence',\n\t\tstatus: 'skip',\n\t\tmessage:\n\t\t\t'OPFS availability is checked in the browser at runtime. Open the app and confirm no IndexedDB fallback warning in the console.',\n\t\tfix: 'Use a Chromium-based browser with storage access; avoid private mode if persistence fails.',\n\t}\n}\n\nasync function resolveSyncHttpUrl(\n\tprojectRoot: string,\n\tconfig: Awaited<ReturnType<typeof loadKoraConfig>>,\n): Promise<string> {\n\tconst envUrl = await readEnvSyncUrl(projectRoot)\n\tif (envUrl) {\n\t\treturn toSyncStatusHttpBase(envUrl)\n\t}\n\n\tconst syncPort =\n\t\ttypeof config?.dev?.sync === 'object' && typeof config.dev.sync.port === 'number'\n\t\t\t? config.dev.sync.port\n\t\t\t: 3001\n\n\treturn `http://localhost:${syncPort}`\n}\n\nasync function readEnvSyncUrl(projectRoot: string): Promise<string | null> {\n\tfor (const file of ['.env', '.env.local']) {\n\t\tconst path = join(projectRoot, file)\n\t\ttry {\n\t\t\tconst content = await readFile(path, 'utf-8')\n\t\t\tfor (const line of content.split('\\n')) {\n\t\t\t\tconst trimmed = line.trim()\n\t\t\t\tif (!trimmed || trimmed.startsWith('#')) continue\n\t\t\t\tconst match = trimmed.match(/^VITE_SYNC_URL=(.+)$/)\n\t\t\t\tif (match?.[1]) {\n\t\t\t\t\treturn match[1].trim().replace(/^[\"']|[\"']$/g, '')\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// continue\n\t\t}\n\t}\n\treturn null\n}\n\n/** Converts a WebSocket sync URL to an HTTP base for {@link STATUS_ENDPOINT}. */\nexport function toSyncStatusHttpBase(url: string): string {\n\ttry {\n\t\tconst parsed = new URL(url)\n\t\tif (parsed.protocol === 'ws:') {\n\t\t\tparsed.protocol = 'http:'\n\t\t} else if (parsed.protocol === 'wss:') {\n\t\t\tparsed.protocol = 'https:'\n\t\t}\n\t\tparsed.pathname = ''\n\t\tparsed.search = ''\n\t\tparsed.hash = ''\n\t\treturn parsed.toString().replace(/\\/$/, '')\n\t} catch {\n\t\treturn 'http://localhost:3001'\n\t}\n}\n\ninterface ServerStatusResponse {\n\tschemaVersion: number\n\trunning: boolean\n\tversion: string\n}\n\nasync function checkSyncServer(\n\thttpBase: string,\n\tschema: SchemaDefinition,\n): Promise<DoctorCheckResult[]> {\n\tconst statusUrl = `${httpBase.replace(/\\/$/, '')}${STATUS_ENDPOINT}`\n\n\ttry {\n\t\tconst response = await fetch(statusUrl, {\n\t\t\tsignal: AbortSignal.timeout(5000),\n\t\t})\n\t\tif (!response.ok) {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tid: 'sync-server',\n\t\t\t\t\ttitle: 'Sync server',\n\t\t\t\t\tstatus: 'fail',\n\t\t\t\t\tmessage: `GET ${statusUrl} returned ${response.status}.`,\n\t\t\t\t\tfix: 'Start the sync server with `kora dev` or `pnpm run dev` in a sync template.',\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\n\t\tconst body = (await response.json()) as ServerStatusResponse\n\t\tconst results: DoctorCheckResult[] = [\n\t\t\t{\n\t\t\t\tid: 'sync-server',\n\t\t\t\ttitle: 'Sync server',\n\t\t\t\tstatus: 'pass',\n\t\t\t\tmessage: `Reachable at ${statusUrl} (server v${body.version ?? 'unknown'}).`,\n\t\t\t},\n\t\t]\n\n\t\tif (typeof body.schemaVersion === 'number' && body.schemaVersion !== schema.version) {\n\t\t\tresults.push({\n\t\t\t\tid: 'schema-version',\n\t\t\t\ttitle: 'Schema version',\n\t\t\t\tstatus: 'warn',\n\t\t\t\tmessage: `Client schema v${schema.version} differs from server schema v${body.schemaVersion}.`,\n\t\t\t\tfix: 'Run migrations on the server and client, or align schema.version before syncing.',\n\t\t\t})\n\t\t} else {\n\t\t\tresults.push({\n\t\t\t\tid: 'schema-version',\n\t\t\t\ttitle: 'Schema version',\n\t\t\t\tstatus: 'pass',\n\t\t\t\tmessage: `Client and server both use schema v${schema.version}.`,\n\t\t\t})\n\t\t}\n\n\t\treturn results\n\t} catch (error) {\n\t\tconst detail = error instanceof Error ? error.message : String(error)\n\t\treturn [\n\t\t\t{\n\t\t\t\tid: 'sync-server',\n\t\t\t\ttitle: 'Sync server',\n\t\t\t\tstatus: 'warn',\n\t\t\t\tmessage: `Could not reach ${statusUrl}: ${detail}`,\n\t\t\t\tfix: 'Start the sync server, or pass --skip-network for local-only checks.',\n\t\t\t},\n\t\t]\n\t}\n}\n\n/**\n * True when any check failed (doctor should exit non-zero).\n */\nexport function doctorHasFailures(results: DoctorCheckResult[]): boolean {\n\treturn results.some((r) => r.status === 'fail')\n}\n","import { mkdir, writeFile } from 'node:fs/promises'\nimport { dirname, resolve } from 'node:path'\nimport type { SchemaDefinition } from '@korajs/core'\nimport { defineCommand } from 'citty'\nimport { InvalidProjectError, SchemaNotFoundError } from '../../errors'\nimport { findProjectRoot, findSchemaFile } from '../../utils/fs-helpers'\nimport { createLogger } from '../../utils/logger'\nimport { loadSchemaDefinition } from '../migrate/schema-loader'\nimport { generateCollectionHooks } from './hook-generator'\nimport { generateTypes } from './type-generator'\n\n/**\n * The `generate` command with `types` subcommand.\n * Reads a schema file and generates TypeScript interfaces.\n */\nexport const generateCommand = defineCommand({\n\tmeta: {\n\t\tname: 'generate',\n\t\tdescription: 'Generate code from your Kora schema',\n\t},\n\tsubCommands: {\n\t\ttypes: defineCommand({\n\t\t\tmeta: {\n\t\t\t\tname: 'types',\n\t\t\t\tdescription: 'Generate TypeScript types from your schema',\n\t\t\t},\n\t\t\targs: {\n\t\t\t\tschema: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Path to schema file',\n\t\t\t\t},\n\t\t\t\toutput: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Output file path',\n\t\t\t\t\tdefault: 'kora/generated/types.ts',\n\t\t\t\t},\n\t\t\t},\n\t\t\tasync run({ args }) {\n\t\t\t\tconst logger = createLogger()\n\n\t\t\t\t// Find project root\n\t\t\t\tconst projectRoot = await findProjectRoot()\n\t\t\t\tif (!projectRoot) {\n\t\t\t\t\tthrow new InvalidProjectError(process.cwd())\n\t\t\t\t}\n\n\t\t\t\t// Find schema file\n\t\t\t\tlet schemaPath: string\n\t\t\t\tif (args.schema && typeof args.schema === 'string') {\n\t\t\t\t\tschemaPath = resolve(args.schema)\n\t\t\t\t} else {\n\t\t\t\t\tconst found = await findSchemaFile(projectRoot)\n\t\t\t\t\tif (!found) {\n\t\t\t\t\t\tthrow new SchemaNotFoundError([\n\t\t\t\t\t\t\t'src/schema.ts',\n\t\t\t\t\t\t\t'schema.ts',\n\t\t\t\t\t\t\t'src/schema.js',\n\t\t\t\t\t\t\t'schema.js',\n\t\t\t\t\t\t])\n\t\t\t\t\t}\n\t\t\t\t\tschemaPath = found\n\t\t\t\t}\n\n\t\t\t\tlogger.step(`Reading schema from ${schemaPath}...`)\n\n\t\t\t\t// Dynamic import the schema file\n\t\t\t\tconst schemaModule: unknown = await import(schemaPath)\n\t\t\t\tconst schema = extractSchema(schemaModule)\n\n\t\t\t\tif (!schema) {\n\t\t\t\t\tlogger.error('Schema file must export a SchemaDefinition as the default export.')\n\t\t\t\t\tprocess.exitCode = 1\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Generate types\n\t\t\t\tconst output = generateTypes(schema)\n\t\t\t\tconst outputFile = typeof args.output === 'string' ? args.output : 'kora/generated/types.ts'\n\t\t\t\tconst outputPath = resolve(projectRoot, outputFile)\n\n\t\t\t\tawait mkdir(dirname(outputPath), { recursive: true })\n\t\t\t\tawait writeFile(outputPath, output, 'utf-8')\n\n\t\t\t\tlogger.success(`Generated types at ${outputPath}`)\n\t\t\t},\n\t\t}),\n\t\thooks: defineCommand({\n\t\t\tmeta: {\n\t\t\t\tname: 'hooks',\n\t\t\t\tdescription: 'Generate per-collection React hook stubs',\n\t\t\t},\n\t\t\targs: {\n\t\t\t\tschema: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Path to schema file',\n\t\t\t\t},\n\t\t\t\toutput: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Output directory for hooks',\n\t\t\t\t\tdefault: 'kora/generated/hooks',\n\t\t\t\t},\n\t\t\t\ttypes: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Relative import path to generated types from hook files',\n\t\t\t\t\tdefault: '../types',\n\t\t\t\t},\n\t\t\t},\n\t\t\tasync run({ args }) {\n\t\t\t\tconst logger = createLogger()\n\t\t\t\tconst projectRoot = await findProjectRoot()\n\t\t\t\tif (!projectRoot) {\n\t\t\t\t\tthrow new InvalidProjectError(process.cwd())\n\t\t\t\t}\n\n\t\t\t\tlet schemaPath: string\n\t\t\t\tif (args.schema && typeof args.schema === 'string') {\n\t\t\t\t\tschemaPath = resolve(projectRoot, args.schema)\n\t\t\t\t} else {\n\t\t\t\t\tconst found = await findSchemaFile(projectRoot)\n\t\t\t\t\tif (!found) {\n\t\t\t\t\t\tthrow new SchemaNotFoundError([\n\t\t\t\t\t\t\t'src/schema.ts',\n\t\t\t\t\t\t\t'schema.ts',\n\t\t\t\t\t\t\t'src/schema.js',\n\t\t\t\t\t\t\t'schema.js',\n\t\t\t\t\t\t])\n\t\t\t\t\t}\n\t\t\t\t\tschemaPath = found\n\t\t\t\t}\n\n\t\t\t\tconst schema = await loadSchemaDefinition(schemaPath, projectRoot)\n\t\t\t\tconst outputDir =\n\t\t\t\t\ttypeof args.output === 'string'\n\t\t\t\t\t\t? resolve(projectRoot, args.output)\n\t\t\t\t\t\t: resolve(projectRoot, 'kora/generated/hooks')\n\n\t\t\t\tconst files = generateCollectionHooks(schema)\n\t\t\t\tfor (const [name, content] of files) {\n\t\t\t\t\tconst adjusted =\n\t\t\t\t\t\ttypeof args.types === 'string' && args.types !== '../types'\n\t\t\t\t\t\t\t? content.replace(\"from '../types'\", `from '${args.types}'`)\n\t\t\t\t\t\t\t: content\n\t\t\t\t\tconst filePath = resolve(outputDir, name)\n\t\t\t\t\tawait mkdir(dirname(filePath), { recursive: true })\n\t\t\t\t\tawait writeFile(filePath, adjusted, 'utf-8')\n\t\t\t\t}\n\n\t\t\t\tlogger.success(`Generated ${String(files.size)} hook file(s) at ${outputDir}`)\n\t\t\t\tlogger.step('Run `kora generate types` first if ../types is missing.')\n\t\t\t},\n\t\t}),\n\t},\n})\n\nfunction extractSchema(mod: unknown): SchemaDefinition | null {\n\tif (typeof mod !== 'object' || mod === null) return null\n\tconst record = mod as Record<string, unknown>\n\n\t// Check for default export\n\tconst candidate = record.default ?? record\n\tif (isSchemaDefinition(candidate)) return candidate\n\n\treturn null\n}\n\nfunction isSchemaDefinition(value: unknown): value is SchemaDefinition {\n\tif (typeof value !== 'object' || value === null) return false\n\tconst obj = value as Record<string, unknown>\n\treturn (\n\t\ttypeof obj.version === 'number' &&\n\t\ttypeof obj.collections === 'object' &&\n\t\tobj.collections !== null\n\t)\n}\n","import type { SchemaDefinition } from '@korajs/core'\n\n/**\n * Generates per-collection React hook stubs from a schema.\n *\n * @param schema - Validated schema definition\n * @returns Map of file basename to file contents\n */\nexport function generateCollectionHooks(schema: SchemaDefinition): Map<string, string> {\n\tconst files = new Map<string, string>()\n\n\tfor (const collectionName of Object.keys(schema.collections)) {\n\t\tconst pascal = toPascalCase(collectionName)\n\t\tconst hookName = `use${pascal}`\n\n\t\tconst content = [\n\t\t\t'// Auto-generated by `kora generate hooks` — safe to edit',\n\t\t\t`// Schema v${String(schema.version)}`,\n\t\t\t'',\n\t\t\t\"import { useCollection, useMutation, useQuery } from '@korajs/react'\",\n\t\t\t`import type { ${pascal}InsertInput, ${pascal}Record, ${pascal}UpdateInput } from '../types'`,\n\t\t\t'',\n\t\t\t'/**',\n\t\t\t` * Collection hook for \\`${collectionName}\\`.`,\n\t\t\t' * Add useQuery(...) calls with your QueryBuilder factories.',\n\t\t\t' */',\n\t\t\t`export function ${hookName}() {`,\n\t\t\t`\\tconst ${collectionName} = useCollection('${collectionName}')`,\n\t\t\t'',\n\t\t\t`\\tconst insert = useMutation((data: ${pascal}InsertInput) => ${collectionName}.insert(data))`,\n\t\t\t`\\tconst update = useMutation((id: string, data: ${pascal}UpdateInput) =>`,\n\t\t\t`\\t\\t${collectionName}.update(id, data),`,\n\t\t\t'\\t)',\n\t\t\t`\\tconst remove = useMutation((id: string) => ${collectionName}.delete(id))`,\n\t\t\t'',\n\t\t\t'\\treturn {',\n\t\t\t`\\t\\t${collectionName},`,\n\t\t\t'\\t\\tinsert,',\n\t\t\t'\\t\\tupdate,',\n\t\t\t'\\t\\tremove,',\n\t\t\t'\\t}',\n\t\t\t'}',\n\t\t\t'',\n\t\t].join('\\n')\n\n\t\tfiles.set(`${collectionName}.ts`, content)\n\t}\n\n\tconst indexLines = [\n\t\t'// Auto-generated by `kora generate hooks`',\n\t\t'',\n\t\t...Object.keys(schema.collections).map((name) => {\n\t\t\tconst pascal = toPascalCase(name)\n\t\t\treturn `export { use${pascal} } from './${name}'`\n\t\t}),\n\t\t'',\n\t]\n\n\tfiles.set('index.ts', indexLines.join('\\n'))\n\treturn files\n}\n\nfunction toPascalCase(value: string): string {\n\treturn value\n\t\t.split(/[-_]/)\n\t\t.filter((part) => part.length > 0)\n\t\t.map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n\t\t.join('')\n}\n","import { defineCommand } from 'citty'\nimport { createLogger } from '../../utils/logger'\n\nconst DEFAULT_SYNC_PORT = 3001\nconst EVENTS_ENDPOINT = '/__kora/events'\n\n/**\n * The `logs` command — streams real-time events from a Kora sync server.\n */\nexport const logsCommand = defineCommand({\n\tmeta: {\n\t\tname: 'logs',\n\t\tdescription: 'Stream real-time events from a Kora sync server',\n\t},\n\targs: {\n\t\turl: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Sync server URL (default: http://localhost:3001)',\n\t\t\tdefault: `http://localhost:${DEFAULT_SYNC_PORT}`,\n\t\t},\n\t\tfollow: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Follow log output (like tail -f)',\n\t\t\tdefault: true,\n\t\t\talias: 'f',\n\t\t},\n\t\tlevel: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Filter by log level (info, warn, error)',\n\t\t},\n\t\ttoken: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Admin token (defaults to KORA_ADMIN_TOKEN)',\n\t\t},\n\t},\n\tasync run({ args }) {\n\t\tconst logger = createLogger()\n\t\tconst url = typeof args.url === 'string' ? args.url : `http://localhost:${DEFAULT_SYNC_PORT}`\n\t\tconst follow = args.follow !== false\n\t\tconst levelFilter = typeof args.level === 'string' ? args.level : null\n\t\tconst token =\n\t\t\ttypeof args.token === 'string' ? args.token : (process.env.KORA_ADMIN_TOKEN ?? undefined)\n\t\tconst eventsUrl = `${url.replace(/\\/$/, '')}${EVENTS_ENDPOINT}`\n\n\t\tlogger.banner()\n\t\tlogger.info(`Connecting to ${eventsUrl}...`)\n\t\tlogger.blank()\n\n\t\ttry {\n\t\t\tconst response = await fetch(eventsUrl, {\n\t\t\t\theaders: token ? { Authorization: `Bearer ${token}` } : undefined,\n\t\t\t})\n\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Failed to connect to ${eventsUrl}: ${response.status} ${response.statusText}`,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst reader = response.body?.getReader()\n\t\t\tif (!reader) {\n\t\t\t\tthrow new Error('Response body is not readable')\n\t\t\t}\n\n\t\t\tconst decoder = new TextDecoder()\n\t\t\tlet buffer = ''\n\n\t\t\tconst processLine = (line: string) => {\n\t\t\t\t// SSE format: \"event: <type>\\ndata: <json>\\n\\n\"\n\t\t\t\tif (line.startsWith('event: ')) {\n\t\t\t\t\treturn // We handle the data line\n\t\t\t\t}\n\t\t\t\tif (line.startsWith('data: ')) {\n\t\t\t\t\tconst data = line.slice(6)\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst parsed = JSON.parse(data) as Record<string, unknown>\n\t\t\t\t\t\tconst level = String(parsed.level ?? 'info')\n\n\t\t\t\t\t\tif (levelFilter && level !== levelFilter) return\n\n\t\t\t\t\t\tconst timestamp = parsed.timestamp\n\t\t\t\t\t\t\t? new Date(parsed.timestamp as number).toISOString()\n\t\t\t\t\t\t\t: ''\n\t\t\t\t\t\tconst event = String(parsed.event ?? 'unknown')\n\t\t\t\t\t\tconst nodeId = parsed.nodeId ? ` [${parsed.nodeId}]` : ''\n\t\t\t\t\t\tconst session = parsed.sessionId ? ` <${parsed.sessionId}>` : ''\n\t\t\t\t\t\tconst count = parsed.count ? ` (${parsed.count})` : ''\n\t\t\t\t\t\tconst error = parsed.error ? ` — ${parsed.error}` : ''\n\n\t\t\t\t\t\tconst prefix = level === 'error' ? '✗' : level === 'warn' ? '⚠' : '●'\n\t\t\t\t\t\tconst color =\n\t\t\t\t\t\t\tlevel === 'error' ? '\\x1b[31m' : level === 'warn' ? '\\x1b[33m' : '\\x1b[36m'\n\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t`${color}${prefix}${'\\x1b[0m'} ${timestamp.slice(11, 23)} ${event}${nodeId}${session}${count}${error}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Ignore parse errors on malformed data\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst read = async () => {\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst { done, value } = await reader.read()\n\t\t\t\t\tif (done) break\n\n\t\t\t\t\tbuffer += decoder.decode(value, { stream: true })\n\t\t\t\t\tconst lines = buffer.split('\\n')\n\t\t\t\t\tbuffer = lines.pop() ?? ''\n\n\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\tprocessLine(line.trim())\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!follow) break\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait read()\n\t\t} catch (error) {\n\t\t\tlogger.error(`Failed to connect to ${eventsUrl}`)\n\t\t\tif (error instanceof Error) {\n\t\t\t\tlogger.error(error.message)\n\t\t\t}\n\t\t\tlogger.blank()\n\t\t\tlogger.step('Make sure the Kora sync server is running.')\n\t\t\tlogger.step('Start it with: kora dev')\n\t\t\tprocess.exit(1)\n\t\t}\n\t},\n})\n","import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises'\nimport { dirname, join, resolve } from 'node:path'\nimport type { SchemaDefinition } from '@korajs/core'\nimport { defineCommand } from 'citty'\nimport { InvalidProjectError, SchemaNotFoundError } from '../../errors'\nimport { findProjectRoot, findSchemaFile } from '../../utils/fs-helpers'\nimport { createLogger } from '../../utils/logger'\nimport { promptConfirm } from '../../utils/prompt'\nimport { loadKoraConfig } from '../dev/kora-config'\nimport { generateMigration } from './migration-generator'\nimport { runMigration } from './migration-runner'\nimport { generateOperationTransformModule } from './operation-transform-generator'\nimport { diffSchemas } from './schema-differ'\nimport { loadSchemaDefinition } from './schema-loader'\n\nconst SNAPSHOT_PATH = 'kora/schema.snapshot.json'\nconst MIGRATIONS_DIR = 'kora/migrations'\n\ninterface MigrationManifest {\n\tid: string\n\tfromVersion: number\n\ttoVersion: number\n\tup: string[]\n\tdown: string[]\n\tsummary: string[]\n\tcontainsBreakingChanges: boolean\n}\n\n/**\n * The `migrate` command — detects schema changes and generates migration artifacts.\n */\nexport const migrateCommand = defineCommand({\n\tmeta: {\n\t\tname: 'migrate',\n\t\tdescription: 'Detect schema changes and generate/apply migrations',\n\t},\n\targs: {\n\t\tapply: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Apply migration to configured database backends',\n\t\t\tdefault: false,\n\t\t},\n\t\tschema: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Path to schema file',\n\t\t},\n\t\tdb: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'SQLite database path for --apply (overrides config)',\n\t\t},\n\t\t'output-dir': {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Migration output directory',\n\t\t\tdefault: MIGRATIONS_DIR,\n\t\t},\n\t\t'dry-run': {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Preview migration changes without writing files',\n\t\t\tdefault: false,\n\t\t},\n\t\tforce: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Skip breaking-change confirmation prompts',\n\t\t\tdefault: false,\n\t\t},\n\t},\n\tasync run({ args }) {\n\t\tconst logger = createLogger()\n\n\t\tconst projectRoot = await findProjectRoot()\n\t\tif (!projectRoot) {\n\t\t\tthrow new InvalidProjectError(process.cwd())\n\t\t}\n\n\t\tconst config = await loadKoraConfig(projectRoot)\n\t\tconst resolvedSchemaPath =\n\t\t\ttypeof args.schema === 'string'\n\t\t\t\t? resolve(projectRoot, args.schema)\n\t\t\t\t: typeof config?.schema === 'string'\n\t\t\t\t\t? resolve(projectRoot, config.schema)\n\t\t\t\t\t: await findSchemaFile(projectRoot)\n\n\t\tif (!resolvedSchemaPath) {\n\t\t\tthrow new SchemaNotFoundError(['src/schema.ts', 'schema.ts', 'src/schema.js', 'schema.js'])\n\t\t}\n\n\t\tconst currentSchema = await loadSchemaDefinition(resolvedSchemaPath, projectRoot)\n\n\t\tconst snapshotFile = join(projectRoot, SNAPSHOT_PATH)\n\t\tconst previousSchema = await readSchemaSnapshot(snapshotFile)\n\n\t\tif (!previousSchema) {\n\t\t\tif (args['dry-run'] === true) {\n\t\t\t\tlogger.info('No schema snapshot found. Dry run: baseline snapshot would be created.')\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tawait writeSchemaSnapshot(snapshotFile, currentSchema)\n\t\t\tlogger.success(`Initialized schema snapshot at ${snapshotFile}`)\n\t\t\tlogger.step('Run `kora migrate` again after schema changes to generate migrations.')\n\t\t\treturn\n\t\t}\n\n\t\tconst diff = diffSchemas(previousSchema, currentSchema)\n\t\tconst outputDir =\n\t\t\ttypeof args['output-dir'] === 'string'\n\t\t\t\t? resolve(projectRoot, args['output-dir'])\n\t\t\t\t: resolve(projectRoot, MIGRATIONS_DIR)\n\n\t\tif (!diff.hasChanges) {\n\t\t\tlogger.success('No schema changes detected.')\n\t\t\tif (args.apply === true) {\n\t\t\t\tconst sqlitePath = resolveSqliteApplyPath(args.db, projectRoot, config)\n\t\t\t\tconst postgresConnectionString = resolvePostgresConnectionString(config)\n\t\t\t\tconst pending = await listMigrationManifests(outputDir)\n\n\t\t\t\tif (pending.length === 0) {\n\t\t\t\t\tlogger.step('No migration files found to apply.')\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tfor (const manifest of pending) {\n\t\t\t\t\tconst report = await runMigration({\n\t\t\t\t\t\tupStatements: manifest.up,\n\t\t\t\t\t\tmigrationId: manifest.id,\n\t\t\t\t\t\tfromVersion: manifest.fromVersion,\n\t\t\t\t\t\ttoVersion: manifest.toVersion,\n\t\t\t\t\t\tsqlitePath,\n\t\t\t\t\t\tpostgresConnectionString,\n\t\t\t\t\t\tprojectRoot,\n\t\t\t\t\t})\n\n\t\t\t\t\tfor (const backend of report.backends) {\n\t\t\t\t\t\tlogger.step(\n\t\t\t\t\t\t\t` ${manifest.id} -> ${backend.backend}: applied=${backend.statementsApplied}, skipped=${backend.skipped}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tconst generated = generateMigration(previousSchema, currentSchema, diff)\n\n\t\tlogger.banner()\n\t\tlogger.info(`Detected schema change: v${diff.fromVersion} → v${diff.toVersion}`)\n\t\tlogger.blank()\n\t\tlogger.info('Changes:')\n\t\tfor (const line of generated.summary) {\n\t\t\tlogger.step(` ${line}`)\n\t\t}\n\n\t\tif (diff.hasBreakingChanges && args['dry-run'] !== true) {\n\t\t\tlogger.blank()\n\t\t\tlogger.warn('Breaking schema changes detected.')\n\t\t\tconst shouldContinue = await confirmBreakingChanges(args.force === true)\n\t\t\tif (!shouldContinue) {\n\t\t\t\tlogger.warn('Migration generation aborted.')\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tif (args['dry-run'] === true) {\n\t\t\tlogger.blank()\n\t\t\tlogger.warn('Dry run enabled: no files written, no migrations applied.')\n\t\t\treturn\n\t\t}\n\n\t\tawait mkdir(outputDir, { recursive: true })\n\n\t\tconst migrationPath = await writeMigrationFile(\n\t\t\toutputDir,\n\t\t\tdiff.fromVersion,\n\t\t\tdiff.toVersion,\n\t\t\tgenerated,\n\t\t)\n\t\tawait writeSchemaSnapshot(snapshotFile, currentSchema)\n\n\t\tlogger.blank()\n\t\tlogger.success(`Generated migration: ${migrationPath}`)\n\n\t\tif (args.apply === true) {\n\t\t\tconst sqlitePath = resolveSqliteApplyPath(args.db, projectRoot, config)\n\t\t\tconst postgresConnectionString = resolvePostgresConnectionString(config)\n\t\t\tconst pending = await listMigrationManifests(outputDir)\n\n\t\t\tfor (const manifest of pending) {\n\t\t\t\tconst report = await runMigration({\n\t\t\t\t\tupStatements: manifest.up,\n\t\t\t\t\tmigrationId: manifest.id,\n\t\t\t\t\tfromVersion: manifest.fromVersion,\n\t\t\t\t\ttoVersion: manifest.toVersion,\n\t\t\t\t\tsqlitePath,\n\t\t\t\t\tpostgresConnectionString,\n\t\t\t\t\tprojectRoot,\n\t\t\t\t})\n\n\t\t\t\tfor (const backend of report.backends) {\n\t\t\t\t\tlogger.step(\n\t\t\t\t\t\t` ${manifest.id} -> ${backend.backend}: applied=${backend.statementsApplied}, skipped=${backend.skipped}, history=${backend.historyRecorded}`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlogger.success('Applied pending migrations successfully.')\n\t\t}\n\t},\n})\n\nasync function readSchemaSnapshot(path: string): Promise<SchemaDefinition | null> {\n\ttry {\n\t\tconst content = await readFile(path, 'utf-8')\n\t\treturn JSON.parse(content) as SchemaDefinition\n\t} catch {\n\t\treturn null\n\t}\n}\n\nasync function confirmBreakingChanges(force: boolean): Promise<boolean> {\n\tif (force) {\n\t\treturn true\n\t}\n\n\tif (!isInteractiveTerminal()) {\n\t\tthrow new Error(\n\t\t\t'Breaking schema changes require confirmation. Re-run with --force to continue or --dry-run to preview.',\n\t\t)\n\t}\n\n\treturn await promptConfirm('Continue and generate a breaking migration?', false)\n}\n\nfunction isInteractiveTerminal(): boolean {\n\treturn process.stdin.isTTY === true && process.stdout.isTTY === true\n}\n\nasync function writeSchemaSnapshot(path: string, schema: SchemaDefinition): Promise<void> {\n\tawait mkdir(dirname(path), { recursive: true })\n\tawait writeFile(path, `${JSON.stringify(schema, null, 2)}\\n`, 'utf-8')\n}\n\nasync function writeMigrationFile(\n\toutputDir: string,\n\tfromVersion: number,\n\ttoVersion: number,\n\tgenerated: ReturnType<typeof generateMigration>,\n): Promise<string> {\n\tconst existing = await readdir(outputDir).catch(() => [])\n\tconst sequence = existing.filter((file) => /^\\d{3}-/.test(file)).length + 1\n\tconst filename = `${String(sequence).padStart(3, '0')}-v${fromVersion}-to-v${toVersion}.ts`\n\tconst path = join(outputDir, filename)\n\tconst migrationId = filename.replace(/\\.ts$/, '')\n\n\tconst fileContent = [\n\t\t`export const up = ${JSON.stringify(generated.up, null, 2)} as const`,\n\t\t'',\n\t\t`export const down = ${JSON.stringify(generated.down, null, 2)} as const`,\n\t\t'',\n\t\t`export const summary = ${JSON.stringify(generated.summary, null, 2)} as const`,\n\t\t'',\n\t\t`export const containsBreakingChanges = ${generated.containsBreakingChanges}`,\n\t\t'',\n\t].join('\\n')\n\n\tawait writeFile(path, fileContent, 'utf-8')\n\n\tconst transformsPath = join(outputDir, `${migrationId}.transforms.ts`)\n\tawait writeFile(transformsPath, generateOperationTransformModule(fromVersion, toVersion), 'utf-8')\n\tawait writeMigrationManifest(join(outputDir, `${migrationId}.json`), {\n\t\tid: migrationId,\n\t\tfromVersion,\n\t\ttoVersion,\n\t\tup: generated.up,\n\t\tdown: generated.down,\n\t\tsummary: generated.summary,\n\t\tcontainsBreakingChanges: generated.containsBreakingChanges,\n\t})\n\treturn path\n}\n\nasync function writeMigrationManifest(path: string, manifest: MigrationManifest): Promise<void> {\n\tawait writeFile(path, `${JSON.stringify(manifest, null, 2)}\\n`, 'utf-8')\n}\n\nasync function listMigrationManifests(outputDir: string): Promise<MigrationManifest[]> {\n\tconst files = await readdir(outputDir).catch(() => [])\n\tconst migrationFiles = files\n\t\t.filter((file) => /^\\d{3}-.*\\.ts$/.test(file))\n\t\t.sort((left, right) => left.localeCompare(right))\n\n\tconst manifests: MigrationManifest[] = []\n\tfor (const file of migrationFiles) {\n\t\tconst id = file.replace(/\\.ts$/, '')\n\t\tconst manifestPath = join(outputDir, `${id}.json`)\n\t\tconst jsonManifest = await readMigrationManifest(manifestPath)\n\n\t\tif (jsonManifest) {\n\t\t\tmanifests.push({ ...jsonManifest, id })\n\t\t\tcontinue\n\t\t}\n\n\t\tconst migrationPath = join(outputDir, file)\n\t\tconst sourceManifest = await readMigrationManifestFromSource(migrationPath, id)\n\t\tmanifests.push(sourceManifest)\n\t}\n\n\treturn manifests\n}\n\nasync function readMigrationManifest(path: string): Promise<MigrationManifest | null> {\n\ttry {\n\t\tconst content = await readFile(path, 'utf-8')\n\t\treturn JSON.parse(content) as MigrationManifest\n\t} catch (error) {\n\t\tconst code = (error as NodeJS.ErrnoException).code\n\t\tif (code === 'ENOENT') {\n\t\t\treturn null\n\t\t}\n\t\tthrow error\n\t}\n}\n\nasync function readMigrationManifestFromSource(\n\tpath: string,\n\tid: string,\n): Promise<MigrationManifest> {\n\tconst content = await readFile(path, 'utf-8')\n\tconst versions = parseVersionsFromMigrationId(id)\n\n\treturn {\n\t\tid,\n\t\tfromVersion: versions.fromVersion,\n\t\ttoVersion: versions.toVersion,\n\t\tup: parseStringArrayExport(content, 'up'),\n\t\tdown: parseStringArrayExport(content, 'down'),\n\t\tsummary: parseStringArrayExport(content, 'summary'),\n\t\tcontainsBreakingChanges: parseBooleanExport(content, 'containsBreakingChanges'),\n\t}\n}\n\nfunction parseVersionsFromMigrationId(id: string): { fromVersion: number; toVersion: number } {\n\tconst match = id.match(/-v(\\d+)-to-v(\\d+)$/)\n\tif (!match) {\n\t\tthrow new Error(`Migration id \"${id}\" does not include a vX-to-vY version suffix.`)\n\t}\n\n\tconst fromVersionText = match[1]\n\tconst toVersionText = match[2]\n\tif (fromVersionText === undefined || toVersionText === undefined) {\n\t\tthrow new Error(`Migration id \"${id}\" does not include a vX-to-vY version suffix.`)\n\t}\n\n\treturn {\n\t\tfromVersion: Number.parseInt(fromVersionText, 10),\n\t\ttoVersion: Number.parseInt(toVersionText, 10),\n\t}\n}\n\nfunction parseStringArrayExport(source: string, exportName: 'up' | 'down' | 'summary'): string[] {\n\tconst expression = parseExportExpression(source, exportName)\n\tconst parsed = JSON.parse(expression) as unknown\n\tif (!Array.isArray(parsed) || parsed.some((item) => typeof item !== 'string')) {\n\t\tthrow new Error(`Migration export \"${exportName}\" must be a string array.`)\n\t}\n\n\treturn parsed\n}\n\nfunction parseBooleanExport(source: string, exportName: 'containsBreakingChanges'): boolean {\n\tconst expression = parseLiteralExport(source, exportName)\n\tif (expression === 'true') return true\n\tif (expression === 'false') return false\n\tthrow new Error(`Migration export \"${exportName}\" must be a boolean literal.`)\n}\n\nfunction parseExportExpression(source: string, exportName: string): string {\n\tconst escapedName = exportName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\tconst regex = new RegExp(`export const ${escapedName} = ([\\\\s\\\\S]*?) as const`)\n\tconst match = source.match(regex)\n\tif (!match || !match[1]) {\n\t\tthrow new Error(`Failed to read migration export \"${exportName}\".`)\n\t}\n\n\treturn match[1].trim()\n}\n\nfunction parseLiteralExport(source: string, exportName: string): string {\n\tconst escapedName = exportName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\tconst regex = new RegExp(`export const ${escapedName} = ([^\\n\\r]+)`)\n\tconst match = source.match(regex)\n\tif (!match || !match[1]) {\n\t\tthrow new Error(`Failed to read migration export \"${exportName}\".`)\n\t}\n\n\treturn match[1].trim()\n}\n\nfunction resolveSqliteApplyPath(\n\tdbArg: unknown,\n\tprojectRoot: string,\n\tconfig: Awaited<ReturnType<typeof loadKoraConfig>>,\n): string | undefined {\n\tif (typeof dbArg === 'string') {\n\t\treturn resolve(projectRoot, dbArg)\n\t}\n\n\tconst sync = config?.dev?.sync\n\tif (typeof sync === 'object' && sync !== null) {\n\t\tif (sync.store === 'sqlite') {\n\t\t\treturn join(projectRoot, 'kora-sync.db')\n\t\t}\n\t\tif (typeof sync.store === 'object' && sync.store !== null && sync.store.type === 'sqlite') {\n\t\t\tif (typeof sync.store.filename === 'string' && sync.store.filename.length > 0) {\n\t\t\t\treturn resolve(projectRoot, sync.store.filename)\n\t\t\t}\n\t\t\treturn join(projectRoot, 'kora-sync.db')\n\t\t}\n\t}\n\n\treturn undefined\n}\n\nfunction resolvePostgresConnectionString(\n\tconfig: Awaited<ReturnType<typeof loadKoraConfig>>,\n): string | undefined {\n\tconst sync = config?.dev?.sync\n\tif (typeof sync !== 'object' || sync === null) return undefined\n\n\tif (sync.store === 'postgres') {\n\t\treturn process.env.DATABASE_URL\n\t}\n\n\tif (typeof sync.store === 'object' && sync.store !== null && sync.store.type === 'postgres') {\n\t\treturn sync.store.connectionString\n\t}\n\n\treturn undefined\n}\n","import { generateSQL } from '@korajs/core'\nimport type { CollectionDefinition, FieldDescriptor, SchemaDefinition } from '@korajs/core'\nimport type { SchemaDiff } from './schema-differ'\nimport { getChangedCollections } from './schema-differ'\n\nexport interface GeneratedMigration {\n\tup: string[]\n\tdown: string[]\n\tsummary: string[]\n\tcontainsBreakingChanges: boolean\n}\n\n/**\n * Generates SQL up/down migration statements from a schema diff.\n */\nexport function generateMigration(\n\tprevious: SchemaDefinition,\n\tcurrent: SchemaDefinition,\n\tdiff: SchemaDiff,\n): GeneratedMigration {\n\tconst up: string[] = []\n\tconst down: string[] = []\n\n\tfor (const change of diff.changes) {\n\t\tif (change.type === 'collection-added') {\n\t\t\tconst collectionDef = current.collections[change.collection]\n\t\t\tif (!collectionDef) continue\n\t\t\tup.push(...generateSQL(change.collection, collectionDef))\n\t\t\tdown.push(...dropCollectionStatements(change.collection))\n\t\t}\n\n\t\tif (change.type === 'collection-removed') {\n\t\t\tconst collectionDef = previous.collections[change.collection]\n\t\t\tup.push(...dropCollectionStatements(change.collection))\n\t\t\tif (collectionDef) {\n\t\t\t\tdown.push(...generateSQL(change.collection, collectionDef))\n\t\t\t}\n\t\t}\n\t}\n\n\tconst changedCollections = getChangedCollections(diff).filter(\n\t\t(collection) =>\n\t\t\tcollection in previous.collections &&\n\t\t\tcollection in current.collections &&\n\t\t\tdiff.changes.some(\n\t\t\t\t(change) =>\n\t\t\t\t\tchange.collection === collection &&\n\t\t\t\t\t(change.type === 'field-added' ||\n\t\t\t\t\t\tchange.type === 'field-removed' ||\n\t\t\t\t\t\tchange.type === 'field-changed' ||\n\t\t\t\t\t\tchange.type === 'index-added' ||\n\t\t\t\t\t\tchange.type === 'index-removed'),\n\t\t\t),\n\t)\n\n\tfor (const collection of changedCollections) {\n\t\tconst previousDef = previous.collections[collection]\n\t\tconst currentDef = current.collections[collection]\n\t\tif (!previousDef || !currentDef) continue\n\n\t\tvalidateRebuildSafety(collection, previousDef, currentDef)\n\n\t\tup.push(...generateRebuildStatements(collection, previousDef, currentDef))\n\t\tdown.push(...generateRebuildStatements(collection, currentDef, previousDef))\n\t}\n\n\tdown.reverse()\n\n\treturn {\n\t\tup,\n\t\tdown,\n\t\tsummary: diff.changes.map(formatChange),\n\t\tcontainsBreakingChanges: diff.hasBreakingChanges,\n\t}\n}\n\nfunction generateRebuildStatements(\n\tcollection: string,\n\tfrom: CollectionDefinition,\n\tto: CollectionDefinition,\n): string[] {\n\tconst table = quoteIdentifier(collection)\n\tconst tempTable = quoteIdentifier(`_kora_mig_${collection}_new`)\n\n\tconst targetColumns = [\n\t\t'id TEXT PRIMARY KEY NOT NULL',\n\t\t...Object.entries(to.fields).map(([field, descriptor]) => columnDefinition(field, descriptor)),\n\t\t'_created_at INTEGER NOT NULL',\n\t\t'_updated_at INTEGER NOT NULL',\n\t\t'_deleted INTEGER NOT NULL DEFAULT 0',\n\t]\n\n\tconst statements: string[] = []\n\tstatements.push(`CREATE TABLE ${tempTable} (\\n ${targetColumns.join(',\\n ')}\\n)`)\n\n\tconst toFields = Object.keys(to.fields)\n\tconst columns = ['id', ...toFields, '_created_at', '_updated_at', '_deleted']\n\tconst selectExpressions = columns.map((column) =>\n\t\tprojectionForColumn(column, from.fields, to.fields[column] ?? null),\n\t)\n\n\tstatements.push(\n\t\t`INSERT INTO ${tempTable} (${columns.map(quoteIdentifier).join(', ')}) SELECT ${selectExpressions.join(', ')} FROM ${table}`,\n\t)\n\tstatements.push(`DROP TABLE ${table}`)\n\tstatements.push(`ALTER TABLE ${tempTable} RENAME TO ${table}`)\n\n\tfor (const indexField of to.indexes) {\n\t\tstatements.push(\n\t\t\t`CREATE INDEX IF NOT EXISTS idx_${collection}_${indexField} ON ${table} (${quoteIdentifier(indexField)})`,\n\t\t)\n\t}\n\n\treturn statements\n}\n\nfunction validateRebuildSafety(\n\tcollection: string,\n\tfrom: CollectionDefinition,\n\tto: CollectionDefinition,\n): void {\n\tfor (const [fieldName, descriptor] of Object.entries(to.fields)) {\n\t\tif (fieldName in from.fields) continue\n\t\tif (descriptor.required && descriptor.defaultValue === undefined && !descriptor.auto) {\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot auto-migrate collection \"${collection}\": added required field \"${fieldName}\" has no default value.`,\n\t\t\t)\n\t\t}\n\t}\n\n\tfor (const [fieldName, targetDescriptor] of Object.entries(to.fields)) {\n\t\tconst sourceDescriptor = from.fields[fieldName]\n\t\tif (!sourceDescriptor) continue\n\t\tif (canTransformField(sourceDescriptor, targetDescriptor)) continue\n\n\t\tif (\n\t\t\ttargetDescriptor.required &&\n\t\t\ttargetDescriptor.defaultValue === undefined &&\n\t\t\t!targetDescriptor.auto\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot auto-migrate collection \"${collection}\": changed required field \"${fieldName}\" from ${sourceDescriptor.kind} to ${targetDescriptor.kind} without a safe transform/default.`,\n\t\t\t)\n\t\t}\n\t}\n}\n\nfunction projectionForColumn(\n\tcolumn: string,\n\tfromFields: Record<string, FieldDescriptor>,\n\ttargetDescriptor: FieldDescriptor | null,\n): string {\n\tif (\n\t\tcolumn === 'id' ||\n\t\tcolumn === '_created_at' ||\n\t\tcolumn === '_updated_at' ||\n\t\tcolumn === '_deleted'\n\t) {\n\t\treturn quoteIdentifier(column)\n\t}\n\n\tconst sourceDescriptor = fromFields[column]\n\tif (sourceDescriptor && targetDescriptor) {\n\t\treturn projectionForFieldTransform(column, sourceDescriptor, targetDescriptor)\n\t}\n\n\tif (sourceDescriptor) {\n\t\treturn quoteIdentifier(column)\n\t}\n\n\tif (!targetDescriptor) {\n\t\treturn 'NULL'\n\t}\n\n\tif (targetDescriptor.auto && targetDescriptor.kind === 'timestamp') {\n\t\treturn \"CAST(strftime('%s','now') AS INTEGER) * 1000\"\n\t}\n\n\tif (targetDescriptor.defaultValue !== undefined) {\n\t\treturn sqlLiteral(targetDescriptor.defaultValue)\n\t}\n\n\treturn 'NULL'\n}\n\nfunction projectionForFieldTransform(\n\tcolumn: string,\n\tsource: FieldDescriptor,\n\ttarget: FieldDescriptor,\n): string {\n\tconst sourceColumn = quoteIdentifier(column)\n\tif (source.kind === target.kind && source.itemKind === target.itemKind) {\n\t\tif (target.kind === 'enum' && target.enumValues && target.enumValues.length > 0) {\n\t\t\tconst allowed = target.enumValues.map((value) => sqlLiteral(value)).join(', ')\n\t\t\tconst fallback =\n\t\t\t\ttarget.defaultValue !== undefined ? sqlLiteral(target.defaultValue) : sourceColumn\n\t\t\treturn `CASE WHEN ${sourceColumn} IN (${allowed}) THEN ${sourceColumn} ELSE ${fallback} END`\n\t\t}\n\t\treturn sourceColumn\n\t}\n\n\tif (target.kind === 'string') {\n\t\treturn `CAST(${sourceColumn} AS TEXT)`\n\t}\n\n\tif (target.kind === 'number' || target.kind === 'timestamp') {\n\t\tif (\n\t\t\tsource.kind === 'string' ||\n\t\t\tsource.kind === 'enum' ||\n\t\t\tsource.kind === 'number' ||\n\t\t\tsource.kind === 'timestamp' ||\n\t\t\tsource.kind === 'boolean'\n\t\t) {\n\t\t\tconst castType = target.kind === 'number' ? 'REAL' : 'INTEGER'\n\t\t\treturn `CASE WHEN ${sourceColumn} IS NULL THEN NULL ELSE CAST(${sourceColumn} AS ${castType}) END`\n\t\t}\n\t}\n\n\tif (target.kind === 'boolean') {\n\t\tif (source.kind === 'number' || source.kind === 'timestamp' || source.kind === 'boolean') {\n\t\t\treturn `CASE WHEN ${sourceColumn} IS NULL THEN NULL WHEN CAST(${sourceColumn} AS REAL) = 0 THEN 0 ELSE 1 END`\n\t\t}\n\n\t\tif (source.kind === 'string' || source.kind === 'enum') {\n\t\t\treturn `CASE WHEN ${sourceColumn} IS NULL THEN NULL WHEN LOWER(TRIM(CAST(${sourceColumn} AS TEXT))) IN ('1','true','t','yes','y','on') THEN 1 WHEN LOWER(TRIM(CAST(${sourceColumn} AS TEXT))) IN ('0','false','f','no','n','off') THEN 0 ELSE ${projectionFallback(target)} END`\n\t\t}\n\t}\n\n\tif (target.kind === 'enum' && target.enumValues && target.enumValues.length > 0) {\n\t\tif (source.kind === 'string' || source.kind === 'enum') {\n\t\t\tconst allowed = target.enumValues.map((value) => sqlLiteral(value)).join(', ')\n\t\t\treturn `CASE WHEN ${sourceColumn} IN (${allowed}) THEN ${sourceColumn} ELSE ${projectionFallback(target)} END`\n\t\t}\n\t}\n\n\tif (target.kind === 'array' && source.kind === 'array' && source.itemKind === target.itemKind) {\n\t\treturn sourceColumn\n\t}\n\n\tif (target.auto && target.kind === 'timestamp') {\n\t\treturn \"CAST(strftime('%s','now') AS INTEGER) * 1000\"\n\t}\n\n\treturn projectionFallback(target)\n}\n\nfunction canTransformField(source: FieldDescriptor, target: FieldDescriptor): boolean {\n\tif (source.kind === target.kind && source.itemKind === target.itemKind) {\n\t\treturn true\n\t}\n\n\tif (target.kind === 'string') {\n\t\treturn true\n\t}\n\n\tif (target.kind === 'number' || target.kind === 'timestamp') {\n\t\treturn (\n\t\t\tsource.kind === 'string' ||\n\t\t\tsource.kind === 'enum' ||\n\t\t\tsource.kind === 'number' ||\n\t\t\tsource.kind === 'timestamp' ||\n\t\t\tsource.kind === 'boolean'\n\t\t)\n\t}\n\n\tif (target.kind === 'boolean') {\n\t\treturn (\n\t\t\tsource.kind === 'number' ||\n\t\t\tsource.kind === 'timestamp' ||\n\t\t\tsource.kind === 'boolean' ||\n\t\t\tsource.kind === 'string' ||\n\t\t\tsource.kind === 'enum'\n\t\t)\n\t}\n\n\tif (target.kind === 'enum') {\n\t\treturn source.kind === 'string' || source.kind === 'enum'\n\t}\n\n\tif (target.kind === 'array') {\n\t\treturn source.kind === 'array' && source.itemKind === target.itemKind\n\t}\n\n\tif (target.kind === 'richtext') {\n\t\treturn source.kind === 'richtext'\n\t}\n\n\treturn false\n}\n\nfunction projectionFallback(target: FieldDescriptor): string {\n\tif (target.auto && target.kind === 'timestamp') {\n\t\treturn \"CAST(strftime('%s','now') AS INTEGER) * 1000\"\n\t}\n\n\tif (target.defaultValue !== undefined) {\n\t\treturn sqlLiteral(target.defaultValue)\n\t}\n\n\treturn 'NULL'\n}\n\nfunction dropCollectionStatements(collection: string): string[] {\n\tconst table = quoteIdentifier(collection)\n\tconst opsTable = quoteIdentifier(`_kora_ops_${collection}`)\n\treturn [`DROP TABLE IF EXISTS ${table}`, `DROP TABLE IF EXISTS ${opsTable}`]\n}\n\nfunction columnDefinition(fieldName: string, descriptor: FieldDescriptor): string {\n\tconst sqlType = mapFieldType(descriptor)\n\tconst parts = [quoteIdentifier(fieldName), sqlType]\n\n\tif (descriptor.required && descriptor.defaultValue === undefined && !descriptor.auto) {\n\t\tparts.push('NOT NULL')\n\t}\n\n\tif (descriptor.defaultValue !== undefined) {\n\t\tparts.push(`DEFAULT ${sqlLiteral(descriptor.defaultValue)}`)\n\t}\n\n\tif (descriptor.kind === 'enum' && descriptor.enumValues) {\n\t\tconst values = descriptor.enumValues.map((value) => sqlLiteral(value)).join(', ')\n\t\tparts.push(`CHECK (${quoteIdentifier(fieldName)} IN (${values}))`)\n\t}\n\n\treturn parts.join(' ')\n}\n\nfunction mapFieldType(descriptor: FieldDescriptor): string {\n\tswitch (descriptor.kind) {\n\t\tcase 'string':\n\t\t\treturn 'TEXT'\n\t\tcase 'number':\n\t\t\treturn 'REAL'\n\t\tcase 'boolean':\n\t\t\treturn 'INTEGER'\n\t\tcase 'enum':\n\t\t\treturn 'TEXT'\n\t\tcase 'timestamp':\n\t\t\treturn 'INTEGER'\n\t\tcase 'array':\n\t\t\treturn 'TEXT'\n\t\tcase 'object':\n\t\t\treturn 'TEXT'\n\t\tcase 'json':\n\t\t\treturn 'TEXT'\n\t\tcase 'blob':\n\t\t\treturn 'TEXT'\n\t\tcase 'secret':\n\t\t\treturn 'TEXT'\n\t\tcase 'richtext':\n\t\t\treturn 'BLOB'\n\t}\n}\n\nfunction sqlLiteral(value: unknown): string {\n\tif (value === null) return 'NULL'\n\tif (typeof value === 'number') return String(value)\n\tif (typeof value === 'boolean') return value ? '1' : '0'\n\tif (typeof value === 'string') return `'${value.replaceAll(\"'\", \"''\")}'`\n\treturn `'${JSON.stringify(value).replaceAll(\"'\", \"''\")}'`\n}\n\nfunction quoteIdentifier(identifier: string): string {\n\tif (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(identifier)) {\n\t\tthrow new Error(`Invalid SQL identifier: ${identifier}`)\n\t}\n\t// Double-quote to match @korajs/core's generateSQL, so a generated migration\n\t// is internally consistent (CREATE from core, DROP/rebuild from here) even for\n\t// camelCase or reserved-word collection and column names.\n\treturn `\"${identifier}\"`\n}\n\nfunction formatChange(change: SchemaDiff['changes'][number]): string {\n\tswitch (change.type) {\n\t\tcase 'collection-added':\n\t\t\treturn `+ collection ${change.collection}`\n\t\tcase 'collection-removed':\n\t\t\treturn `- collection ${change.collection}`\n\t\tcase 'field-added':\n\t\t\treturn `+ ${change.collection}.${change.field}`\n\t\tcase 'field-removed':\n\t\t\treturn `- ${change.collection}.${change.field}`\n\t\tcase 'field-changed':\n\t\t\treturn `~ ${change.collection}.${change.field}`\n\t\tcase 'index-added':\n\t\t\treturn `+ index ${change.collection}.${change.index}`\n\t\tcase 'index-removed':\n\t\t\treturn `- index ${change.collection}.${change.index}`\n\t}\n}\n","import type { FieldDescriptor, SchemaDefinition } from '@korajs/core'\n\nexport type SchemaChange =\n\t| { type: 'collection-added'; collection: string }\n\t| { type: 'collection-removed'; collection: string }\n\t| { type: 'field-added'; collection: string; field: string; descriptor: FieldDescriptor }\n\t| { type: 'field-removed'; collection: string; field: string; descriptor: FieldDescriptor }\n\t| {\n\t\t\ttype: 'field-changed'\n\t\t\tcollection: string\n\t\t\tfield: string\n\t\t\tbefore: FieldDescriptor\n\t\t\tafter: FieldDescriptor\n\t }\n\t| { type: 'index-added'; collection: string; index: string }\n\t| { type: 'index-removed'; collection: string; index: string }\n\nexport interface SchemaDiff {\n\tfromVersion: number\n\ttoVersion: number\n\tchanges: SchemaChange[]\n\thasChanges: boolean\n\thasBreakingChanges: boolean\n}\n\n/**\n * Computes a structural schema diff.\n */\nexport function diffSchemas(previous: SchemaDefinition, current: SchemaDefinition): SchemaDiff {\n\tconst changes: SchemaChange[] = []\n\n\tconst previousCollections = new Set(Object.keys(previous.collections))\n\tconst currentCollections = new Set(Object.keys(current.collections))\n\n\tfor (const collection of currentCollections) {\n\t\tif (!previousCollections.has(collection)) {\n\t\t\tchanges.push({ type: 'collection-added', collection })\n\t\t}\n\t}\n\n\tfor (const collection of previousCollections) {\n\t\tif (!currentCollections.has(collection)) {\n\t\t\tchanges.push({ type: 'collection-removed', collection })\n\t\t}\n\t}\n\n\tfor (const collection of currentCollections) {\n\t\tif (!previousCollections.has(collection)) continue\n\n\t\tconst previousDef = previous.collections[collection]\n\t\tconst currentDef = current.collections[collection]\n\t\tif (!previousDef || !currentDef) continue\n\n\t\tconst previousFields = previousDef.fields\n\t\tconst currentFields = currentDef.fields\n\n\t\tfor (const [fieldName, currentField] of Object.entries(currentFields)) {\n\t\t\tconst previousField = previousFields[fieldName]\n\t\t\tif (!previousField) {\n\t\t\t\tchanges.push({\n\t\t\t\t\ttype: 'field-added',\n\t\t\t\t\tcollection,\n\t\t\t\t\tfield: fieldName,\n\t\t\t\t\tdescriptor: currentField,\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (!fieldDescriptorsEqual(previousField, currentField)) {\n\t\t\t\tchanges.push({\n\t\t\t\t\ttype: 'field-changed',\n\t\t\t\t\tcollection,\n\t\t\t\t\tfield: fieldName,\n\t\t\t\t\tbefore: previousField,\n\t\t\t\t\tafter: currentField,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tfor (const [fieldName, previousField] of Object.entries(previousFields)) {\n\t\t\tif (!(fieldName in currentFields)) {\n\t\t\t\tchanges.push({\n\t\t\t\t\ttype: 'field-removed',\n\t\t\t\t\tcollection,\n\t\t\t\t\tfield: fieldName,\n\t\t\t\t\tdescriptor: previousField,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tconst previousIndexes = new Set(previousDef.indexes)\n\t\tconst currentIndexes = new Set(currentDef.indexes)\n\n\t\tfor (const index of currentIndexes) {\n\t\t\tif (!previousIndexes.has(index)) {\n\t\t\t\tchanges.push({ type: 'index-added', collection, index })\n\t\t\t}\n\t\t}\n\n\t\tfor (const index of previousIndexes) {\n\t\t\tif (!currentIndexes.has(index)) {\n\t\t\t\tchanges.push({ type: 'index-removed', collection, index })\n\t\t\t}\n\t\t}\n\t}\n\n\tchanges.sort(compareChanges)\n\n\treturn {\n\t\tfromVersion: previous.version,\n\t\ttoVersion: current.version,\n\t\tchanges,\n\t\thasChanges: changes.length > 0,\n\t\thasBreakingChanges: changes.some(isBreakingChange),\n\t}\n}\n\nexport function getChangedCollections(diff: SchemaDiff): string[] {\n\tconst collections = new Set<string>()\n\tfor (const change of diff.changes) {\n\t\tcollections.add(change.collection)\n\t}\n\treturn [...collections].sort()\n}\n\nfunction isBreakingChange(change: SchemaChange): boolean {\n\tif (change.type === 'collection-removed' || change.type === 'field-removed') return true\n\tif (change.type === 'field-changed') {\n\t\tif (change.before.kind !== change.after.kind) return true\n\t\tif (change.before.itemKind !== change.after.itemKind) return true\n\t\tif (serializeEnum(change.before.enumValues) !== serializeEnum(change.after.enumValues))\n\t\t\treturn true\n\t\tif (change.before.required !== change.after.required && change.after.required) return true\n\t\treturn false\n\t}\n\tif (change.type === 'field-added') {\n\t\tconst descriptor = change.descriptor\n\t\treturn descriptor.required && descriptor.defaultValue === undefined && !descriptor.auto\n\t}\n\treturn false\n}\n\nfunction fieldDescriptorsEqual(left: FieldDescriptor, right: FieldDescriptor): boolean {\n\treturn (\n\t\tleft.kind === right.kind &&\n\t\tleft.required === right.required &&\n\t\tleft.defaultValue === right.defaultValue &&\n\t\tleft.auto === right.auto &&\n\t\tleft.itemKind === right.itemKind &&\n\t\tserializeEnum(left.enumValues) === serializeEnum(right.enumValues)\n\t)\n}\n\nfunction serializeEnum(values: readonly string[] | null): string {\n\tif (!values) return ''\n\treturn values.join('|')\n}\n\nfunction compareChanges(left: SchemaChange, right: SchemaChange): number {\n\tif (left.collection < right.collection) return -1\n\tif (left.collection > right.collection) return 1\n\n\tif (left.type < right.type) return -1\n\tif (left.type > right.type) return 1\n\n\tconst leftKey = 'field' in left ? left.field : 'index' in left ? left.index : ''\n\tconst rightKey = 'field' in right ? right.field : 'index' in right ? right.index : ''\n\n\tif (leftKey < rightKey) return -1\n\tif (leftKey > rightKey) return 1\n\treturn 0\n}\n","export interface RunMigrationOptions {\n\tupStatements: string[]\n\tmigrationId?: string\n\tfromVersion?: number\n\ttoVersion?: number\n\tsqlitePath?: string\n\tpostgresConnectionString?: string\n\tprojectRoot?: string\n\tsqliteDriver?: {\n\t\topen(path: string): {\n\t\t\texec(sql: string): void\n\t\t\tisMigrationApplied?(id: string): boolean\n\t\t\tclose?(): void\n\t\t}\n\t}\n\tpostgresClientFactory?: (connectionString: string) => {\n\t\tunsafe(query: string): Promise<unknown>\n\t\tend?(): Promise<void>\n\t}\n}\n\nexport interface BackendApplyReport {\n\tbackend: 'sqlite' | 'postgres'\n\tstatementsApplied: number\n\thistoryRecorded: boolean\n\tskipped: boolean\n}\n\nexport interface RunMigrationReport {\n\tbackends: BackendApplyReport[]\n}\n\nexport class MigrationApplyError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly backend: 'sqlite' | 'postgres',\n\t\tpublic readonly report: RunMigrationReport,\n\t) {\n\t\tsuper(message)\n\t\tthis.name = 'MigrationApplyError'\n\t}\n}\n\n/**\n * Applies migration statements to configured backends.\n */\nexport async function runMigration(options: RunMigrationOptions): Promise<RunMigrationReport> {\n\tconst report: RunMigrationReport = { backends: [] }\n\tconst migrationId = options.migrationId ?? `migration-${Date.now()}`\n\tconst fromVersion = options.fromVersion ?? 0\n\tconst toVersion = options.toVersion ?? 0\n\n\tif (options.sqlitePath) {\n\t\ttry {\n\t\t\tconst sqliteReport = await runSqliteMigration(\n\t\t\t\toptions.sqlitePath,\n\t\t\t\toptions.upStatements,\n\t\t\t\tmigrationId,\n\t\t\t\tfromVersion,\n\t\t\t\ttoVersion,\n\t\t\t\toptions.projectRoot,\n\t\t\t\toptions.sqliteDriver,\n\t\t\t)\n\t\t\treport.backends.push(sqliteReport)\n\t\t} catch (error) {\n\t\t\tthrow new MigrationApplyError((error as Error).message, 'sqlite', report)\n\t\t}\n\t}\n\n\tif (options.postgresConnectionString) {\n\t\ttry {\n\t\t\tconst postgresReport = await runPostgresMigration(\n\t\t\t\toptions.postgresConnectionString,\n\t\t\t\toptions.upStatements,\n\t\t\t\tmigrationId,\n\t\t\t\tfromVersion,\n\t\t\t\ttoVersion,\n\t\t\t\toptions.postgresClientFactory,\n\t\t\t)\n\t\t\treport.backends.push(postgresReport)\n\t\t} catch (error) {\n\t\t\tthrow new MigrationApplyError((error as Error).message, 'postgres', report)\n\t\t}\n\t}\n\n\treturn report\n}\n\nasync function runSqliteMigration(\n\tpath: string,\n\tstatements: string[],\n\tmigrationId: string,\n\tfromVersion: number,\n\ttoVersion: number,\n\tprojectRoot?: string,\n\tdriverOverride?: RunMigrationOptions['sqliteDriver'],\n): Promise<BackendApplyReport> {\n\tconst driver = driverOverride ?? (await loadSqliteDriver(projectRoot))\n\tconst db = driver.open(path)\n\tlet statementsApplied = 0\n\n\ttry {\n\t\tdb.exec('BEGIN')\n\t\tdb.exec(\n\t\t\t'CREATE TABLE IF NOT EXISTS _kora_migrations (id TEXT PRIMARY KEY NOT NULL, from_version INTEGER NOT NULL, to_version INTEGER NOT NULL, applied_at INTEGER NOT NULL)',\n\t\t)\n\t\tconst alreadyApplied =\n\t\t\ttypeof db.isMigrationApplied === 'function' ? db.isMigrationApplied(migrationId) : false\n\t\tif (alreadyApplied) {\n\t\t\tdb.exec('COMMIT')\n\t\t\treturn {\n\t\t\t\tbackend: 'sqlite',\n\t\t\t\tstatementsApplied: 0,\n\t\t\t\thistoryRecorded: true,\n\t\t\t\tskipped: true,\n\t\t\t}\n\t\t}\n\t\tfor (const statement of statements) {\n\t\t\tdb.exec(statement)\n\t\t\tstatementsApplied++\n\t\t}\n\t\tdb.exec(\n\t\t\t`INSERT OR REPLACE INTO _kora_migrations (id, from_version, to_version, applied_at) VALUES (${sqlLiteral(migrationId)}, ${fromVersion}, ${toVersion}, ${Date.now()})`,\n\t\t)\n\t\tdb.exec('COMMIT')\n\n\t\treturn {\n\t\t\tbackend: 'sqlite',\n\t\t\tstatementsApplied,\n\t\t\thistoryRecorded: true,\n\t\t\tskipped: false,\n\t\t}\n\t} catch (error) {\n\t\ttry {\n\t\t\tdb.exec('ROLLBACK')\n\t\t} catch {\n\t\t\t// best effort\n\t\t}\n\t\tthrow error\n\t} finally {\n\t\tif (typeof db.close === 'function') {\n\t\t\tdb.close()\n\t\t}\n\t}\n}\n\nasync function loadSqliteDriver(projectRoot?: string): Promise<{\n\topen(path: string): {\n\t\texec(sql: string): void\n\t\tisMigrationApplied(id: string): boolean\n\t\tclose(): void\n\t}\n}> {\n\ttry {\n\t\tconst { createRequire } = await import('node:module')\n\t\tconst requireFrom = createRequire(projectRoot ? `${projectRoot}/package.json` : import.meta.url)\n\t\tconst Database = requireFrom('better-sqlite3') as new (\n\t\t\tpath: string,\n\t\t) => {\n\t\t\texec(sql: string): void\n\t\t\tprepare(sql: string): {\n\t\t\t\tget(...params: unknown[]): { count?: number } | undefined\n\t\t\t}\n\t\t\tclose(): void\n\t\t}\n\n\t\treturn {\n\t\t\topen(path: string) {\n\t\t\t\tconst db = new Database(path)\n\t\t\t\treturn {\n\t\t\t\t\texec(sql: string) {\n\t\t\t\t\t\tdb.exec(sql)\n\t\t\t\t\t},\n\t\t\t\t\tisMigrationApplied(id: string) {\n\t\t\t\t\t\tconst row = db\n\t\t\t\t\t\t\t.prepare('SELECT COUNT(*) AS count FROM _kora_migrations WHERE id = ?')\n\t\t\t\t\t\t\t.get(id)\n\t\t\t\t\t\treturn (row?.count ?? 0) > 0\n\t\t\t\t\t},\n\t\t\t\t\tclose() {\n\t\t\t\t\t\tdb.close()\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t},\n\t\t}\n\t} catch {\n\t\tthrow new Error(\n\t\t\t'SQLite migration apply requires the \"better-sqlite3\" package in the target project dependencies.',\n\t\t)\n\t}\n}\n\nasync function runPostgresMigration(\n\tconnectionString: string,\n\tstatements: string[],\n\tmigrationId: string,\n\tfromVersion: number,\n\ttoVersion: number,\n\tclientFactoryOverride?: RunMigrationOptions['postgresClientFactory'],\n): Promise<BackendApplyReport> {\n\tconst sql =\n\t\ttypeof clientFactoryOverride === 'function'\n\t\t\t? clientFactoryOverride(connectionString)\n\t\t\t: (await loadPostgresModule()).default(connectionString)\n\tlet statementsApplied = 0\n\n\ttry {\n\t\tawait sql.unsafe('BEGIN')\n\t\tawait sql.unsafe(\n\t\t\t'CREATE TABLE IF NOT EXISTS _kora_migrations (id TEXT PRIMARY KEY, from_version INTEGER NOT NULL, to_version INTEGER NOT NULL, applied_at BIGINT NOT NULL)',\n\t\t)\n\t\tconst existing = (await sql.unsafe(\n\t\t\t`SELECT COUNT(*)::int AS count FROM _kora_migrations WHERE id = ${sqlLiteral(migrationId)}`,\n\t\t)) as Array<{ count: number }>\n\t\tif ((existing[0]?.count ?? 0) > 0) {\n\t\t\tawait sql.unsafe('COMMIT')\n\t\t\treturn {\n\t\t\t\tbackend: 'postgres',\n\t\t\t\tstatementsApplied: 0,\n\t\t\t\thistoryRecorded: true,\n\t\t\t\tskipped: true,\n\t\t\t}\n\t\t}\n\t\tfor (const statement of statements) {\n\t\t\tawait sql.unsafe(statement)\n\t\t\tstatementsApplied++\n\t\t}\n\t\tawait sql.unsafe(\n\t\t\t`INSERT INTO _kora_migrations (id, from_version, to_version, applied_at) VALUES (${sqlLiteral(migrationId)}, ${fromVersion}, ${toVersion}, ${Date.now()}) ON CONFLICT (id) DO UPDATE SET from_version = EXCLUDED.from_version, to_version = EXCLUDED.to_version, applied_at = EXCLUDED.applied_at`,\n\t\t)\n\t\tawait sql.unsafe('COMMIT')\n\n\t\treturn {\n\t\t\tbackend: 'postgres',\n\t\t\tstatementsApplied,\n\t\t\thistoryRecorded: true,\n\t\t\tskipped: false,\n\t\t}\n\t} catch (error) {\n\t\ttry {\n\t\t\tawait sql.unsafe('ROLLBACK')\n\t\t} catch {\n\t\t\t// best effort\n\t\t}\n\t\tthrow error\n\t} finally {\n\t\tif (typeof sql.end === 'function') {\n\t\t\tawait sql.end()\n\t\t}\n\t}\n}\n\nfunction sqlLiteral(value: string): string {\n\treturn `'${value.replaceAll(\"'\", \"''\")}'`\n}\n\nasync function loadPostgresModule(): Promise<{\n\tdefault: (connectionString: string) => {\n\t\tunsafe: (query: string) => Promise<unknown>\n\t\tend?: () => Promise<void>\n\t}\n}> {\n\ttry {\n\t\tconst dynamicImport = new Function('specifier', 'return import(specifier)') as (\n\t\t\tspecifier: string,\n\t\t) => Promise<unknown>\n\t\tconst mod = await dynamicImport('postgres')\n\t\tif (typeof mod === 'object' && mod !== null && 'default' in mod) {\n\t\t\treturn mod as {\n\t\t\t\tdefault: (connectionString: string) => {\n\t\t\t\t\tunsafe: (query: string) => Promise<unknown>\n\t\t\t\t\tend?: () => Promise<void>\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthrow new Error('Invalid postgres module')\n\t} catch {\n\t\tthrow new Error(\n\t\t\t'PostgreSQL migration apply requires the \"postgres\" package in the target project dependencies.',\n\t\t)\n\t}\n}\n","/**\n * Generates a stub operation-transform module for sync-time op log migration.\n */\nexport function generateOperationTransformModule(fromVersion: number, toVersion: number): string {\n\treturn [\n\t\t\"import type { Operation, OperationTransform } from '@korajs/core'\",\n\t\t'',\n\t\t'/**',\n\t\t` * Operation transforms for schema v${fromVersion} → v${toVersion}.`,\n\t\t' * Implement `transform` to rewrite or drop legacy operations during sync.',\n\t\t' * @see https://korajs.dev/docs/migrations',\n\t\t' */',\n\t\t'export const operationTransforms: OperationTransform[] = [',\n\t\t' {',\n\t\t` fromVersion: ${fromVersion},`,\n\t\t` toVersion: ${toVersion},`,\n\t\t' transform(operation: Operation): Operation | null {',\n\t\t' // Return null to drop unmigratable operations.',\n\t\t' return operation',\n\t\t' },',\n\t\t' },',\n\t\t']',\n\t\t'',\n\t].join('\\n')\n}\n","import { defineCommand } from 'citty'\nimport { createLogger } from '../../utils/logger'\n\nconst DEFAULT_SYNC_PORT = 3001\nconst STATUS_ENDPOINT = '/__kora/status'\n\ninterface ServerStatusResponse {\n\trunning: boolean\n\tconnectedClients: number\n\tport: number | null\n\ttotalOperations: number\n\tuptime: number\n\tversion: string\n\tschemaVersion: number\n\tconnectedNodeIds: string[]\n\tpeakConnections: number\n\tconnectionsTotal: number\n\toperationsReceived: number\n\toperationsSent: number\n\terrorCount: number\n}\n\n/**\n * Fetch server status from a Kora sync server.\n */\nasync function fetchServerStatus(url: string, token?: string): Promise<ServerStatusResponse> {\n\tconst statusUrl = `${url.replace(/\\/$/, '')}${STATUS_ENDPOINT}`\n\tconst response = await fetch(statusUrl, {\n\t\theaders: token ? { Authorization: `Bearer ${token}` } : undefined,\n\t})\n\tif (!response.ok) {\n\t\tthrow new Error(\n\t\t\t`Failed to fetch status from ${statusUrl}: ${response.status} ${response.statusText}`,\n\t\t)\n\t}\n\n\treturn (await response.json()) as ServerStatusResponse\n}\n\nfunction formatUptime(ms: number): string {\n\tconst seconds = Math.floor(ms / 1000)\n\tconst minutes = Math.floor(seconds / 60)\n\tconst hours = Math.floor(minutes / 60)\n\tconst days = Math.floor(hours / 24)\n\tconst parts: string[] = []\n\tif (days > 0) parts.push(`${days}d`)\n\tif (hours % 24 > 0) parts.push(`${hours % 24}h`)\n\tif (minutes % 60 > 0) parts.push(`${minutes % 60}m`)\n\tparts.push(`${seconds % 60}s`)\n\treturn parts.join(' ')\n}\n\n/**\n * The `status` command — shows the current status of a Kora sync server.\n */\nexport const statusCommand = defineCommand({\n\tmeta: {\n\t\tname: 'status',\n\t\tdescription: 'Show Kora sync server status',\n\t},\n\targs: {\n\t\turl: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Sync server URL (default: http://localhost:3001)',\n\t\t\tdefault: `http://localhost:${DEFAULT_SYNC_PORT}`,\n\t\t},\n\t\twatch: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Live-updating status (like htop)',\n\t\t\tdefault: false,\n\t\t\talias: 'w',\n\t\t},\n\t\ttoken: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Admin token (defaults to KORA_ADMIN_TOKEN)',\n\t\t},\n\t},\n\tasync run({ args }) {\n\t\tconst logger = createLogger()\n\t\tconst url = typeof args.url === 'string' ? args.url : `http://localhost:${DEFAULT_SYNC_PORT}`\n\t\tconst watch = args.watch === true\n\t\tconst token =\n\t\t\ttypeof args.token === 'string' ? args.token : (process.env.KORA_ADMIN_TOKEN ?? undefined)\n\n\t\ttry {\n\t\t\tif (watch) {\n\t\t\t\t// Live-updating mode\n\t\t\t\tconsole.clear()\n\t\t\t\tlogger.banner()\n\t\t\t\tlogger.info(`Connecting to ${url}...`)\n\n\t\t\t\tconst interval = setInterval(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst status = await fetchServerStatus(url, token)\n\t\t\t\t\t\tprintStatus(status, url, logger)\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Clear the previous status output\n\t\t\t\t\t\t// On next iteration, we'll try again\n\t\t\t\t\t}\n\t\t\t\t}, 2000)\n\n\t\t\t\t// Initial fetch\n\t\t\t\ttry {\n\t\t\t\t\tconst status = await fetchServerStatus(url, token)\n\t\t\t\t\tprintStatus(status, url, logger)\n\t\t\t\t} catch {\n\t\t\t\t\t// Will retry on interval\n\t\t\t\t}\n\n\t\t\t\t// Keep running until Ctrl+C\n\t\t\t\tawait new Promise(() => {\n\t\t\t\t\tprocess.on('SIGINT', () => {\n\t\t\t\t\t\tclearInterval(interval)\n\t\t\t\t\t\tprocess.exit(0)\n\t\t\t\t\t})\n\t\t\t\t\tprocess.on('SIGTERM', () => {\n\t\t\t\t\t\tclearInterval(interval)\n\t\t\t\t\t\tprocess.exit(0)\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tconst status = await fetchServerStatus(url, token)\n\t\t\t\tprintStatus(status, url, logger)\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(`Failed to connect to ${url}`)\n\t\t\tif (error instanceof Error) {\n\t\t\t\tlogger.error(error.message)\n\t\t\t}\n\t\t\tlogger.blank()\n\t\t\tlogger.step('Make sure the Kora sync server is running.')\n\t\t\tlogger.step('Start it with: kora dev')\n\t\t\tprocess.exit(1)\n\t\t}\n\t},\n})\n\nfunction printStatus(\n\tstatus: ServerStatusResponse,\n\turl: string,\n\tlogger: ReturnType<typeof createLogger>,\n): void {\n\tconsole.clear()\n\tlogger.banner()\n\tlogger.info(`Kora Sync Server — ${url}`)\n\tlogger.blank()\n\n\tif (!status.running) {\n\t\tlogger.error('Server is not running')\n\t\treturn\n\t}\n\n\t// Server info\n\tlogger.step(`Status: Running (uptime: ${formatUptime(status.uptime)}) — v${status.version}`)\n\tlogger.step(`Schema: v${status.schemaVersion}`)\n\tlogger.blank()\n\n\t// Connections\n\tlogger.step(`Connections: ${status.connectedClients} connected`)\n\tlogger.step(` Peak: ${status.peakConnections}`)\n\tlogger.step(` Total: ${status.connectionsTotal}`)\n\n\tif (status.connectedNodeIds.length > 0) {\n\t\tlogger.step(' Active nodes:')\n\t\tfor (const nodeId of status.connectedNodeIds) {\n\t\t\tlogger.step(` • ${nodeId}`)\n\t\t}\n\t}\n\tlogger.blank()\n\n\t// Operations\n\tlogger.step('Operations:')\n\tlogger.step(` Received: ${status.operationsReceived.toLocaleString()}`)\n\tlogger.step(` Sent: ${status.operationsSent.toLocaleString()}`)\n\tlogger.step(` Total: ${status.totalOperations.toLocaleString()}`)\n\tlogger.blank()\n\n\t// Errors\n\tif (status.errorCount > 0) {\n\t\tlogger.warn(`Errors: ${status.errorCount}`)\n\t} else {\n\t\tlogger.step('Errors: 0')\n\t}\n}\n","import { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { defineCommand } from 'citty'\nimport { createLogger } from '../../utils/logger'\n\n/**\n * `kora studio` — the visual window into Kora's data plane.\n *\n * FILE mode (`--db path`): read-only inspection of any Kora database —\n * records with per-field last writers, operation history, causal DAG, time\n * travel, merge audit, sync state.\n *\n * LAB mode (`--lab`): an interactive multi-device sync laboratory running\n * REAL stores, sync engines, and a real server in-process. Create devices,\n * edit data on each, disconnect them, inject chaos (drops, duplicates,\n * reordering, latency), and watch conflicts resolve and devices converge —\n * live, with evidence.\n */\nexport const studioCommand = defineCommand({\n\tmeta: {\n\t\tname: 'studio',\n\t\tdescription: 'Kora Studio: visualize records, operations, and sync — or run the sync lab',\n\t},\n\targs: {\n\t\tdb: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Path to a Kora SQLite database file (file mode, read-only)',\n\t\t},\n\t\tlab: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Start the interactive multi-device sync laboratory',\n\t\t},\n\t\tconnect: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Spectator mode: WebSocket URL of a live Kora sync server (read-only replica)',\n\t\t},\n\t\ttoken: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Spectator mode: bearer token for the sync auth handshake',\n\t\t},\n\t\tdevices: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Lab mode: number of initial devices (default 2)',\n\t\t},\n\t\tschema: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Lab mode: path to a schema file (defaults to a built-in demo schema)',\n\t\t},\n\t\tport: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Port for the Studio UI (default 4321, 0 for a random free port)',\n\t\t},\n\t},\n\tasync run({ args }) {\n\t\tconst logger = createLogger()\n\n\t\tconst port = args.port !== undefined ? Number.parseInt(args.port, 10) : 4321\n\t\tif (Number.isNaN(port) || port < 0 || port > 65535) {\n\t\t\tthrow new Error(`Invalid port \"${args.port}\"`)\n\t\t}\n\n\t\tconst { startStudioServer } = await import('./studio-server')\n\n\t\tif (typeof args.connect === 'string') {\n\t\t\t// SPECTATOR: live read-only replica of a production sync server.\n\t\t\tif (typeof args.schema !== 'string') {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Spectator mode needs your schema to materialize records: kora studio --connect wss://… --schema ./kora/schema.ts',\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst { loadSchemaDefinition } = await import('../migrate/schema-loader')\n\t\t\tconst schema = await loadSchemaDefinition(resolve(process.cwd(), args.schema), process.cwd())\n\n\t\t\tconst { SpectatorManager } = await import('./spectator-manager')\n\t\t\tconst spectator = new SpectatorManager({\n\t\t\t\turl: args.connect,\n\t\t\t\tschema,\n\t\t\t\t...(typeof args.token === 'string' ? { token: args.token } : {}),\n\t\t\t})\n\t\t\tawait spectator.start()\n\t\t\tconst server = await startStudioServer({ port, spectator })\n\n\t\t\tlogger.banner()\n\t\t\tlogger.success(`Kora Studio SPECTATOR running at ${server.url}`)\n\t\t\tlogger.step(`Watching ${args.connect} (read-only replica — nothing is ever pushed)`)\n\t\t\tlogger.step('Press Ctrl+C to stop.')\n\n\t\t\tconst shutdown = async (): Promise<void> => {\n\t\t\t\tawait server.close()\n\t\t\t\tawait spectator.close()\n\t\t\t\tprocess.exit(0)\n\t\t\t}\n\t\t\tprocess.on('SIGINT', () => void shutdown())\n\t\t\tprocess.on('SIGTERM', () => void shutdown())\n\t\t\treturn\n\t\t}\n\n\t\tif (args.lab) {\n\t\t\tconst { LabManager, defaultLabSchema } = await import('./lab-manager')\n\n\t\t\tlet schema = defaultLabSchema()\n\t\t\tif (typeof args.schema === 'string') {\n\t\t\t\tconst { loadSchemaDefinition } = await import('../migrate/schema-loader')\n\t\t\t\tschema = await loadSchemaDefinition(resolve(process.cwd(), args.schema), process.cwd())\n\t\t\t}\n\n\t\t\tconst initialDevices =\n\t\t\t\targs.devices !== undefined ? Math.max(1, Number.parseInt(args.devices, 10) || 2) : 2\n\n\t\t\tconst lab = new LabManager(schema)\n\t\t\tawait lab.start(initialDevices)\n\t\t\tconst server = await startStudioServer({ port, lab })\n\n\t\t\tlogger.banner()\n\t\t\tlogger.success(`Kora Studio LAB running at ${server.url}`)\n\t\t\tlogger.step(`${initialDevices} device(s) started against an in-process sync server.`)\n\t\t\tlogger.step('Everything in the lab is throwaway — experiment freely.')\n\t\t\tlogger.step('Press Ctrl+C to stop.')\n\n\t\t\tconst shutdown = async (): Promise<void> => {\n\t\t\t\tawait server.close()\n\t\t\t\tawait lab.close()\n\t\t\t\tprocess.exit(0)\n\t\t\t}\n\t\t\tprocess.on('SIGINT', () => void shutdown())\n\t\t\tprocess.on('SIGTERM', () => void shutdown())\n\t\t\treturn\n\t\t}\n\n\t\tif (typeof args.db !== 'string') {\n\t\t\tthrow new Error(\n\t\t\t\t'Pass --db <path> to inspect a database, --lab for the sync laboratory, or --connect <wss url> for live spectator mode.',\n\t\t\t)\n\t\t}\n\t\tconst dbPath = resolve(process.cwd(), args.db)\n\t\tif (!existsSync(dbPath)) {\n\t\t\tthrow new Error(`Database file not found: ${dbPath}`)\n\t\t}\n\n\t\tconst server = await startStudioServer({ port, dbPath })\n\n\t\tlogger.banner()\n\t\tlogger.success(`Kora Studio running at ${server.url}`)\n\t\tlogger.step(`Database: ${dbPath} (read-only)`)\n\t\tlogger.step('Press Ctrl+C to stop.')\n\n\t\tconst shutdown = async (): Promise<void> => {\n\t\t\tawait server.close()\n\t\t\tprocess.exit(0)\n\t\t}\n\t\tprocess.on('SIGINT', () => void shutdown())\n\t\tprocess.on('SIGTERM', () => void shutdown())\n\t},\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,iBAAAA,iBAAe,eAAe;;;ACAvC,SAAS,UAAU,iBAAiB;AACpC,OAAqB;AACrB,SAAS,qBAAqB;AAG9B,IAAM,oBAAoB;AAK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G,UAAU,MAAM,KAAKC,UAAS,CAAC;AAC1C,cAAQ,GAAG,WAAW,MAAM,KAAKA,UAAS,CAAC;AAC3C;AAAA,IACD;AAEA,QAAI,OAAO,KAAK,OAAO,UAAU;AAChC,YAAM,IAAI;AAAA,QACT;AAAA,MACD;AAAA,IACD;AACA,UAAM,SAASF,SAAQ,QAAQ,IAAI,GAAG,KAAK,EAAE;AAC7C,QAAI,CAACG,YAAW,MAAM,GAAG;AACxB,YAAM,IAAI,MAAM,4BAA4B,MAAM,EAAE;AAAA,IACrD;AAEA,UAAM,SAAS,MAAM,kBAAkB,EAAE,MAAM,OAAO,CAAC;AAEvD,WAAO,OAAO;AACd,WAAO,QAAQ,0BAA0B,OAAO,GAAG,EAAE;AACrD,WAAO,KAAK,aAAa,MAAM,cAAc;AAC7C,WAAO,KAAK,uBAAuB;AAEnC,UAAM,WAAW,YAA2B;AAC3C,YAAM,OAAO,MAAM;AACnB,cAAQ,KAAK,CAAC;AAAA,IACf;AACA,YAAQ,GAAG,UAAU,MAAM,KAAK,SAAS,CAAC;AAC1C,YAAQ,GAAG,WAAW,MAAM,KAAK,SAAS,CAAC;AAAA,EAC5C;AACD,CAAC;;;AlB3ID,IAAM,OAAOC,gBAAc;AAAA,EAC1B,MAAM;AAAA,IACL,MAAM;AAAA,IACN,aAAa;AAAA,EACd;AAAA,EACA,aAAa;AAAA,IACZ,aAAa;AAAA,IACb,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,MAAM;AAAA,IACN,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,QAAQ;AAAA,EACT;AACD,CAAC;AAED,QAAQ,IAAI;","names":["defineCommand","defineCommand","join","loaded","join","resolve","defineCommand","access","join","resolve","defineCommand","resolve","spawn","join","join","resolve","spawn","defineCommand","join","resolve","access","defineCommand","access","readFile","join","resolve","resolve","access","join","readFile","defineCommand","writeFile","resolve","defineCommand","defineCommand","resolve","writeFile","defineCommand","DEFAULT_SYNC_PORT","defineCommand","mkdir","readFile","writeFile","dirname","join","resolve","defineCommand","sqlLiteral","defineCommand","resolve","join","mkdir","readFile","dirname","writeFile","defineCommand","DEFAULT_SYNC_PORT","STATUS_ENDPOINT","defineCommand","watch","existsSync","resolve","defineCommand","defineCommand","loadSchemaDefinition","resolve","server","shutdown","existsSync","defineCommand"]}
|
|
1
|
+
{"version":3,"sources":["../src/bin.ts","../src/commands/backup/backup-command.ts","../src/commands/compact/compact-command.ts","../src/commands/dev/kora-config.ts","../src/commands/dev/dev-command.ts","../src/commands/dev/process-manager.ts","../src/commands/dev/schema-watcher.ts","../src/commands/doctor/doctor-command.ts","../src/commands/doctor/doctor-checks.ts","../src/commands/generate/generate-command.ts","../src/commands/generate/hook-generator.ts","../src/commands/logs/logs-command.ts","../src/commands/migrate/migrate-command.ts","../src/commands/migrate/migration-generator.ts","../src/commands/migrate/schema-differ.ts","../src/commands/migrate/table-evolution-directive.ts","../src/commands/migrate/value-domain-directive.ts","../src/commands/migrate/migration-runner.ts","../src/commands/migrate/operation-transform-generator.ts","../src/commands/status/status-command.ts","../src/commands/studio/studio-command.ts"],"sourcesContent":["import { defineCommand, runMain } from 'citty'\nimport { agentsCommand } from './commands/agents/agents-command'\nimport { backupCommand } from './commands/backup/backup-command'\nimport { compactCommand } from './commands/compact/compact-command'\nimport { createCommand } from './commands/create/create-command'\nimport { deployCommand } from './commands/deploy/deploy-command'\nimport { devCommand } from './commands/dev/dev-command'\nimport { doctorCommand } from './commands/doctor/doctor-command'\nimport { generateCommand } from './commands/generate/generate-command'\nimport { logsCommand } from './commands/logs/logs-command'\nimport { migrateCommand } from './commands/migrate/migrate-command'\nimport { statusCommand } from './commands/status/status-command'\nimport { studioCommand } from './commands/studio/studio-command'\n\nconst main = defineCommand({\n\tmeta: {\n\t\tname: 'kora',\n\t\tdescription: 'Kora.js, the offline-first application framework',\n\t},\n\tsubCommands: {\n\t\t'agents-md': agentsCommand,\n\t\tbackup: backupCommand,\n\t\tcompact: compactCommand,\n\t\tcreate: createCommand,\n\t\tdev: devCommand,\n\t\tdoctor: doctorCommand,\n\t\tdeploy: deployCommand,\n\t\tgenerate: generateCommand,\n\t\tlogs: logsCommand,\n\t\tmigrate: migrateCommand,\n\t\tstatus: statusCommand,\n\t\tstudio: studioCommand,\n\t},\n})\n\nrunMain(main)\n","import { readFile, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { defineCommand } from 'citty'\nimport { createLogger } from '../../utils/logger'\n\nconst DEFAULT_SYNC_PORT = 3001\n\n/**\n * The `backup` command — creates and restores Kora sync server backups.\n */\nexport const backupCommand = defineCommand({\n\tmeta: {\n\t\tname: 'backup',\n\t\tdescription: 'Backup and restore Kora sync server data',\n\t},\n\tsubCommands: {\n\t\tcreate: defineCommand({\n\t\t\tmeta: {\n\t\t\t\tname: 'create',\n\t\t\t\tdescription: 'Create a backup of the sync server',\n\t\t\t},\n\t\t\targs: {\n\t\t\t\turl: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Sync server URL (default: http://localhost:3001)',\n\t\t\t\t\tdefault: `http://localhost:${DEFAULT_SYNC_PORT}`,\n\t\t\t\t},\n\t\t\t\tout: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Output file path (default: kora-backup-<timestamp>.kora)',\n\t\t\t\t},\n\t\t\t\ttoken: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Backup token (defaults to KORA_BACKUP_TOKEN or KORA_ADMIN_TOKEN)',\n\t\t\t\t},\n\t\t\t},\n\t\t\tasync run({ args }) {\n\t\t\t\tconst logger = createLogger()\n\t\t\t\tconst url =\n\t\t\t\t\ttypeof args.url === 'string' ? args.url : `http://localhost:${DEFAULT_SYNC_PORT}`\n\t\t\t\tconst outFile = typeof args.out === 'string' ? args.out : `kora-backup-${Date.now()}.kora`\n\t\t\t\tconst token =\n\t\t\t\t\ttypeof args.token === 'string'\n\t\t\t\t\t\t? args.token\n\t\t\t\t\t\t: (process.env.KORA_BACKUP_TOKEN ?? process.env.KORA_ADMIN_TOKEN)\n\n\t\t\t\tlogger.banner()\n\t\t\t\tlogger.info(`Exporting backup from ${url}...`)\n\n\t\t\t\ttry {\n\t\t\t\t\tconst backupUrl = `${url.replace(/\\/$/, '')}/__kora/backup/export`\n\t\t\t\t\tconst response = await fetch(backupUrl, {\n\t\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\t\theaders: token ? { Authorization: `Bearer ${token}` } : undefined,\n\t\t\t\t\t})\n\n\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\tconst error = await response.json().catch(() => ({ message: response.statusText }))\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Backup failed: ${(error as { message: string }).message ?? response.statusText}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\n\t\t\t\t\tconst buffer = await response.arrayBuffer()\n\t\t\t\t\tawait writeFile(outFile, new Uint8Array(buffer))\n\n\t\t\t\t\tconst size = (buffer.byteLength / 1024).toFixed(1)\n\t\t\t\t\tlogger.success(`Backup saved to ${outFile} (${size} KB)`)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error('Backup failed')\n\t\t\t\t\tif (error instanceof Error) logger.error(error.message)\n\t\t\t\t\tlogger.blank()\n\t\t\t\t\tlogger.step('Make sure the Kora sync server is running.')\n\t\t\t\t\tprocess.exit(1)\n\t\t\t\t}\n\t\t\t},\n\t\t}),\n\n\t\trestore: defineCommand({\n\t\t\tmeta: {\n\t\t\t\tname: 'restore',\n\t\t\t\tdescription: 'Restore a backup to the sync server',\n\t\t\t},\n\t\t\targs: {\n\t\t\t\tfile: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Backup file path',\n\t\t\t\t\trequired: true,\n\t\t\t\t},\n\t\t\t\turl: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Sync server URL (default: http://localhost:3001)',\n\t\t\t\t\tdefault: `http://localhost:${DEFAULT_SYNC_PORT}`,\n\t\t\t\t},\n\t\t\t\tmerge: {\n\t\t\t\t\ttype: 'boolean',\n\t\t\t\t\tdescription: 'Merge with existing data instead of replacing',\n\t\t\t\t\tdefault: false,\n\t\t\t\t},\n\t\t\t\ttoken: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Backup token (defaults to KORA_BACKUP_TOKEN or KORA_ADMIN_TOKEN)',\n\t\t\t\t},\n\t\t\t},\n\t\t\tasync run({ args }) {\n\t\t\t\tconst logger = createLogger()\n\t\t\t\tconst filePath = typeof args.file === 'string' ? args.file : ''\n\t\t\t\tconst url =\n\t\t\t\t\ttypeof args.url === 'string' ? args.url : `http://localhost:${DEFAULT_SYNC_PORT}`\n\t\t\t\tconst merge = args.merge === true\n\t\t\t\tconst token =\n\t\t\t\t\ttypeof args.token === 'string'\n\t\t\t\t\t\t? args.token\n\t\t\t\t\t\t: (process.env.KORA_BACKUP_TOKEN ?? process.env.KORA_ADMIN_TOKEN)\n\n\t\t\t\tlogger.banner()\n\t\t\t\tlogger.info(`Restoring backup from ${filePath} to ${url}...`)\n\n\t\t\t\ttry {\n\t\t\t\t\tconst data = await readFile(filePath)\n\t\t\t\t\tconst restoreUrl = `${url.replace(/\\/$/, '')}/__kora/backup/import?merge=${merge}`\n\n\t\t\t\t\tconst response = await fetch(restoreUrl, {\n\t\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\t\theaders: token ? { Authorization: `Bearer ${token}` } : undefined,\n\t\t\t\t\t\tbody: data,\n\t\t\t\t\t})\n\n\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\tconst error = await response.json().catch(() => ({ message: response.statusText }))\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Restore failed: ${(error as { message: string }).message ?? response.statusText}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\n\t\t\t\t\tconst result = (await response.json()) as {\n\t\t\t\t\t\toperationsRestored: number\n\t\t\t\t\t\tsuccess: boolean\n\t\t\t\t\t\tduration?: number\n\t\t\t\t\t}\n\n\t\t\t\t\tif (result.success) {\n\t\t\t\t\t\tlogger.success(\n\t\t\t\t\t\t\t`Restored ${result.operationsRestored} operations${result.duration ? ` in ${result.duration}ms` : ''}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger.error('Restore completed with errors')\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error('Restore failed')\n\t\t\t\t\tif (error instanceof Error) logger.error(error.message)\n\t\t\t\t\tprocess.exit(1)\n\t\t\t\t}\n\t\t\t},\n\t\t}),\n\n\t\tinfo: defineCommand({\n\t\t\tmeta: {\n\t\t\t\tname: 'info',\n\t\t\t\tdescription: 'Show backup file information',\n\t\t\t},\n\t\t\targs: {\n\t\t\t\tfile: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Backup file path',\n\t\t\t\t\trequired: true,\n\t\t\t\t},\n\t\t\t},\n\t\t\tasync run({ args }) {\n\t\t\t\tconst logger = createLogger()\n\t\t\t\tconst filePath = typeof args.file === 'string' ? args.file : ''\n\n\t\t\t\ttry {\n\t\t\t\t\tconst data = await readFile(filePath)\n\t\t\t\t\tconst { readBackupManifest } = await import('@korajs/store')\n\n\t\t\t\t\tconst manifest = readBackupManifest(\n\t\t\t\t\t\tnew Uint8Array(data.buffer, data.byteOffset, data.byteLength),\n\t\t\t\t\t)\n\n\t\t\t\t\tlogger.banner()\n\t\t\t\t\tlogger.info(`Backup: ${filePath}`)\n\t\t\t\t\tlogger.blank()\n\t\t\t\t\tlogger.step(`Created: ${new Date(manifest.createdAt).toISOString()}`)\n\t\t\t\t\tlogger.step(`Node ID: ${manifest.nodeId}`)\n\t\t\t\t\tlogger.step(`Schema: v${manifest.schemaVersion}`)\n\t\t\t\t\tlogger.step(`Operations: ${manifest.operationCount.toLocaleString()}`)\n\t\t\t\t\tlogger.step(`Collections: ${manifest.collections.join(', ') || '(none)'}`)\n\t\t\t\t\tlogger.step(`Checksum: ${manifest.checksum.slice(0, 16)}...`)\n\t\t\t\t\tlogger.blank()\n\t\t\t\t\tlogger.step(`Format version: ${manifest.version}`)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error('Failed to read backup file')\n\t\t\t\t\tif (error instanceof Error) logger.error(error.message)\n\t\t\t\t\tprocess.exit(1)\n\t\t\t\t}\n\t\t\t},\n\t\t}),\n\t},\n})\n","import { resolve } from 'node:path'\nimport { defineCommand } from 'citty'\nimport { InvalidProjectError } from '../../errors'\nimport { findProjectRoot } from '../../utils/fs-helpers'\nimport { createLogger } from '../../utils/logger'\nimport { loadKoraConfig } from '../dev/kora-config'\nimport { loadSchemaDefinition } from '../migrate/schema-loader'\n\n/**\n * Compact the local client operation log (materialized rows are the baseline).\n */\nexport const compactCommand = defineCommand({\n\tmeta: {\n\t\tname: 'compact',\n\t\tdescription: 'Compact the local Kora operation log after server ack',\n\t},\n\targs: {\n\t\tdb: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Path to the local SQLite database (required)',\n\t\t},\n\t\tschema: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Path to schema file',\n\t\t},\n\t\tstrategy: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Compaction strategy: after-ack | after-days | never',\n\t\t\tdefault: 'after-ack',\n\t\t},\n\t\tdays: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Age threshold when strategy is after-days',\n\t\t\tdefault: '30',\n\t\t},\n\t},\n\tasync run({ args }) {\n\t\tconst logger = createLogger()\n\t\tconst projectRoot = await findProjectRoot()\n\t\tif (!projectRoot) {\n\t\t\tthrow new InvalidProjectError(process.cwd())\n\t\t}\n\n\t\tconst dbPath = typeof args.db === 'string' ? resolve(projectRoot, args.db) : undefined\n\t\tif (!dbPath) {\n\t\t\tthrow new Error('Missing --db <path> to the local SQLite database file.')\n\t\t}\n\n\t\tconst config = await loadKoraConfig(projectRoot)\n\t\tconst schemaPath =\n\t\t\ttypeof args.schema === 'string'\n\t\t\t\t? resolve(projectRoot, args.schema)\n\t\t\t\t: typeof config?.schema === 'string'\n\t\t\t\t\t? resolve(projectRoot, config.schema)\n\t\t\t\t\t: undefined\n\t\tif (!schemaPath) {\n\t\t\tthrow new Error('Could not resolve schema path. Pass --schema <path>.')\n\t\t}\n\n\t\tconst schema = await loadSchemaDefinition(schemaPath, projectRoot)\n\t\tconst { BetterSqlite3Adapter } = await import('@korajs/store/better-sqlite3')\n\t\tconst { Store } = await import('@korajs/store')\n\n\t\tconst strategyName = typeof args.strategy === 'string' ? args.strategy : 'after-ack'\n\t\tconst days = Number.parseInt(typeof args.days === 'string' ? args.days : '30', 10)\n\n\t\tconst store = new Store({\n\t\t\tschema,\n\t\t\tadapter: new BetterSqlite3Adapter(dbPath),\n\t\t})\n\t\tawait store.open()\n\n\t\tlet result: { deletedCount: number; watermark: Map<string, number> }\n\t\tif (strategyName === 'never') {\n\t\t\tresult = await store.compact({ mode: 'never' })\n\t\t} else if (strategyName === 'after-days') {\n\t\t\tresult = await store.compact({ mode: 'after-days', days })\n\t\t} else if (strategyName === 'after-ack') {\n\t\t\tresult = await store.compact({ mode: 'after-ack' })\n\t\t} else {\n\t\t\tawait store.close()\n\t\t\tthrow new Error(`Unknown strategy \"${strategyName}\". Use after-ack, after-days, or never.`)\n\t\t}\n\n\t\tawait store.close()\n\n\t\tlogger.banner()\n\t\tlogger.success(`Compacted ${result.deletedCount} operation log entries.`)\n\t\tfor (const [nodeId, seq] of result.watermark) {\n\t\t\tlogger.step(` ${nodeId}: seq <= ${seq}`)\n\t\t}\n\t},\n})\n","import { spawn } from 'node:child_process'\nimport { access } from 'node:fs/promises'\nimport { extname, join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { hasTsxInstalled } from '../../utils/fs-helpers'\n\nexport interface KoraConfigFile {\n\tschema?: string\n\tdev?: {\n\t\tport?: number\n\t\tsync?:\n\t\t\t| boolean\n\t\t\t| {\n\t\t\t\t\tenabled?: boolean\n\t\t\t\t\tport?: number\n\t\t\t\t\tstore?:\n\t\t\t\t\t\t| 'memory'\n\t\t\t\t\t\t| 'sqlite'\n\t\t\t\t\t\t| 'postgres'\n\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\ttype: 'memory'\n\t\t\t\t\t\t }\n\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\ttype: 'sqlite'\n\t\t\t\t\t\t\t\tfilename?: string\n\t\t\t\t\t\t }\n\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\ttype: 'postgres'\n\t\t\t\t\t\t\t\tconnectionString: string\n\t\t\t\t\t\t }\n\t\t\t }\n\t\twatch?:\n\t\t\t| boolean\n\t\t\t| {\n\t\t\t\t\tenabled?: boolean\n\t\t\t\t\tdebounceMs?: number\n\t\t\t }\n\t}\n}\n\nconst CONFIG_CANDIDATES = [\n\t'kora.config.ts',\n\t'kora.config.mts',\n\t'kora.config.cts',\n\t'kora.config.js',\n\t'kora.config.mjs',\n\t'kora.config.cjs',\n]\n\n/**\n * Loads `kora.config.*` from the project root if present.\n */\nexport async function loadKoraConfig(projectRoot: string): Promise<KoraConfigFile | null> {\n\tconst configPath = await findKoraConfigFile(projectRoot)\n\tif (!configPath) return null\n\n\tconst ext = extname(configPath)\n\tif (ext === '.ts' || ext === '.mts' || ext === '.cts') {\n\t\tconst loaded = await loadTypeScriptConfig(configPath, projectRoot)\n\t\treturn toConfigObject(loaded)\n\t}\n\n\tconst loaded = await import(pathToFileURL(configPath).href)\n\treturn toConfigObject(loaded)\n}\n\nasync function findKoraConfigFile(projectRoot: string): Promise<string | null> {\n\tfor (const file of CONFIG_CANDIDATES) {\n\t\tconst candidate = join(projectRoot, file)\n\t\ttry {\n\t\t\tawait access(candidate)\n\t\t\treturn candidate\n\t\t} catch {\n\t\t\t// continue\n\t\t}\n\t}\n\n\treturn null\n}\n\nasync function loadTypeScriptConfig(configPath: string, projectRoot: string): Promise<unknown> {\n\tif (!(await hasTsxInstalled(projectRoot))) {\n\t\tthrow new Error(\n\t\t\t`Found TypeScript config at ${configPath}, but \"tsx\" is not installed in this project. Install tsx or use kora.config.js.`,\n\t\t)\n\t}\n\n\t// Use process.execPath (node) + --import tsx to avoid .cmd shim issues on Windows.\n\t// Use dynamic import() with .then() since --eval may run as CJS (no top-level await).\n\tconst script =\n\t\t'const configPath = process.argv[process.argv.length - 1];' +\n\t\t\"import('node:url').then(u => import(u.pathToFileURL(configPath).href))\" +\n\t\t'.then(mod => { const v = mod.default ?? mod; process.stdout.write(JSON.stringify(v)) })' +\n\t\t'.catch(e => { process.stderr.write(String(e)); process.exit(1) })'\n\n\tconst output = await runCommand(\n\t\tprocess.execPath,\n\t\t['--import', 'tsx', '--eval', script, configPath],\n\t\tprojectRoot,\n\t)\n\n\ttry {\n\t\treturn JSON.parse(output)\n\t} catch {\n\t\tthrow new Error(`Failed to parse ${configPath} output as JSON.`)\n\t}\n}\n\nasync function runCommand(command: string, args: string[], cwd: string): Promise<string> {\n\treturn await new Promise<string>((resolve, reject) => {\n\t\tconst child = spawn(command, args, {\n\t\t\tcwd,\n\t\t\tstdio: ['ignore', 'pipe', 'pipe'],\n\t\t\tenv: process.env,\n\t\t})\n\n\t\tlet stdout = ''\n\t\tlet stderr = ''\n\n\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\tstdout += chunk.toString('utf-8')\n\t\t})\n\n\t\tchild.stderr?.on('data', (chunk: Buffer) => {\n\t\t\tstderr += chunk.toString('utf-8')\n\t\t})\n\n\t\tchild.on('error', (error) => {\n\t\t\treject(error)\n\t\t})\n\n\t\tchild.on('exit', (code) => {\n\t\t\tif (code === 0) {\n\t\t\t\tresolve(stdout.trim())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\treject(new Error(`Failed to load kora config (exit ${code ?? 'unknown'}): ${stderr.trim()}`))\n\t\t})\n\t})\n}\n\nfunction toConfigObject(mod: unknown): KoraConfigFile {\n\tif (typeof mod !== 'object' || mod === null) {\n\t\tthrow new Error('kora config must export an object.')\n\t}\n\n\tconst value = (mod as Record<string, unknown>).default ?? mod\n\tif (typeof value !== 'object' || value === null || Array.isArray(value)) {\n\t\tthrow new Error('kora config must export an object.')\n\t}\n\n\treturn value as KoraConfigFile\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { access } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { resolve } from 'node:path'\nimport { defineCommand } from 'citty'\nimport { DevServerError, InvalidProjectError } from '../../errors'\nimport {\n\tfindProjectRoot,\n\tfindSchemaFile,\n\thasTsxInstalled,\n\tresolveProjectBinaryEntryPoint,\n} from '../../utils/fs-helpers'\nimport { createLogger } from '../../utils/logger'\nimport { loadKoraConfig } from './kora-config'\nimport type { KoraConfigFile } from './kora-config'\nimport { ProcessManager } from './process-manager'\nimport type { ManagedProcessConfig } from './process-manager'\nimport { SchemaWatcher } from './schema-watcher'\n\ninterface ManagedSyncStoreConfig {\n\ttype: 'memory' | 'sqlite' | 'postgres'\n\tfilename?: string\n\tconnectionString?: string\n}\n\n/**\n * The `dev` command — starts the Kora development environment.\n */\nexport const devCommand = defineCommand({\n\tmeta: {\n\t\tname: 'dev',\n\t\tdescription: 'Start the Kora development environment',\n\t},\n\targs: {\n\t\tport: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Vite dev server port',\n\t\t},\n\t\t'sync-port': {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Kora sync server port',\n\t\t},\n\t\t'no-sync': {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Disable sync server startup',\n\t\t\tdefault: false,\n\t\t},\n\t\t'no-watch': {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Disable schema file watching',\n\t\t\tdefault: false,\n\t\t},\n\t},\n\tasync run({ args }) {\n\t\tconst logger = createLogger()\n\n\t\tconst projectRoot = await findProjectRoot()\n\t\tif (!projectRoot) {\n\t\t\tthrow new InvalidProjectError(process.cwd())\n\t\t}\n\n\t\tloadProjectEnv(projectRoot)\n\n\t\tconst config = await loadKoraConfig(projectRoot)\n\t\tconst vitePort = typeof args.port === 'string' ? args.port : String(config?.dev?.port ?? 5173)\n\t\tconst syncPortFromConfig =\n\t\t\ttypeof config?.dev?.sync === 'object' && typeof config.dev.sync.port === 'number'\n\t\t\t\t? config.dev.sync.port\n\t\t\t\t: 3001\n\t\tconst syncPort =\n\t\t\ttypeof args['sync-port'] === 'string' ? args['sync-port'] : String(syncPortFromConfig)\n\n\t\tconst configSyncEnabled =\n\t\t\tconfig?.dev?.sync === undefined ||\n\t\t\tconfig.dev.sync === true ||\n\t\t\t(typeof config.dev.sync === 'object' && config.dev.sync.enabled !== false)\n\n\t\tconst configWatchEnabled =\n\t\t\tconfig?.dev?.watch === undefined ||\n\t\t\tconfig.dev.watch === true ||\n\t\t\t(typeof config.dev.watch === 'object' && config.dev.watch.enabled !== false)\n\n\t\tconst watchDebounceMs =\n\t\t\ttypeof config?.dev?.watch === 'object' && typeof config.dev.watch.debounceMs === 'number'\n\t\t\t\t? config.dev.watch.debounceMs\n\t\t\t\t: 300\n\n\t\tconst viteEntryPoint = await resolveProjectBinaryEntryPoint(projectRoot, 'vite', 'vite')\n\t\tif (!viteEntryPoint) {\n\t\t\tthrow new DevServerError('vite', join(projectRoot, 'node_modules', '.bin', 'vite'))\n\t\t}\n\n\t\tconst syncServerFile = await findSyncServerFile(projectRoot)\n\t\tlet managedSyncStore = normalizeManagedSyncStore(config, projectRoot)\n\t\tconst postgresEnvRequested = isPostgresEnvRequested(config)\n\t\tconst syncAllowed = args['no-sync'] !== true && configSyncEnabled\n\t\tlet shouldStartSync = syncAllowed && (syncServerFile !== null || managedSyncStore !== null)\n\n\t\tlet hasTsx = false\n\t\tif (shouldStartSync && syncServerFile !== null) {\n\t\t\thasTsx = await hasTsxInstalled(projectRoot)\n\t\t\tif (!hasTsx) {\n\t\t\t\tlogger.warn('Sync server detected, but \"tsx\" is not installed. Skipping sync.')\n\t\t\t}\n\t\t}\n\n\t\tif (shouldStartSync && syncServerFile === null && managedSyncStore) {\n\t\t\tconst hasServerPackage = await fileExists(\n\t\t\t\tjoin(projectRoot, 'node_modules', '@korajs', 'server', 'package.json'),\n\t\t\t)\n\t\t\tif (!hasServerPackage) {\n\t\t\t\tlogger.warn(\n\t\t\t\t\t'Managed sync is configured, but @korajs/server is not installed. Install it or add server.ts.',\n\t\t\t\t)\n\t\t\t\tmanagedSyncStore = null\n\t\t\t\tshouldStartSync = syncAllowed && (syncServerFile !== null || managedSyncStore !== null)\n\t\t\t}\n\t\t}\n\n\t\tif (\n\t\t\tsyncAllowed &&\n\t\t\tsyncServerFile === null &&\n\t\t\tmanagedSyncStore === null &&\n\t\t\tpostgresEnvRequested\n\t\t) {\n\t\t\tlogger.warn(\n\t\t\t\t'Managed postgres sync requested but no connection string found. Set dev.sync.store.connectionString or DATABASE_URL.',\n\t\t\t)\n\t\t}\n\n\t\tlet configuredSchemaPath: string | null = null\n\t\tif (typeof config?.schema === 'string') {\n\t\t\tconst candidate = resolve(projectRoot, config.schema)\n\t\t\tif (await fileExists(candidate)) {\n\t\t\t\tconfiguredSchemaPath = candidate\n\t\t\t} else {\n\t\t\t\tlogger.warn(\n\t\t\t\t\t`Configured schema file not found: ${candidate}. Falling back to auto-detection.`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tconst schemaPath = configuredSchemaPath ?? (await findSchemaFile(projectRoot))\n\t\tconst watchEnabled = args['no-watch'] !== true && configWatchEnabled && schemaPath !== null\n\n\t\tconst processManager = new ProcessManager()\n\t\tlet schemaWatcher: SchemaWatcher | null = null\n\t\tlet shuttingDown = false\n\t\tlet resolveFinished: (() => void) | undefined\n\t\tconst finished = new Promise<void>((resolve) => {\n\t\t\tresolveFinished = resolve\n\t\t})\n\n\t\tconst onManagedProcessExit = () => {\n\t\t\tif (!processManager.hasRunning() && !shuttingDown) {\n\t\t\t\tresolveFinished?.()\n\t\t\t}\n\t\t}\n\n\t\tconst shutdown = async () => {\n\t\t\tif (shuttingDown) return\n\t\t\tshuttingDown = true\n\t\t\tschemaWatcher?.stop()\n\t\t\tawait processManager.shutdownAll()\n\t\t\tresolveFinished?.()\n\t\t}\n\n\t\tconst onSigInt = () => {\n\t\t\tvoid shutdown()\n\t\t}\n\t\tconst onSigTerm = () => {\n\t\t\tvoid shutdown()\n\t\t}\n\n\t\tprocess.on('SIGINT', onSigInt)\n\t\tprocess.on('SIGTERM', onSigTerm)\n\n\t\tlogger.banner()\n\t\tlogger.info('Starting development environment:')\n\t\tlogger.blank()\n\t\tlogger.step(` Vite dev server on port ${vitePort}`)\n\t\tif (shouldStartSync && hasTsx && syncServerFile) {\n\t\t\tlogger.step(` Sync server on port ${syncPort}`)\n\t\t} else if (shouldStartSync && syncServerFile === null && managedSyncStore !== null) {\n\t\t\tlogger.step(` Managed sync server on port ${syncPort} (${managedSyncStore.type})`)\n\t\t} else if (syncAllowed && syncServerFile === null) {\n\t\t\tlogger.step(' Sync server configured but no server.ts/server.js or managed store found')\n\t\t} else if (!syncAllowed) {\n\t\t\tlogger.step(' Sync server disabled via --no-sync')\n\t\t}\n\n\t\tif (watchEnabled && schemaPath) {\n\t\t\tlogger.step(` Schema watcher enabled (${schemaPath})`)\n\t\t} else if (args['no-watch'] === true) {\n\t\t\tlogger.step(' Schema watcher disabled via --no-watch')\n\t\t} else {\n\t\t\tlogger.step(' Schema watcher disabled (schema.ts not found)')\n\t\t}\n\t\tlogger.blank()\n\n\t\tlogger.step(\n\t\t\t' Kora DevTools overlay: Ctrl+Shift+K (Cmd+Shift+K on macOS) when devtools is enabled',\n\t\t)\n\n\t\tprocessManager.spawn({\n\t\t\tlabel: 'vite',\n\t\t\tcommand: process.execPath,\n\t\t\targs: [viteEntryPoint, '--port', String(vitePort)],\n\t\t\tcwd: projectRoot,\n\t\t\tenv: {\n\t\t\t\tKORA_DEV: '1',\n\t\t\t},\n\t\t\tonExit: onManagedProcessExit,\n\t\t})\n\n\t\tconst syncProcessConfig: ManagedProcessConfig | null =\n\t\t\tshouldStartSync && hasTsx && syncServerFile\n\t\t\t\t? {\n\t\t\t\t\t\tlabel: 'sync',\n\t\t\t\t\t\tcommand: process.execPath,\n\t\t\t\t\t\targs: ['--import', 'tsx', syncServerFile],\n\t\t\t\t\t\tcwd: projectRoot,\n\t\t\t\t\t\tenv: {\n\t\t\t\t\t\t\tPORT: String(syncPort),\n\t\t\t\t\t\t\tKORA_SYNC_PORT: String(syncPort),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tonExit: onManagedProcessExit,\n\t\t\t\t\t}\n\t\t\t\t: shouldStartSync && syncServerFile === null && managedSyncStore !== null\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tlabel: 'sync',\n\t\t\t\t\t\t\tcommand: process.execPath,\n\t\t\t\t\t\t\targs: ['--input-type=module', '--eval', MANAGED_SYNC_BOOTSTRAP_SCRIPT],\n\t\t\t\t\t\t\tcwd: projectRoot,\n\t\t\t\t\t\t\tenv: {\n\t\t\t\t\t\t\t\tKORA_DEV_SYNC_CONFIG: JSON.stringify({\n\t\t\t\t\t\t\t\t\tport: Number(syncPort),\n\t\t\t\t\t\t\t\t\tstore: managedSyncStore,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tonExit: onManagedProcessExit,\n\t\t\t\t\t\t}\n\t\t\t\t\t: null\n\n\t\tif (syncProcessConfig) {\n\t\t\tprocessManager.spawn(syncProcessConfig)\n\t\t}\n\n\t\tif (watchEnabled && schemaPath) {\n\t\t\tschemaWatcher = new SchemaWatcher({\n\t\t\t\tschemaPath,\n\t\t\t\tprojectRoot,\n\t\t\t\tdebounceMs: watchDebounceMs,\n\t\t\t\tonRegenerate: () => {\n\t\t\t\t\tlogger.success('Regenerated types from schema changes')\n\t\t\t\t},\n\t\t\t\tonSchemaVersionChange: ({ previous, next }) => {\n\t\t\t\t\tif (!syncProcessConfig) {\n\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t`Schema version changed from ${previous} to ${next}; restart your sync server before clients can sync.`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tlogger.warn(`Schema version changed from ${previous} to ${next}; restarting sync server.`)\n\t\t\t\t\tvoid processManager.restart(syncProcessConfig)\n\t\t\t\t},\n\t\t\t\tonError: (error) => {\n\t\t\t\t\tlogger.error(`Schema watcher error: ${error.message}`)\n\t\t\t\t},\n\t\t\t})\n\t\t\tschemaWatcher.start()\n\t\t}\n\n\t\tawait finished\n\t\tprocess.off('SIGINT', onSigInt)\n\t\tprocess.off('SIGTERM', onSigTerm)\n\t},\n})\n\nasync function findSyncServerFile(projectRoot: string): Promise<string | null> {\n\tconst candidates = [join(projectRoot, 'server.ts'), join(projectRoot, 'server.js')]\n\n\tfor (const candidate of candidates) {\n\t\ttry {\n\t\t\tawait access(candidate)\n\t\t\treturn candidate\n\t\t} catch {\n\t\t\t// continue\n\t\t}\n\t}\n\n\treturn null\n}\n\nasync function fileExists(path: string): Promise<boolean> {\n\ttry {\n\t\tawait access(path)\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n\nfunction loadProjectEnv(projectRoot: string, mode = 'development'): void {\n\tconst files = ['.env', '.env.local', `.env.${mode}`, `.env.${mode}.local`]\n\tconst existingKeys = new Set(Object.keys(process.env))\n\tfor (const file of files) {\n\t\tconst path = join(projectRoot, file)\n\t\tif (!existsSync(path)) continue\n\t\tconst parsed = parseEnvFile(readFileSync(path, 'utf8'))\n\t\tfor (const [key, value] of Object.entries(parsed)) {\n\t\t\tif (!existingKeys.has(key)) {\n\t\t\t\tprocess.env[key] = value\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction parseEnvFile(contents: string): Record<string, string> {\n\tconst env: Record<string, string> = {}\n\n\tfor (const rawLine of contents.split(/\\r?\\n/)) {\n\t\tconst line = rawLine.trim()\n\t\tif (!line || line.startsWith('#')) continue\n\n\t\tconst normalized = line.startsWith('export ') ? line.slice('export '.length).trim() : line\n\t\tconst equalsIndex = normalized.indexOf('=')\n\t\tif (equalsIndex <= 0) continue\n\n\t\tconst key = normalized.slice(0, equalsIndex).trim()\n\t\tif (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue\n\n\t\tenv[key] = parseEnvValue(normalized.slice(equalsIndex + 1).trim())\n\t}\n\n\treturn env\n}\n\nfunction parseEnvValue(value: string): string {\n\tconst quote = value[0]\n\tif ((quote === '\"' || quote === \"'\") && value[value.length - 1] === quote) {\n\t\tconst inner = value.slice(1, -1)\n\t\treturn quote === '\"' ? inner.replace(/\\\\n/g, '\\n').replace(/\\\\r/g, '\\r') : inner\n\t}\n\n\tconst commentIndex = value.search(/\\s#/)\n\treturn (commentIndex >= 0 ? value.slice(0, commentIndex) : value).trim()\n}\n\nfunction normalizeManagedSyncStore(\n\tconfig: KoraConfigFile | null,\n\tprojectRoot: string,\n): ManagedSyncStoreConfig | null {\n\tconst sync = config?.dev?.sync\n\tif (typeof sync !== 'object' || sync === null) return null\n\n\tconst store = sync.store\n\tif (store === undefined) return { type: 'memory' }\n\n\tif (store === 'memory') return { type: 'memory' }\n\tif (store === 'sqlite') return { type: 'sqlite', filename: join(projectRoot, 'kora-sync.db') }\n\tif (store === 'postgres') {\n\t\tconst connectionString = process.env.DATABASE_URL\n\t\tif (!connectionString) return null\n\t\treturn { type: 'postgres', connectionString }\n\t}\n\n\tif (typeof store === 'object' && store !== null) {\n\t\tif (store.type === 'memory') return { type: 'memory' }\n\t\tif (store.type === 'sqlite') {\n\t\t\tconst filename =\n\t\t\t\ttypeof store.filename === 'string' && store.filename.length > 0\n\t\t\t\t\t? resolve(projectRoot, store.filename)\n\t\t\t\t\t: join(projectRoot, 'kora-sync.db')\n\t\t\treturn { type: 'sqlite', filename }\n\t\t}\n\t\tif (store.type === 'postgres' && typeof store.connectionString === 'string') {\n\t\t\treturn { type: 'postgres', connectionString: store.connectionString }\n\t\t}\n\t}\n\n\treturn null\n}\n\nfunction isPostgresEnvRequested(config: KoraConfigFile | null): boolean {\n\tconst sync = config?.dev?.sync\n\tif (typeof sync !== 'object' || sync === null) return false\n\tif (sync.store === 'postgres') return true\n\tif (typeof sync.store === 'object' && sync.store !== null && sync.store.type === 'postgres')\n\t\treturn true\n\treturn false\n}\n\nconst MANAGED_SYNC_BOOTSTRAP_SCRIPT = `\nconst config = JSON.parse(process.env.KORA_DEV_SYNC_CONFIG ?? '{}');\nconst {\n createKoraServer,\n MemoryServerStore,\n createSqliteServerStore,\n createPostgresServerStore,\n} = await import('@korajs/server');\nconst storeConfig = config.store ?? { type: 'memory' };\nlet store;\nif (storeConfig.type === 'memory') {\n store = new MemoryServerStore();\n} else if (storeConfig.type === 'sqlite') {\n const filename = typeof storeConfig.filename === 'string' && storeConfig.filename.length > 0\n ? storeConfig.filename\n : './kora-sync.db';\n store = createSqliteServerStore({ filename });\n} else if (storeConfig.type === 'postgres') {\n if (typeof storeConfig.connectionString !== 'string' || storeConfig.connectionString.length === 0) {\n throw new Error('Managed postgres sync requires a connectionString');\n }\n store = await createPostgresServerStore({\n connectionString: storeConfig.connectionString,\n });\n} else {\n throw new Error('Unsupported managed sync store type: ' + String(storeConfig.type));\n}\nconst server = createKoraServer({ store, port: Number(config.port ?? 3001) });\nconst shutdown = async () => {\n try {\n await server.stop();\n } catch {\n }\n process.exit(0);\n};\nprocess.on('SIGINT', () => {\n void shutdown();\n});\nprocess.on('SIGTERM', () => {\n void shutdown();\n});\nawait server.start();\nprocess.stdout.write('Managed sync server running on ws://localhost:' + String(config.port ?? 3001) + '\\\\n');\nawait new Promise(() => {});\n`\n","import { spawn as spawnChild } from 'node:child_process'\nimport type { ChildProcess, SpawnOptions } from 'node:child_process'\n\nexport interface ManagedProcessConfig {\n\tlabel: string\n\tcommand: string\n\targs: string[]\n\tcwd: string\n\tenv?: Record<string, string>\n\tonExit?: (code: number | null, signal: NodeJS.Signals | null) => void\n}\n\ninterface RunningProcess {\n\tchild: ChildProcess\n\texitPromise: Promise<void>\n\tstdoutBuffer: string\n\tstderrBuffer: string\n}\n\n/**\n * Manages long-running child processes for the dev command.\n */\nexport class ProcessManager {\n\tprivate readonly processes = new Map<string, RunningProcess>()\n\n\tspawn(config: ManagedProcessConfig): void {\n\t\tthis.processes.get(config.label)?.child.kill('SIGTERM')\n\t\tconst options: SpawnOptions = {\n\t\t\tcwd: config.cwd,\n\t\t\tenv: { ...process.env, ...config.env },\n\t\t\tstdio: ['ignore', 'pipe', 'pipe'],\n\t\t}\n\n\t\tconst child = spawnChild(config.command, config.args, options)\n\t\tlet resolveExit: (() => void) | undefined\n\n\t\tconst runningProcess: RunningProcess = {\n\t\t\tchild,\n\t\t\texitPromise: new Promise<void>((resolve) => {\n\t\t\t\tresolveExit = resolve\n\t\t\t}),\n\t\t\tstdoutBuffer: '',\n\t\t\tstderrBuffer: '',\n\t\t}\n\n\t\tthis.processes.set(config.label, runningProcess)\n\n\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\trunningProcess.stdoutBuffer = this.writeChunk(\n\t\t\t\tconfig.label,\n\t\t\t\trunningProcess.stdoutBuffer,\n\t\t\t\tchunk,\n\t\t\t\tfalse,\n\t\t\t)\n\t\t})\n\n\t\tchild.stderr?.on('data', (chunk: Buffer) => {\n\t\t\trunningProcess.stderrBuffer = this.writeChunk(\n\t\t\t\tconfig.label,\n\t\t\t\trunningProcess.stderrBuffer,\n\t\t\t\tchunk,\n\t\t\t\ttrue,\n\t\t\t)\n\t\t})\n\n\t\tchild.on('exit', (code, signal) => {\n\t\t\tthis.flushBuffer(config.label, runningProcess.stdoutBuffer, false)\n\t\t\tthis.flushBuffer(config.label, runningProcess.stderrBuffer, true)\n\t\t\tthis.processes.delete(config.label)\n\t\t\tconfig.onExit?.(code, signal)\n\t\t\tresolveExit?.()\n\t\t})\n\t}\n\n\thasRunning(): boolean {\n\t\treturn this.processes.size > 0\n\t}\n\n\tasync restart(config: ManagedProcessConfig): Promise<void> {\n\t\tawait this.stop(config.label)\n\t\tthis.spawn(config)\n\t}\n\n\tasync stop(label: string): Promise<void> {\n\t\tconst running = this.processes.get(label)\n\t\tif (!running) return\n\t\trunning.child.kill('SIGTERM')\n\t\tawait Promise.race([running.exitPromise, delay(5000)])\n\t\tconst remaining = this.processes.get(label)\n\t\tif (!remaining) return\n\t\tremaining.child.kill('SIGKILL')\n\t\tawait remaining.exitPromise\n\t}\n\n\tasync shutdownAll(): Promise<void> {\n\t\tconst running = Array.from(this.processes.values())\n\t\tif (running.length === 0) return\n\n\t\tfor (const processEntry of running) {\n\t\t\tprocessEntry.child.kill('SIGTERM')\n\t\t}\n\n\t\tawait Promise.race([Promise.all(running.map((entry) => entry.exitPromise)), delay(5000)])\n\n\t\tconst remaining = Array.from(this.processes.values())\n\t\tif (remaining.length === 0) return\n\n\t\tfor (const processEntry of remaining) {\n\t\t\tprocessEntry.child.kill('SIGKILL')\n\t\t}\n\n\t\tawait Promise.all(remaining.map((entry) => entry.exitPromise))\n\t}\n\n\tprivate writeChunk(label: string, buffer: string, chunk: Buffer, isError: boolean): string {\n\t\tconst combined = `${buffer}${chunk.toString('utf-8')}`\n\t\tconst lines = combined.split(/\\r?\\n/)\n\t\tconst remaining = lines.pop() ?? ''\n\n\t\tfor (const line of lines) {\n\t\t\tthis.writeLine(label, line, isError)\n\t\t}\n\n\t\treturn remaining\n\t}\n\n\tprivate flushBuffer(label: string, buffer: string, isError: boolean): void {\n\t\tif (!buffer) return\n\t\tthis.writeLine(label, buffer, isError)\n\t}\n\n\tprivate writeLine(label: string, line: string, isError: boolean): void {\n\t\tconst stream = isError ? process.stderr : process.stdout\n\t\tstream.write(`[${label}] ${line}\\n`)\n\t}\n}\n\nfunction delay(ms: number): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tsetTimeout(resolve, ms)\n\t})\n}\n","import { spawn } from 'node:child_process'\nimport { watch } from 'node:fs'\nimport type { FSWatcher } from 'node:fs'\nimport { join } from 'node:path'\nimport { hasTsxInstalled } from '../../utils/fs-helpers'\nimport { loadSchemaDefinition } from '../migrate/schema-loader'\n\nexport interface SchemaWatcherConfig {\n\tschemaPath: string\n\tprojectRoot: string\n\tdebounceMs?: number\n\tonRegenerate?: () => void\n\tonSchemaVersionChange?: (change: { previous: number; next: number }) => void\n\tonError?: (error: Error) => void\n}\n\n/**\n * Watches a schema file and regenerates types when it changes.\n */\nexport class SchemaWatcher {\n\tprivate readonly debounceMs: number\n\tprivate watcher: FSWatcher | null = null\n\tprivate debounceTimer: NodeJS.Timeout | null = null\n\tprivate schemaVersion: number | null = null\n\n\tconstructor(private readonly config: SchemaWatcherConfig) {\n\t\tthis.debounceMs = config.debounceMs ?? 300\n\t}\n\n\tstart(): void {\n\t\tif (this.watcher) return\n\n\t\tthis.watcher = watch(this.config.schemaPath, () => {\n\t\t\tthis.scheduleRegeneration()\n\t\t})\n\n\t\tthis.watcher.on('error', (error) => {\n\t\t\tthis.config.onError?.(toError(error))\n\t\t})\n\n\t\tvoid this.refreshSchemaVersion().catch((error) => {\n\t\t\tthis.config.onError?.(toError(error))\n\t\t})\n\t}\n\n\tstop(): void {\n\t\tif (this.debounceTimer) {\n\t\t\tclearTimeout(this.debounceTimer)\n\t\t\tthis.debounceTimer = null\n\t\t}\n\n\t\tthis.watcher?.close()\n\t\tthis.watcher = null\n\t}\n\n\tasync regenerate(): Promise<void> {\n\t\t// Use process.execPath (node) + --import tsx to run kora generate,\n\t\t// avoiding .cmd shim issues on Windows with paths containing spaces.\n\t\tconst koraBinJs = join(\n\t\t\tthis.config.projectRoot,\n\t\t\t'node_modules',\n\t\t\t'@korajs',\n\t\t\t'cli',\n\t\t\t'dist',\n\t\t\t'bin.js',\n\t\t)\n\t\tconst hasTsx = await hasTsxInstalled(this.config.projectRoot)\n\n\t\tconst command = process.execPath\n\t\tconst args = hasTsx\n\t\t\t? ['--import', 'tsx', koraBinJs, 'generate', 'types', '--schema', this.config.schemaPath]\n\t\t\t: [koraBinJs, 'generate', 'types', '--schema', this.config.schemaPath]\n\n\t\tawait spawnCommand(command, args, this.config.projectRoot)\n\t\tthis.config.onRegenerate?.()\n\t\tawait this.refreshSchemaVersion()\n\t}\n\n\tprivate async refreshSchemaVersion(): Promise<void> {\n\t\tconst schema = await loadSchemaDefinition(this.config.schemaPath, this.config.projectRoot)\n\t\tconst previous = this.schemaVersion\n\t\tthis.schemaVersion = schema.version\n\t\tif (previous !== null && previous !== schema.version) {\n\t\t\tthis.config.onSchemaVersionChange?.({ previous, next: schema.version })\n\t\t}\n\t}\n\n\tprivate scheduleRegeneration(): void {\n\t\tif (this.debounceTimer) {\n\t\t\tclearTimeout(this.debounceTimer)\n\t\t}\n\n\t\tthis.debounceTimer = setTimeout(() => {\n\t\t\tthis.debounceTimer = null\n\t\t\tvoid this.regenerate().catch((error) => {\n\t\t\t\tthis.config.onError?.(toError(error))\n\t\t\t})\n\t\t}, this.debounceMs)\n\t}\n}\n\nasync function spawnCommand(command: string, args: string[], cwd: string): Promise<void> {\n\tawait new Promise<void>((resolve, reject) => {\n\t\tconst child = spawn(command, args, {\n\t\t\tcwd,\n\t\t\tstdio: ['ignore', 'pipe', 'pipe'],\n\t\t\tenv: process.env,\n\t\t})\n\n\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\twritePrefixedLines(chunk, false)\n\t\t})\n\n\t\tchild.stderr?.on('data', (chunk: Buffer) => {\n\t\t\twritePrefixedLines(chunk, true)\n\t\t})\n\n\t\tchild.on('error', (error) => {\n\t\t\treject(error)\n\t\t})\n\n\t\tchild.on('exit', (code) => {\n\t\t\tif (code === 0) {\n\t\t\t\tresolve()\n\t\t\t\treturn\n\t\t\t}\n\t\t\treject(new Error(`Type generation exited with code ${code ?? 'unknown'}.`))\n\t\t})\n\t})\n}\n\nfunction writePrefixedLines(chunk: Buffer, isError: boolean): void {\n\tconst text = chunk.toString('utf-8')\n\tconst lines = text.split(/\\r?\\n/).filter((line) => line.length > 0)\n\tconst stream = isError ? process.stderr : process.stdout\n\n\tfor (const line of lines) {\n\t\tstream.write(`[kora] ${line}\\n`)\n\t}\n}\n\nfunction toError(error: unknown): Error {\n\tif (error instanceof Error) return error\n\treturn new Error(String(error))\n}\n","import { defineCommand } from 'citty'\nimport { InvalidProjectError } from '../../errors'\nimport { findProjectRoot } from '../../utils/fs-helpers'\nimport { createLogger } from '../../utils/logger'\nimport { doctorHasFailures, runDoctorChecks } from './doctor-checks'\n\n/**\n * Diagnose common Kora project setup issues (schema, worker, sync, versions).\n */\nexport const doctorCommand = defineCommand({\n\tmeta: {\n\t\tname: 'doctor',\n\t\tdescription: 'Check Kora project setup (schema, worker, sync server, versions)',\n\t},\n\targs: {\n\t\turl: {\n\t\t\ttype: 'string',\n\t\t\tdescription:\n\t\t\t\t'Sync server HTTP base URL for status probe (default: from .env or localhost:3001)',\n\t\t},\n\t\t'skip-network': {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Skip sync server and schema version network checks',\n\t\t\tdefault: false,\n\t\t},\n\t},\n\tasync run({ args }) {\n\t\tconst logger = createLogger()\n\t\tconst projectRoot = await findProjectRoot()\n\t\tif (!projectRoot) {\n\t\t\tthrow new InvalidProjectError(process.cwd())\n\t\t}\n\n\t\tconst syncHttpUrl = typeof args.url === 'string' ? args.url : undefined\n\t\tconst skipNetwork = args['skip-network'] === true\n\n\t\tlogger.banner()\n\t\tlogger.info(`Checking project at ${projectRoot}`)\n\t\tlogger.blank()\n\n\t\tconst results = await runDoctorChecks({\n\t\t\tprojectRoot,\n\t\t\tsyncHttpUrl,\n\t\t\tskipNetwork,\n\t\t})\n\n\t\tfor (const check of results) {\n\t\t\tconst prefix =\n\t\t\t\tcheck.status === 'pass'\n\t\t\t\t\t? 'success'\n\t\t\t\t\t: check.status === 'warn'\n\t\t\t\t\t\t? 'warn'\n\t\t\t\t\t\t: check.status === 'fail'\n\t\t\t\t\t\t\t? 'error'\n\t\t\t\t\t\t\t: 'step'\n\t\t\tlogger[prefix](`${check.title}: ${check.message}`)\n\t\t\tif (check.fix && check.status !== 'pass' && check.status !== 'skip') {\n\t\t\t\tlogger.step(` Fix: ${check.fix}`)\n\t\t\t}\n\t\t}\n\n\t\tlogger.blank()\n\t\tif (doctorHasFailures(results)) {\n\t\t\tlogger.error('Doctor found blocking issues.')\n\t\t\tprocess.exitCode = 1\n\t\t\treturn\n\t\t}\n\n\t\tconst warnings = results.filter((r) => r.status === 'warn').length\n\t\tif (warnings > 0) {\n\t\t\tlogger.warn(`Doctor finished with ${warnings} warning(s).`)\n\t\t} else {\n\t\t\tlogger.success('All checks passed.')\n\t\t}\n\t},\n})\n","import { access, readFile } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport type { SchemaDefinition } from '@korajs/core'\nimport { findSchemaFile } from '../../utils/fs-helpers'\nimport { loadKoraConfig } from '../dev/kora-config'\nimport { loadSchemaDefinition } from '../migrate/schema-loader'\n\nexport type DoctorCheckStatus = 'pass' | 'warn' | 'fail' | 'skip'\n\nexport interface DoctorCheckResult {\n\tid: string\n\ttitle: string\n\tstatus: DoctorCheckStatus\n\tmessage: string\n\tfix?: string\n}\n\nexport interface DoctorRunOptions {\n\tprojectRoot: string\n\t/** HTTP base URL for sync status probe (e.g. http://localhost:3001) */\n\tsyncHttpUrl?: string\n\t/** Skip network checks */\n\tskipNetwork?: boolean\n}\n\nconst STATUS_ENDPOINT = '/__kora/status'\n\n/**\n * Run all static and optional network diagnostics for a Kora project.\n */\nexport async function runDoctorChecks(options: DoctorRunOptions): Promise<DoctorCheckResult[]> {\n\tconst { projectRoot } = options\n\tconst results: DoctorCheckResult[] = []\n\n\tresults.push({\n\t\tid: 'project-root',\n\t\ttitle: 'Project root',\n\t\tstatus: 'pass',\n\t\tmessage: projectRoot,\n\t})\n\n\tconst config = await loadKoraConfig(projectRoot)\n\tif (!config) {\n\t\tresults.push({\n\t\t\tid: 'kora-config',\n\t\t\ttitle: 'kora.config',\n\t\t\tstatus: 'warn',\n\t\t\tmessage: 'No kora.config.* file found.',\n\t\t\tfix: 'Add kora.config.ts with schema path and dev settings (see create-kora-app templates).',\n\t\t})\n\t} else {\n\t\tresults.push({\n\t\t\tid: 'kora-config',\n\t\t\ttitle: 'kora.config',\n\t\t\tstatus: 'pass',\n\t\t\tmessage: 'Configuration file loaded.',\n\t\t})\n\t}\n\n\tconst schemaPath = await resolveSchemaPath(projectRoot, config?.schema)\n\tif (!schemaPath) {\n\t\tresults.push({\n\t\t\tid: 'schema',\n\t\t\ttitle: 'Schema',\n\t\t\tstatus: 'fail',\n\t\t\tmessage: 'Could not find schema.ts in src/ or project root.',\n\t\t\tfix: 'Add src/schema.ts or set schema in kora.config.ts.',\n\t\t})\n\t} else {\n\t\ttry {\n\t\t\tconst schema = await loadSchemaDefinition(schemaPath, projectRoot)\n\t\t\tresults.push({\n\t\t\t\tid: 'schema',\n\t\t\t\ttitle: 'Schema',\n\t\t\t\tstatus: 'pass',\n\t\t\t\tmessage: `Loaded schema v${schema.version} (${Object.keys(schema.collections).length} collection(s)).`,\n\t\t\t})\n\n\t\t\tconst workerCheck = await checkWorkerFile(projectRoot)\n\t\t\tresults.push(workerCheck)\n\n\t\t\tconst depsCheck = await checkDependencies(projectRoot)\n\t\t\tresults.push(depsCheck)\n\n\t\t\tresults.push(opfsBrowserNote())\n\n\t\t\tif (!options.skipNetwork) {\n\t\t\t\tconst syncUrl = options.syncHttpUrl ?? (await resolveSyncHttpUrl(projectRoot, config))\n\t\t\t\tconst syncChecks = await checkSyncServer(syncUrl, schema)\n\t\t\t\tresults.push(...syncChecks)\n\t\t\t} else {\n\t\t\t\tresults.push({\n\t\t\t\t\tid: 'sync-server',\n\t\t\t\t\ttitle: 'Sync server',\n\t\t\t\t\tstatus: 'skip',\n\t\t\t\t\tmessage: 'Network checks skipped.',\n\t\t\t\t})\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tresults.push({\n\t\t\t\tid: 'schema',\n\t\t\t\ttitle: 'Schema',\n\t\t\t\tstatus: 'fail',\n\t\t\t\tmessage: `Failed to load schema: ${message}`,\n\t\t\t\tfix: 'Ensure the schema exports defineSchema() as default and TypeScript can be evaluated (install tsx).',\n\t\t\t})\n\t\t}\n\t}\n\n\treturn results\n}\n\nasync function resolveSchemaPath(\n\tprojectRoot: string,\n\tconfigSchema?: string,\n): Promise<string | null> {\n\tif (typeof configSchema === 'string') {\n\t\tconst resolved = resolve(projectRoot, configSchema)\n\t\ttry {\n\t\t\tawait access(resolved)\n\t\t\treturn resolved\n\t\t} catch {\n\t\t\t// fall through to search\n\t\t}\n\t}\n\treturn findSchemaFile(projectRoot)\n}\n\nasync function checkWorkerFile(projectRoot: string): Promise<DoctorCheckResult> {\n\tconst candidates = [\n\t\tjoin(projectRoot, 'src', 'kora-worker.ts'),\n\t\tjoin(projectRoot, 'src', 'kora-worker.js'),\n\t]\n\n\tfor (const path of candidates) {\n\t\ttry {\n\t\t\tawait access(path)\n\t\t\treturn {\n\t\t\t\tid: 'worker',\n\t\t\t\ttitle: 'SQLite WASM worker',\n\t\t\t\tstatus: 'pass',\n\t\t\t\tmessage: `Found ${path.replace(projectRoot, '.')}.`,\n\t\t\t}\n\t\t} catch {\n\t\t\t// try next\n\t\t}\n\t}\n\n\treturn {\n\t\tid: 'worker',\n\t\ttitle: 'SQLite WASM worker',\n\t\tstatus: 'warn',\n\t\tmessage: 'No src/kora-worker.ts found.',\n\t\tfix: 'Add kora-worker.ts and pass store.workerUrl from Vite (?worker&url) in createApp().',\n\t}\n}\n\nasync function checkDependencies(projectRoot: string): Promise<DoctorCheckResult> {\n\ttry {\n\t\tconst raw = await readFile(join(projectRoot, 'package.json'), 'utf-8')\n\t\tconst pkg = JSON.parse(raw) as {\n\t\t\tdependencies?: Record<string, string>\n\t\t\tdevDependencies?: Record<string, string>\n\t\t}\n\t\tconst deps = { ...pkg.dependencies, ...pkg.devDependencies }\n\t\tconst hasKora = Boolean(deps.korajs || deps.kora)\n\t\tconst hasStore = Boolean(deps['@korajs/store'])\n\t\tif (hasKora || hasStore) {\n\t\t\treturn {\n\t\t\t\tid: 'dependencies',\n\t\t\t\ttitle: 'Dependencies',\n\t\t\t\tstatus: 'pass',\n\t\t\t\tmessage: hasKora\n\t\t\t\t\t? 'korajs is listed in package.json.'\n\t\t\t\t\t: '@korajs/store is listed in package.json.',\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tid: 'dependencies',\n\t\t\ttitle: 'Dependencies',\n\t\t\tstatus: 'fail',\n\t\t\tmessage: 'No korajs or @korajs/store dependency found.',\n\t\t\tfix: 'Run pnpm add korajs @korajs/react (or your package manager equivalent).',\n\t\t}\n\t} catch {\n\t\treturn {\n\t\t\tid: 'dependencies',\n\t\t\ttitle: 'Dependencies',\n\t\t\tstatus: 'fail',\n\t\t\tmessage: 'Could not read package.json.',\n\t\t\tfix: 'Run this command from a Kora app directory with a valid package.json.',\n\t\t}\n\t}\n}\n\nfunction opfsBrowserNote(): DoctorCheckResult {\n\treturn {\n\t\tid: 'opfs',\n\t\ttitle: 'OPFS persistence',\n\t\tstatus: 'skip',\n\t\tmessage:\n\t\t\t'OPFS availability is checked in the browser at runtime. Open the app and confirm no IndexedDB fallback warning in the console.',\n\t\tfix: 'Use a Chromium-based browser with storage access; avoid private mode if persistence fails.',\n\t}\n}\n\nasync function resolveSyncHttpUrl(\n\tprojectRoot: string,\n\tconfig: Awaited<ReturnType<typeof loadKoraConfig>>,\n): Promise<string> {\n\tconst envUrl = await readEnvSyncUrl(projectRoot)\n\tif (envUrl) {\n\t\treturn toSyncStatusHttpBase(envUrl)\n\t}\n\n\tconst syncPort =\n\t\ttypeof config?.dev?.sync === 'object' && typeof config.dev.sync.port === 'number'\n\t\t\t? config.dev.sync.port\n\t\t\t: 3001\n\n\treturn `http://localhost:${syncPort}`\n}\n\nasync function readEnvSyncUrl(projectRoot: string): Promise<string | null> {\n\tfor (const file of ['.env', '.env.local']) {\n\t\tconst path = join(projectRoot, file)\n\t\ttry {\n\t\t\tconst content = await readFile(path, 'utf-8')\n\t\t\tfor (const line of content.split('\\n')) {\n\t\t\t\tconst trimmed = line.trim()\n\t\t\t\tif (!trimmed || trimmed.startsWith('#')) continue\n\t\t\t\tconst match = trimmed.match(/^VITE_SYNC_URL=(.+)$/)\n\t\t\t\tif (match?.[1]) {\n\t\t\t\t\treturn match[1].trim().replace(/^[\"']|[\"']$/g, '')\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// continue\n\t\t}\n\t}\n\treturn null\n}\n\n/** Converts a WebSocket sync URL to an HTTP base for {@link STATUS_ENDPOINT}. */\nexport function toSyncStatusHttpBase(url: string): string {\n\ttry {\n\t\tconst parsed = new URL(url)\n\t\tif (parsed.protocol === 'ws:') {\n\t\t\tparsed.protocol = 'http:'\n\t\t} else if (parsed.protocol === 'wss:') {\n\t\t\tparsed.protocol = 'https:'\n\t\t}\n\t\tparsed.pathname = ''\n\t\tparsed.search = ''\n\t\tparsed.hash = ''\n\t\treturn parsed.toString().replace(/\\/$/, '')\n\t} catch {\n\t\treturn 'http://localhost:3001'\n\t}\n}\n\ninterface ServerStatusResponse {\n\tschemaVersion: number\n\trunning: boolean\n\tversion: string\n}\n\nasync function checkSyncServer(\n\thttpBase: string,\n\tschema: SchemaDefinition,\n): Promise<DoctorCheckResult[]> {\n\tconst statusUrl = `${httpBase.replace(/\\/$/, '')}${STATUS_ENDPOINT}`\n\n\ttry {\n\t\tconst response = await fetch(statusUrl, {\n\t\t\tsignal: AbortSignal.timeout(5000),\n\t\t})\n\t\tif (!response.ok) {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tid: 'sync-server',\n\t\t\t\t\ttitle: 'Sync server',\n\t\t\t\t\tstatus: 'fail',\n\t\t\t\t\tmessage: `GET ${statusUrl} returned ${response.status}.`,\n\t\t\t\t\tfix: 'Start the sync server with `kora dev` or `pnpm run dev` in a sync template.',\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\n\t\tconst body = (await response.json()) as ServerStatusResponse\n\t\tconst results: DoctorCheckResult[] = [\n\t\t\t{\n\t\t\t\tid: 'sync-server',\n\t\t\t\ttitle: 'Sync server',\n\t\t\t\tstatus: 'pass',\n\t\t\t\tmessage: `Reachable at ${statusUrl} (server v${body.version ?? 'unknown'}).`,\n\t\t\t},\n\t\t]\n\n\t\tif (typeof body.schemaVersion === 'number' && body.schemaVersion !== schema.version) {\n\t\t\tresults.push({\n\t\t\t\tid: 'schema-version',\n\t\t\t\ttitle: 'Schema version',\n\t\t\t\tstatus: 'warn',\n\t\t\t\tmessage: `Client schema v${schema.version} differs from server schema v${body.schemaVersion}.`,\n\t\t\t\tfix: 'Run migrations on the server and client, or align schema.version before syncing.',\n\t\t\t})\n\t\t} else {\n\t\t\tresults.push({\n\t\t\t\tid: 'schema-version',\n\t\t\t\ttitle: 'Schema version',\n\t\t\t\tstatus: 'pass',\n\t\t\t\tmessage: `Client and server both use schema v${schema.version}.`,\n\t\t\t})\n\t\t}\n\n\t\treturn results\n\t} catch (error) {\n\t\tconst detail = error instanceof Error ? error.message : String(error)\n\t\treturn [\n\t\t\t{\n\t\t\t\tid: 'sync-server',\n\t\t\t\ttitle: 'Sync server',\n\t\t\t\tstatus: 'warn',\n\t\t\t\tmessage: `Could not reach ${statusUrl}: ${detail}`,\n\t\t\t\tfix: 'Start the sync server, or pass --skip-network for local-only checks.',\n\t\t\t},\n\t\t]\n\t}\n}\n\n/**\n * True when any check failed (doctor should exit non-zero).\n */\nexport function doctorHasFailures(results: DoctorCheckResult[]): boolean {\n\treturn results.some((r) => r.status === 'fail')\n}\n","import { mkdir, writeFile } from 'node:fs/promises'\nimport { dirname, resolve } from 'node:path'\nimport type { SchemaDefinition } from '@korajs/core'\nimport { defineCommand } from 'citty'\nimport { InvalidProjectError, SchemaNotFoundError } from '../../errors'\nimport { findProjectRoot, findSchemaFile } from '../../utils/fs-helpers'\nimport { createLogger } from '../../utils/logger'\nimport { loadSchemaDefinition } from '../migrate/schema-loader'\nimport { generateCollectionHooks } from './hook-generator'\nimport { generateTypes } from './type-generator'\n\n/**\n * The `generate` command with `types` subcommand.\n * Reads a schema file and generates TypeScript interfaces.\n */\nexport const generateCommand = defineCommand({\n\tmeta: {\n\t\tname: 'generate',\n\t\tdescription: 'Generate code from your Kora schema',\n\t},\n\tsubCommands: {\n\t\ttypes: defineCommand({\n\t\t\tmeta: {\n\t\t\t\tname: 'types',\n\t\t\t\tdescription: 'Generate TypeScript types from your schema',\n\t\t\t},\n\t\t\targs: {\n\t\t\t\tschema: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Path to schema file',\n\t\t\t\t},\n\t\t\t\toutput: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Output file path',\n\t\t\t\t\tdefault: 'kora/generated/types.ts',\n\t\t\t\t},\n\t\t\t},\n\t\t\tasync run({ args }) {\n\t\t\t\tconst logger = createLogger()\n\n\t\t\t\t// Find project root\n\t\t\t\tconst projectRoot = await findProjectRoot()\n\t\t\t\tif (!projectRoot) {\n\t\t\t\t\tthrow new InvalidProjectError(process.cwd())\n\t\t\t\t}\n\n\t\t\t\t// Find schema file\n\t\t\t\tlet schemaPath: string\n\t\t\t\tif (args.schema && typeof args.schema === 'string') {\n\t\t\t\t\tschemaPath = resolve(args.schema)\n\t\t\t\t} else {\n\t\t\t\t\tconst found = await findSchemaFile(projectRoot)\n\t\t\t\t\tif (!found) {\n\t\t\t\t\t\tthrow new SchemaNotFoundError([\n\t\t\t\t\t\t\t'src/schema.ts',\n\t\t\t\t\t\t\t'schema.ts',\n\t\t\t\t\t\t\t'src/schema.js',\n\t\t\t\t\t\t\t'schema.js',\n\t\t\t\t\t\t])\n\t\t\t\t\t}\n\t\t\t\t\tschemaPath = found\n\t\t\t\t}\n\n\t\t\t\tlogger.step(`Reading schema from ${schemaPath}...`)\n\n\t\t\t\t// Dynamic import the schema file\n\t\t\t\tconst schemaModule: unknown = await import(schemaPath)\n\t\t\t\tconst schema = extractSchema(schemaModule)\n\n\t\t\t\tif (!schema) {\n\t\t\t\t\tlogger.error('Schema file must export a SchemaDefinition as the default export.')\n\t\t\t\t\tprocess.exitCode = 1\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Generate types\n\t\t\t\tconst output = generateTypes(schema)\n\t\t\t\tconst outputFile = typeof args.output === 'string' ? args.output : 'kora/generated/types.ts'\n\t\t\t\tconst outputPath = resolve(projectRoot, outputFile)\n\n\t\t\t\tawait mkdir(dirname(outputPath), { recursive: true })\n\t\t\t\tawait writeFile(outputPath, output, 'utf-8')\n\n\t\t\t\tlogger.success(`Generated types at ${outputPath}`)\n\t\t\t},\n\t\t}),\n\t\thooks: defineCommand({\n\t\t\tmeta: {\n\t\t\t\tname: 'hooks',\n\t\t\t\tdescription: 'Generate per-collection React hook stubs',\n\t\t\t},\n\t\t\targs: {\n\t\t\t\tschema: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Path to schema file',\n\t\t\t\t},\n\t\t\t\toutput: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Output directory for hooks',\n\t\t\t\t\tdefault: 'kora/generated/hooks',\n\t\t\t\t},\n\t\t\t\ttypes: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'Relative import path to generated types from hook files',\n\t\t\t\t\tdefault: '../types',\n\t\t\t\t},\n\t\t\t},\n\t\t\tasync run({ args }) {\n\t\t\t\tconst logger = createLogger()\n\t\t\t\tconst projectRoot = await findProjectRoot()\n\t\t\t\tif (!projectRoot) {\n\t\t\t\t\tthrow new InvalidProjectError(process.cwd())\n\t\t\t\t}\n\n\t\t\t\tlet schemaPath: string\n\t\t\t\tif (args.schema && typeof args.schema === 'string') {\n\t\t\t\t\tschemaPath = resolve(projectRoot, args.schema)\n\t\t\t\t} else {\n\t\t\t\t\tconst found = await findSchemaFile(projectRoot)\n\t\t\t\t\tif (!found) {\n\t\t\t\t\t\tthrow new SchemaNotFoundError([\n\t\t\t\t\t\t\t'src/schema.ts',\n\t\t\t\t\t\t\t'schema.ts',\n\t\t\t\t\t\t\t'src/schema.js',\n\t\t\t\t\t\t\t'schema.js',\n\t\t\t\t\t\t])\n\t\t\t\t\t}\n\t\t\t\t\tschemaPath = found\n\t\t\t\t}\n\n\t\t\t\tconst schema = await loadSchemaDefinition(schemaPath, projectRoot)\n\t\t\t\tconst outputDir =\n\t\t\t\t\ttypeof args.output === 'string'\n\t\t\t\t\t\t? resolve(projectRoot, args.output)\n\t\t\t\t\t\t: resolve(projectRoot, 'kora/generated/hooks')\n\n\t\t\t\tconst files = generateCollectionHooks(schema)\n\t\t\t\tfor (const [name, content] of files) {\n\t\t\t\t\tconst adjusted =\n\t\t\t\t\t\ttypeof args.types === 'string' && args.types !== '../types'\n\t\t\t\t\t\t\t? content.replace(\"from '../types'\", `from '${args.types}'`)\n\t\t\t\t\t\t\t: content\n\t\t\t\t\tconst filePath = resolve(outputDir, name)\n\t\t\t\t\tawait mkdir(dirname(filePath), { recursive: true })\n\t\t\t\t\tawait writeFile(filePath, adjusted, 'utf-8')\n\t\t\t\t}\n\n\t\t\t\tlogger.success(`Generated ${String(files.size)} hook file(s) at ${outputDir}`)\n\t\t\t\tlogger.step('Run `kora generate types` first if ../types is missing.')\n\t\t\t},\n\t\t}),\n\t},\n})\n\nfunction extractSchema(mod: unknown): SchemaDefinition | null {\n\tif (typeof mod !== 'object' || mod === null) return null\n\tconst record = mod as Record<string, unknown>\n\n\t// Check for default export\n\tconst candidate = record.default ?? record\n\tif (isSchemaDefinition(candidate)) return candidate\n\n\treturn null\n}\n\nfunction isSchemaDefinition(value: unknown): value is SchemaDefinition {\n\tif (typeof value !== 'object' || value === null) return false\n\tconst obj = value as Record<string, unknown>\n\treturn (\n\t\ttypeof obj.version === 'number' &&\n\t\ttypeof obj.collections === 'object' &&\n\t\tobj.collections !== null\n\t)\n}\n","import type { SchemaDefinition } from '@korajs/core'\n\n/**\n * Generates per-collection React hook stubs from a schema.\n *\n * @param schema - Validated schema definition\n * @returns Map of file basename to file contents\n */\nexport function generateCollectionHooks(schema: SchemaDefinition): Map<string, string> {\n\tconst files = new Map<string, string>()\n\n\tfor (const collectionName of Object.keys(schema.collections)) {\n\t\tconst pascal = toPascalCase(collectionName)\n\t\tconst hookName = `use${pascal}`\n\n\t\tconst content = [\n\t\t\t'// Auto-generated by `kora generate hooks` — safe to edit',\n\t\t\t`// Schema v${String(schema.version)}`,\n\t\t\t'',\n\t\t\t\"import { useCollection, useMutation, useQuery } from '@korajs/react'\",\n\t\t\t`import type { ${pascal}InsertInput, ${pascal}Record, ${pascal}UpdateInput } from '../types'`,\n\t\t\t'',\n\t\t\t'/**',\n\t\t\t` * Collection hook for \\`${collectionName}\\`.`,\n\t\t\t' * Add useQuery(...) calls with your QueryBuilder factories.',\n\t\t\t' */',\n\t\t\t`export function ${hookName}() {`,\n\t\t\t`\\tconst ${collectionName} = useCollection('${collectionName}')`,\n\t\t\t'',\n\t\t\t`\\tconst insert = useMutation((data: ${pascal}InsertInput) => ${collectionName}.insert(data))`,\n\t\t\t`\\tconst update = useMutation((id: string, data: ${pascal}UpdateInput) =>`,\n\t\t\t`\\t\\t${collectionName}.update(id, data),`,\n\t\t\t'\\t)',\n\t\t\t`\\tconst remove = useMutation((id: string) => ${collectionName}.delete(id))`,\n\t\t\t'',\n\t\t\t'\\treturn {',\n\t\t\t`\\t\\t${collectionName},`,\n\t\t\t'\\t\\tinsert,',\n\t\t\t'\\t\\tupdate,',\n\t\t\t'\\t\\tremove,',\n\t\t\t'\\t}',\n\t\t\t'}',\n\t\t\t'',\n\t\t].join('\\n')\n\n\t\tfiles.set(`${collectionName}.ts`, content)\n\t}\n\n\tconst indexLines = [\n\t\t'// Auto-generated by `kora generate hooks`',\n\t\t'',\n\t\t...Object.keys(schema.collections).map((name) => {\n\t\t\tconst pascal = toPascalCase(name)\n\t\t\treturn `export { use${pascal} } from './${name}'`\n\t\t}),\n\t\t'',\n\t]\n\n\tfiles.set('index.ts', indexLines.join('\\n'))\n\treturn files\n}\n\nfunction toPascalCase(value: string): string {\n\treturn value\n\t\t.split(/[-_]/)\n\t\t.filter((part) => part.length > 0)\n\t\t.map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n\t\t.join('')\n}\n","import { defineCommand } from 'citty'\nimport { createLogger } from '../../utils/logger'\n\nconst DEFAULT_SYNC_PORT = 3001\nconst EVENTS_ENDPOINT = '/__kora/events'\n\n/**\n * The `logs` command — streams real-time events from a Kora sync server.\n */\nexport const logsCommand = defineCommand({\n\tmeta: {\n\t\tname: 'logs',\n\t\tdescription: 'Stream real-time events from a Kora sync server',\n\t},\n\targs: {\n\t\turl: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Sync server URL (default: http://localhost:3001)',\n\t\t\tdefault: `http://localhost:${DEFAULT_SYNC_PORT}`,\n\t\t},\n\t\tfollow: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Follow log output (like tail -f)',\n\t\t\tdefault: true,\n\t\t\talias: 'f',\n\t\t},\n\t\tlevel: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Filter by log level (info, warn, error)',\n\t\t},\n\t\ttoken: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Admin token (defaults to KORA_ADMIN_TOKEN)',\n\t\t},\n\t},\n\tasync run({ args }) {\n\t\tconst logger = createLogger()\n\t\tconst url = typeof args.url === 'string' ? args.url : `http://localhost:${DEFAULT_SYNC_PORT}`\n\t\tconst follow = args.follow !== false\n\t\tconst levelFilter = typeof args.level === 'string' ? args.level : null\n\t\tconst token =\n\t\t\ttypeof args.token === 'string' ? args.token : (process.env.KORA_ADMIN_TOKEN ?? undefined)\n\t\tconst eventsUrl = `${url.replace(/\\/$/, '')}${EVENTS_ENDPOINT}`\n\n\t\tlogger.banner()\n\t\tlogger.info(`Connecting to ${eventsUrl}...`)\n\t\tlogger.blank()\n\n\t\ttry {\n\t\t\tconst response = await fetch(eventsUrl, {\n\t\t\t\theaders: token ? { Authorization: `Bearer ${token}` } : undefined,\n\t\t\t})\n\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Failed to connect to ${eventsUrl}: ${response.status} ${response.statusText}`,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst reader = response.body?.getReader()\n\t\t\tif (!reader) {\n\t\t\t\tthrow new Error('Response body is not readable')\n\t\t\t}\n\n\t\t\tconst decoder = new TextDecoder()\n\t\t\tlet buffer = ''\n\n\t\t\tconst processLine = (line: string) => {\n\t\t\t\t// SSE format: \"event: <type>\\ndata: <json>\\n\\n\"\n\t\t\t\tif (line.startsWith('event: ')) {\n\t\t\t\t\treturn // We handle the data line\n\t\t\t\t}\n\t\t\t\tif (line.startsWith('data: ')) {\n\t\t\t\t\tconst data = line.slice(6)\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst parsed = JSON.parse(data) as Record<string, unknown>\n\t\t\t\t\t\tconst level = String(parsed.level ?? 'info')\n\n\t\t\t\t\t\tif (levelFilter && level !== levelFilter) return\n\n\t\t\t\t\t\tconst timestamp = parsed.timestamp\n\t\t\t\t\t\t\t? new Date(parsed.timestamp as number).toISOString()\n\t\t\t\t\t\t\t: ''\n\t\t\t\t\t\tconst event = String(parsed.event ?? 'unknown')\n\t\t\t\t\t\tconst nodeId = parsed.nodeId ? ` [${parsed.nodeId}]` : ''\n\t\t\t\t\t\tconst session = parsed.sessionId ? ` <${parsed.sessionId}>` : ''\n\t\t\t\t\t\tconst count = parsed.count ? ` (${parsed.count})` : ''\n\t\t\t\t\t\tconst error = parsed.error ? ` — ${parsed.error}` : ''\n\n\t\t\t\t\t\tconst prefix = level === 'error' ? '✗' : level === 'warn' ? '⚠' : '●'\n\t\t\t\t\t\tconst color =\n\t\t\t\t\t\t\tlevel === 'error' ? '\\x1b[31m' : level === 'warn' ? '\\x1b[33m' : '\\x1b[36m'\n\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t`${color}${prefix}${'\\x1b[0m'} ${timestamp.slice(11, 23)} ${event}${nodeId}${session}${count}${error}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Ignore parse errors on malformed data\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst read = async () => {\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst { done, value } = await reader.read()\n\t\t\t\t\tif (done) break\n\n\t\t\t\t\tbuffer += decoder.decode(value, { stream: true })\n\t\t\t\t\tconst lines = buffer.split('\\n')\n\t\t\t\t\tbuffer = lines.pop() ?? ''\n\n\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\tprocessLine(line.trim())\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!follow) break\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait read()\n\t\t} catch (error) {\n\t\t\tlogger.error(`Failed to connect to ${eventsUrl}`)\n\t\t\tif (error instanceof Error) {\n\t\t\t\tlogger.error(error.message)\n\t\t\t}\n\t\t\tlogger.blank()\n\t\t\tlogger.step('Make sure the Kora sync server is running.')\n\t\t\tlogger.step('Start it with: kora dev')\n\t\t\tprocess.exit(1)\n\t\t}\n\t},\n})\n","import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises'\nimport { dirname, join, resolve } from 'node:path'\nimport type { SchemaDefinition } from '@korajs/core'\nimport { defineCommand } from 'citty'\nimport { InvalidProjectError, SchemaNotFoundError } from '../../errors'\nimport { findProjectRoot, findSchemaFile } from '../../utils/fs-helpers'\nimport { createLogger } from '../../utils/logger'\nimport { promptConfirm } from '../../utils/prompt'\nimport { loadKoraConfig } from '../dev/kora-config'\nimport { generateMigration } from './migration-generator'\nimport { runMigration } from './migration-runner'\nimport { generateOperationTransformModule } from './operation-transform-generator'\nimport { diffSchemas } from './schema-differ'\nimport { loadSchemaDefinition } from './schema-loader'\n\nconst SNAPSHOT_PATH = 'kora/schema.snapshot.json'\nconst MIGRATIONS_DIR = 'kora/migrations'\n\ninterface MigrationManifest {\n\tid: string\n\tfromVersion: number\n\ttoVersion: number\n\tup: string[]\n\tdown: string[]\n\tsummary: string[]\n\tcontainsBreakingChanges: boolean\n}\n\n/**\n * The `migrate` command — detects schema changes and generates migration artifacts.\n */\nexport const migrateCommand = defineCommand({\n\tmeta: {\n\t\tname: 'migrate',\n\t\tdescription: 'Detect schema changes and generate/apply migrations',\n\t},\n\targs: {\n\t\tapply: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Apply migration to configured database backends',\n\t\t\tdefault: false,\n\t\t},\n\t\tschema: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Path to schema file',\n\t\t},\n\t\tdb: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'SQLite database path for --apply (overrides config)',\n\t\t},\n\t\t'output-dir': {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Migration output directory',\n\t\t\tdefault: MIGRATIONS_DIR,\n\t\t},\n\t\t'dry-run': {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Preview migration changes without writing files',\n\t\t\tdefault: false,\n\t\t},\n\t\tforce: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Skip breaking-change confirmation prompts',\n\t\t\tdefault: false,\n\t\t},\n\t},\n\tasync run({ args }) {\n\t\tconst logger = createLogger()\n\n\t\tconst projectRoot = await findProjectRoot()\n\t\tif (!projectRoot) {\n\t\t\tthrow new InvalidProjectError(process.cwd())\n\t\t}\n\n\t\tconst config = await loadKoraConfig(projectRoot)\n\t\tconst resolvedSchemaPath =\n\t\t\ttypeof args.schema === 'string'\n\t\t\t\t? resolve(projectRoot, args.schema)\n\t\t\t\t: typeof config?.schema === 'string'\n\t\t\t\t\t? resolve(projectRoot, config.schema)\n\t\t\t\t\t: await findSchemaFile(projectRoot)\n\n\t\tif (!resolvedSchemaPath) {\n\t\t\tthrow new SchemaNotFoundError(['src/schema.ts', 'schema.ts', 'src/schema.js', 'schema.js'])\n\t\t}\n\n\t\tconst currentSchema = await loadSchemaDefinition(resolvedSchemaPath, projectRoot)\n\n\t\tconst snapshotFile = join(projectRoot, SNAPSHOT_PATH)\n\t\tconst previousSchema = await readSchemaSnapshot(snapshotFile)\n\n\t\tif (!previousSchema) {\n\t\t\tif (args['dry-run'] === true) {\n\t\t\t\tlogger.info('No schema snapshot found. Dry run: baseline snapshot would be created.')\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tawait writeSchemaSnapshot(snapshotFile, currentSchema)\n\t\t\tlogger.success(`Initialized schema snapshot at ${snapshotFile}`)\n\t\t\tlogger.step('Run `kora migrate` again after schema changes to generate migrations.')\n\t\t\treturn\n\t\t}\n\n\t\tconst diff = diffSchemas(previousSchema, currentSchema)\n\t\tconst outputDir =\n\t\t\ttypeof args['output-dir'] === 'string'\n\t\t\t\t? resolve(projectRoot, args['output-dir'])\n\t\t\t\t: resolve(projectRoot, MIGRATIONS_DIR)\n\n\t\tif (!diff.hasChanges) {\n\t\t\tlogger.success('No schema changes detected.')\n\t\t\tif (args.apply === true) {\n\t\t\t\tconst sqlitePath = resolveSqliteApplyPath(args.db, projectRoot, config)\n\t\t\t\tconst postgresConnectionString = resolvePostgresConnectionString(config)\n\t\t\t\tconst pending = await listMigrationManifests(outputDir)\n\n\t\t\t\tif (pending.length === 0) {\n\t\t\t\t\tlogger.step('No migration files found to apply.')\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tfor (const manifest of pending) {\n\t\t\t\t\tconst report = await runMigration({\n\t\t\t\t\t\tupStatements: manifest.up,\n\t\t\t\t\t\tmigrationId: manifest.id,\n\t\t\t\t\t\tfromVersion: manifest.fromVersion,\n\t\t\t\t\t\ttoVersion: manifest.toVersion,\n\t\t\t\t\t\tsqlitePath,\n\t\t\t\t\t\tpostgresConnectionString,\n\t\t\t\t\t\tprojectRoot,\n\t\t\t\t\t})\n\n\t\t\t\t\tfor (const backend of report.backends) {\n\t\t\t\t\t\tlogger.step(\n\t\t\t\t\t\t\t` ${manifest.id} -> ${backend.backend}: applied=${backend.statementsApplied}, skipped=${backend.skipped}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tconst generated = generateMigration(previousSchema, currentSchema, diff)\n\n\t\tlogger.banner()\n\t\tlogger.info(`Detected schema change: v${diff.fromVersion} → v${diff.toVersion}`)\n\t\tlogger.blank()\n\t\tlogger.info('Changes:')\n\t\tfor (const line of generated.summary) {\n\t\t\tlogger.step(` ${line}`)\n\t\t}\n\n\t\tif (diff.hasBreakingChanges && args['dry-run'] !== true) {\n\t\t\tlogger.blank()\n\t\t\tlogger.warn('Breaking schema changes detected.')\n\t\t\tconst shouldContinue = await confirmBreakingChanges(args.force === true)\n\t\t\tif (!shouldContinue) {\n\t\t\t\tlogger.warn('Migration generation aborted.')\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tif (args['dry-run'] === true) {\n\t\t\tlogger.blank()\n\t\t\tlogger.warn('Dry run enabled: no files written, no migrations applied.')\n\t\t\treturn\n\t\t}\n\n\t\tawait mkdir(outputDir, { recursive: true })\n\n\t\tconst migrationPath = await writeMigrationFile(\n\t\t\toutputDir,\n\t\t\tdiff.fromVersion,\n\t\t\tdiff.toVersion,\n\t\t\tgenerated,\n\t\t)\n\t\tawait writeSchemaSnapshot(snapshotFile, currentSchema)\n\n\t\tlogger.blank()\n\t\tlogger.success(`Generated migration: ${migrationPath}`)\n\n\t\tif (args.apply === true) {\n\t\t\tconst sqlitePath = resolveSqliteApplyPath(args.db, projectRoot, config)\n\t\t\tconst postgresConnectionString = resolvePostgresConnectionString(config)\n\t\t\tconst pending = await listMigrationManifests(outputDir)\n\n\t\t\tfor (const manifest of pending) {\n\t\t\t\tconst report = await runMigration({\n\t\t\t\t\tupStatements: manifest.up,\n\t\t\t\t\tmigrationId: manifest.id,\n\t\t\t\t\tfromVersion: manifest.fromVersion,\n\t\t\t\t\ttoVersion: manifest.toVersion,\n\t\t\t\t\tsqlitePath,\n\t\t\t\t\tpostgresConnectionString,\n\t\t\t\t\tprojectRoot,\n\t\t\t\t})\n\n\t\t\t\tfor (const backend of report.backends) {\n\t\t\t\t\tlogger.step(\n\t\t\t\t\t\t` ${manifest.id} -> ${backend.backend}: applied=${backend.statementsApplied}, skipped=${backend.skipped}, history=${backend.historyRecorded}`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlogger.success('Applied pending migrations successfully.')\n\t\t}\n\t},\n})\n\nasync function readSchemaSnapshot(path: string): Promise<SchemaDefinition | null> {\n\ttry {\n\t\tconst content = await readFile(path, 'utf-8')\n\t\treturn JSON.parse(content) as SchemaDefinition\n\t} catch {\n\t\treturn null\n\t}\n}\n\nasync function confirmBreakingChanges(force: boolean): Promise<boolean> {\n\tif (force) {\n\t\treturn true\n\t}\n\n\tif (!isInteractiveTerminal()) {\n\t\tthrow new Error(\n\t\t\t'Breaking schema changes require confirmation. Re-run with --force to continue or --dry-run to preview.',\n\t\t)\n\t}\n\n\treturn await promptConfirm('Continue and generate a breaking migration?', false)\n}\n\nfunction isInteractiveTerminal(): boolean {\n\treturn process.stdin.isTTY === true && process.stdout.isTTY === true\n}\n\nasync function writeSchemaSnapshot(path: string, schema: SchemaDefinition): Promise<void> {\n\tawait mkdir(dirname(path), { recursive: true })\n\tawait writeFile(path, `${JSON.stringify(schema, null, 2)}\\n`, 'utf-8')\n}\n\nasync function writeMigrationFile(\n\toutputDir: string,\n\tfromVersion: number,\n\ttoVersion: number,\n\tgenerated: ReturnType<typeof generateMigration>,\n): Promise<string> {\n\tconst existing = await readdir(outputDir).catch(() => [])\n\tconst sequence = existing.filter((file) => /^\\d{3}-/.test(file)).length + 1\n\tconst filename = `${String(sequence).padStart(3, '0')}-v${fromVersion}-to-v${toVersion}.ts`\n\tconst path = join(outputDir, filename)\n\tconst migrationId = filename.replace(/\\.ts$/, '')\n\n\tconst fileContent = [\n\t\t`export const up = ${JSON.stringify(generated.up, null, 2)} as const`,\n\t\t'',\n\t\t`export const down = ${JSON.stringify(generated.down, null, 2)} as const`,\n\t\t'',\n\t\t`export const summary = ${JSON.stringify(generated.summary, null, 2)} as const`,\n\t\t'',\n\t\t`export const containsBreakingChanges = ${generated.containsBreakingChanges}`,\n\t\t'',\n\t].join('\\n')\n\n\tawait writeFile(path, fileContent, 'utf-8')\n\n\tconst transformsPath = join(outputDir, `${migrationId}.transforms.ts`)\n\tawait writeFile(transformsPath, generateOperationTransformModule(fromVersion, toVersion), 'utf-8')\n\tawait writeMigrationManifest(join(outputDir, `${migrationId}.json`), {\n\t\tid: migrationId,\n\t\tfromVersion,\n\t\ttoVersion,\n\t\tup: generated.up,\n\t\tdown: generated.down,\n\t\tsummary: generated.summary,\n\t\tcontainsBreakingChanges: generated.containsBreakingChanges,\n\t})\n\treturn path\n}\n\nasync function writeMigrationManifest(path: string, manifest: MigrationManifest): Promise<void> {\n\tawait writeFile(path, `${JSON.stringify(manifest, null, 2)}\\n`, 'utf-8')\n}\n\nasync function listMigrationManifests(outputDir: string): Promise<MigrationManifest[]> {\n\tconst files = await readdir(outputDir).catch(() => [])\n\tconst migrationFiles = files\n\t\t.filter((file) => /^\\d{3}-.*\\.ts$/.test(file))\n\t\t.sort((left, right) => left.localeCompare(right))\n\n\tconst manifests: MigrationManifest[] = []\n\tfor (const file of migrationFiles) {\n\t\tconst id = file.replace(/\\.ts$/, '')\n\t\tconst manifestPath = join(outputDir, `${id}.json`)\n\t\tconst jsonManifest = await readMigrationManifest(manifestPath)\n\n\t\tif (jsonManifest) {\n\t\t\tmanifests.push({ ...jsonManifest, id })\n\t\t\tcontinue\n\t\t}\n\n\t\tconst migrationPath = join(outputDir, file)\n\t\tconst sourceManifest = await readMigrationManifestFromSource(migrationPath, id)\n\t\tmanifests.push(sourceManifest)\n\t}\n\n\treturn manifests\n}\n\nasync function readMigrationManifest(path: string): Promise<MigrationManifest | null> {\n\ttry {\n\t\tconst content = await readFile(path, 'utf-8')\n\t\treturn JSON.parse(content) as MigrationManifest\n\t} catch (error) {\n\t\tconst code = (error as NodeJS.ErrnoException).code\n\t\tif (code === 'ENOENT') {\n\t\t\treturn null\n\t\t}\n\t\tthrow error\n\t}\n}\n\nasync function readMigrationManifestFromSource(\n\tpath: string,\n\tid: string,\n): Promise<MigrationManifest> {\n\tconst content = await readFile(path, 'utf-8')\n\tconst versions = parseVersionsFromMigrationId(id)\n\n\treturn {\n\t\tid,\n\t\tfromVersion: versions.fromVersion,\n\t\ttoVersion: versions.toVersion,\n\t\tup: parseStringArrayExport(content, 'up'),\n\t\tdown: parseStringArrayExport(content, 'down'),\n\t\tsummary: parseStringArrayExport(content, 'summary'),\n\t\tcontainsBreakingChanges: parseBooleanExport(content, 'containsBreakingChanges'),\n\t}\n}\n\nfunction parseVersionsFromMigrationId(id: string): { fromVersion: number; toVersion: number } {\n\tconst match = id.match(/-v(\\d+)-to-v(\\d+)$/)\n\tif (!match) {\n\t\tthrow new Error(`Migration id \"${id}\" does not include a vX-to-vY version suffix.`)\n\t}\n\n\tconst fromVersionText = match[1]\n\tconst toVersionText = match[2]\n\tif (fromVersionText === undefined || toVersionText === undefined) {\n\t\tthrow new Error(`Migration id \"${id}\" does not include a vX-to-vY version suffix.`)\n\t}\n\n\treturn {\n\t\tfromVersion: Number.parseInt(fromVersionText, 10),\n\t\ttoVersion: Number.parseInt(toVersionText, 10),\n\t}\n}\n\nfunction parseStringArrayExport(source: string, exportName: 'up' | 'down' | 'summary'): string[] {\n\tconst expression = parseExportExpression(source, exportName)\n\tconst parsed = JSON.parse(expression) as unknown\n\tif (!Array.isArray(parsed) || parsed.some((item) => typeof item !== 'string')) {\n\t\tthrow new Error(`Migration export \"${exportName}\" must be a string array.`)\n\t}\n\n\treturn parsed\n}\n\nfunction parseBooleanExport(source: string, exportName: 'containsBreakingChanges'): boolean {\n\tconst expression = parseLiteralExport(source, exportName)\n\tif (expression === 'true') return true\n\tif (expression === 'false') return false\n\tthrow new Error(`Migration export \"${exportName}\" must be a boolean literal.`)\n}\n\nfunction parseExportExpression(source: string, exportName: string): string {\n\tconst escapedName = exportName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\tconst regex = new RegExp(`export const ${escapedName} = ([\\\\s\\\\S]*?) as const`)\n\tconst match = source.match(regex)\n\tif (!match || !match[1]) {\n\t\tthrow new Error(`Failed to read migration export \"${exportName}\".`)\n\t}\n\n\treturn match[1].trim()\n}\n\nfunction parseLiteralExport(source: string, exportName: string): string {\n\tconst escapedName = exportName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\tconst regex = new RegExp(`export const ${escapedName} = ([^\\n\\r]+)`)\n\tconst match = source.match(regex)\n\tif (!match || !match[1]) {\n\t\tthrow new Error(`Failed to read migration export \"${exportName}\".`)\n\t}\n\n\treturn match[1].trim()\n}\n\nfunction resolveSqliteApplyPath(\n\tdbArg: unknown,\n\tprojectRoot: string,\n\tconfig: Awaited<ReturnType<typeof loadKoraConfig>>,\n): string | undefined {\n\tif (typeof dbArg === 'string') {\n\t\treturn resolve(projectRoot, dbArg)\n\t}\n\n\tconst sync = config?.dev?.sync\n\tif (typeof sync === 'object' && sync !== null) {\n\t\tif (sync.store === 'sqlite') {\n\t\t\treturn join(projectRoot, 'kora-sync.db')\n\t\t}\n\t\tif (typeof sync.store === 'object' && sync.store !== null && sync.store.type === 'sqlite') {\n\t\t\tif (typeof sync.store.filename === 'string' && sync.store.filename.length > 0) {\n\t\t\t\treturn resolve(projectRoot, sync.store.filename)\n\t\t\t}\n\t\t\treturn join(projectRoot, 'kora-sync.db')\n\t\t}\n\t}\n\n\treturn undefined\n}\n\nfunction resolvePostgresConnectionString(\n\tconfig: Awaited<ReturnType<typeof loadKoraConfig>>,\n): string | undefined {\n\tconst sync = config?.dev?.sync\n\tif (typeof sync !== 'object' || sync === null) return undefined\n\n\tif (sync.store === 'postgres') {\n\t\treturn process.env.DATABASE_URL\n\t}\n\n\tif (typeof sync.store === 'object' && sync.store !== null && sync.store.type === 'postgres') {\n\t\treturn sync.store.connectionString\n\t}\n\n\treturn undefined\n}\n","import { generateSQL } from '@korajs/core'\nimport type { CollectionDefinition, FieldDescriptor, SchemaDefinition } from '@korajs/core'\nimport type { SchemaDiff } from './schema-differ'\nimport { getChangedCollections } from './schema-differ'\nimport {\n\ttype EvolveTableTarget,\n\tevolveFieldSpec,\n\tformatEvolveTableDirective,\n} from './table-evolution-directive'\nimport { formatRelaxValueDomainDirective } from './value-domain-directive'\n\nexport interface GeneratedMigration {\n\tup: string[]\n\tdown: string[]\n\tsummary: string[]\n\tcontainsBreakingChanges: boolean\n}\n\n/**\n * Generates SQL up/down migration statements from a schema diff.\n */\nexport function generateMigration(\n\tprevious: SchemaDefinition,\n\tcurrent: SchemaDefinition,\n\tdiff: SchemaDiff,\n): GeneratedMigration {\n\tconst up: string[] = []\n\t// Each change's inverse is one group of statements in its own order; the groups run\n\t// in reverse order of the changes they undo.\n\tconst downGroups: string[][] = []\n\n\tfor (const change of diff.changes) {\n\t\tif (change.type === 'collection-added') {\n\t\t\tconst collectionDef = current.collections[change.collection]\n\t\t\tif (!collectionDef) continue\n\t\t\tup.push(...generateSQL(change.collection, collectionDef))\n\t\t\tdownGroups.push(dropCollectionStatements(change.collection))\n\t\t}\n\n\t\tif (change.type === 'collection-removed') {\n\t\t\tconst collectionDef = previous.collections[change.collection]\n\t\t\tup.push(...dropCollectionStatements(change.collection))\n\t\t\tif (collectionDef) {\n\t\t\t\tdownGroups.push(generateSQL(change.collection, collectionDef))\n\t\t\t}\n\t\t}\n\t}\n\n\tconst changedCollections = getChangedCollections(diff).filter(\n\t\t(collection) =>\n\t\t\tcollection in previous.collections &&\n\t\t\tcollection in current.collections &&\n\t\t\tdiff.changes.some(\n\t\t\t\t(change) =>\n\t\t\t\t\tchange.collection === collection &&\n\t\t\t\t\t(change.type === 'field-added' ||\n\t\t\t\t\t\tchange.type === 'field-removed' ||\n\t\t\t\t\t\tchange.type === 'field-changed' ||\n\t\t\t\t\t\tchange.type === 'index-added' ||\n\t\t\t\t\t\tchange.type === 'index-removed'),\n\t\t\t),\n\t)\n\n\tfor (const collection of changedCollections) {\n\t\tconst previousDef = previous.collections[collection]\n\t\tconst currentDef = current.collections[collection]\n\t\tif (!previousDef || !currentDef) continue\n\n\t\t// A change to a field's value domain only (enum values, requiredness, default) needs\n\t\t// no new table shape: the value domain is enforced by validation on every replica\n\t\t// (RT-101). What it needs is the removal of the constraints beta.12 and earlier DDL\n\t\t// restated it with (an enum CHECK, NOT NULL), which a table cannot evolve. The\n\t\t// directive is expanded by `kora migrate --apply` against the live catalog of each\n\t\t// backend, in the migration's transaction (with its history row), and is a no-op on\n\t\t// tables that are already relaxed.\n\t\tconst valueDomainOnly = diff.changes.every(\n\t\t\t(change) =>\n\t\t\t\tchange.collection !== collection ||\n\t\t\t\t(change.type === 'field-changed' && isValueDomainChange(change.before, change.after)),\n\t\t)\n\t\tif (valueDomainOnly) {\n\t\t\tconst directive = relaxValueDomainDirective(collection, previousDef, currentDef)\n\t\t\tup.push(directive)\n\t\t\tdownGroups.push([directive])\n\t\t\tcontinue\n\t\t}\n\n\t\tvalidateRebuildSafety(collection, previousDef, currentDef)\n\n\t\t// The table keeps everything the migration does not name (RT-105): a client store's\n\t\t// `_version` / `_field_versions` and foreign keys, each store's indexes, the\n\t\t// Postgres server store's column types. So the change is a directive that\n\t\t// `kora migrate --apply` expands against each backend's live catalog (ADD / DROP\n\t\t// COLUMN, a catalog-driven SQLite rebuild), in the migration's transaction, after\n\t\t// relaxing beta.12 value-domain constraints the same way.\n\t\tconst relax = relaxValueDomainDirective(collection, previousDef, currentDef)\n\t\tup.push(relax, formatEvolveTableDirective(evolveTarget(collection, previousDef, currentDef)))\n\t\tdownGroups.push([\n\t\t\trelax,\n\t\t\tformatEvolveTableDirective(evolveTarget(collection, currentDef, previousDef)),\n\t\t])\n\t}\n\n\treturn {\n\t\tup,\n\t\tdown: downGroups.reverse().flat(),\n\t\tsummary: diff.changes.map(formatChange),\n\t\tcontainsBreakingChanges: diff.hasBreakingChanges,\n\t}\n}\n\n/**\n * Whether a field change touches only its value domain (same kind, item kind and auto\n * flag; enum values, requiredness or default differ).\n */\nfunction isValueDomainChange(before: FieldDescriptor, after: FieldDescriptor): boolean {\n\treturn (\n\t\tbefore.kind === after.kind && before.itemKind === after.itemKind && before.auto === after.auto\n\t)\n}\n\n/** The table changes that take a collection from `from` to `to`. */\nfunction evolveTarget(\n\tcollection: string,\n\tfrom: CollectionDefinition,\n\tto: CollectionDefinition,\n): EvolveTableTarget {\n\tconst target: EvolveTableTarget = {\n\t\ttable: collection,\n\t\tadd: {},\n\t\tdrop: [],\n\t\tchange: {},\n\t\taddIndexes: to.indexes.filter((field) => !from.indexes.includes(field)),\n\t\tremoveIndexes: from.indexes.filter((field) => !to.indexes.includes(field)),\n\t}\n\tfor (const [field, descriptor] of Object.entries(to.fields)) {\n\t\tconst before = from.fields[field]\n\t\tif (!before) {\n\t\t\ttarget.add[field] = evolveFieldSpec(descriptor)\n\t\t} else if (before.kind !== descriptor.kind || before.itemKind !== descriptor.itemKind) {\n\t\t\ttarget.change[field] = { from: evolveFieldSpec(before), to: evolveFieldSpec(descriptor) }\n\t\t}\n\t}\n\ttarget.drop = Object.keys(from.fields).filter((field) => !(field in to.fields))\n\treturn target\n}\n\nfunction relaxValueDomainDirective(\n\tcollection: string,\n\tfrom: CollectionDefinition,\n\tto: CollectionDefinition,\n): string {\n\tconst fields = [...new Set([...Object.keys(from.fields), ...Object.keys(to.fields)])].sort()\n\tconst enums = fields.filter(\n\t\t(field) => from.fields[field]?.kind === 'enum' || to.fields[field]?.kind === 'enum',\n\t)\n\treturn formatRelaxValueDomainDirective({ table: collection, fields, enums })\n}\n\nfunction validateRebuildSafety(\n\tcollection: string,\n\tfrom: CollectionDefinition,\n\tto: CollectionDefinition,\n): void {\n\tfor (const [fieldName, descriptor] of Object.entries(to.fields)) {\n\t\tif (fieldName in from.fields) continue\n\t\tif (descriptor.required && descriptor.defaultValue === undefined && !descriptor.auto) {\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot auto-migrate collection \"${collection}\": added required field \"${fieldName}\" has no default value.`,\n\t\t\t)\n\t\t}\n\t}\n\n\tfor (const [fieldName, targetDescriptor] of Object.entries(to.fields)) {\n\t\tconst sourceDescriptor = from.fields[fieldName]\n\t\tif (!sourceDescriptor) continue\n\t\tif (canTransformField(sourceDescriptor, targetDescriptor)) continue\n\n\t\tif (\n\t\t\ttargetDescriptor.required &&\n\t\t\ttargetDescriptor.defaultValue === undefined &&\n\t\t\t!targetDescriptor.auto\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot auto-migrate collection \"${collection}\": changed required field \"${fieldName}\" from ${sourceDescriptor.kind} to ${targetDescriptor.kind} without a safe transform/default.`,\n\t\t\t)\n\t\t}\n\t}\n}\n\nfunction canTransformField(source: FieldDescriptor, target: FieldDescriptor): boolean {\n\tif (source.kind === target.kind && source.itemKind === target.itemKind) {\n\t\treturn true\n\t}\n\n\tif (target.kind === 'string') {\n\t\treturn true\n\t}\n\n\tif (target.kind === 'number' || target.kind === 'timestamp') {\n\t\treturn (\n\t\t\tsource.kind === 'string' ||\n\t\t\tsource.kind === 'enum' ||\n\t\t\tsource.kind === 'number' ||\n\t\t\tsource.kind === 'timestamp' ||\n\t\t\tsource.kind === 'boolean'\n\t\t)\n\t}\n\n\tif (target.kind === 'boolean') {\n\t\treturn (\n\t\t\tsource.kind === 'number' ||\n\t\t\tsource.kind === 'timestamp' ||\n\t\t\tsource.kind === 'boolean' ||\n\t\t\tsource.kind === 'string' ||\n\t\t\tsource.kind === 'enum'\n\t\t)\n\t}\n\n\tif (target.kind === 'enum') {\n\t\treturn source.kind === 'string' || source.kind === 'enum'\n\t}\n\n\tif (target.kind === 'array') {\n\t\treturn source.kind === 'array' && source.itemKind === target.itemKind\n\t}\n\n\tif (target.kind === 'richtext') {\n\t\treturn source.kind === 'richtext'\n\t}\n\n\treturn false\n}\n\nfunction dropCollectionStatements(collection: string): string[] {\n\tconst table = quoteIdentifier(collection)\n\tconst opsTable = quoteIdentifier(`_kora_ops_${collection}`)\n\treturn [`DROP TABLE IF EXISTS ${table}`, `DROP TABLE IF EXISTS ${opsTable}`]\n}\n\nfunction quoteIdentifier(identifier: string): string {\n\tif (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(identifier)) {\n\t\tthrow new Error(`Invalid SQL identifier: ${identifier}`)\n\t}\n\t// Double-quote to match @korajs/core's generateSQL, so a generated migration\n\t// is internally consistent (CREATE from core, DROP/rebuild from here) even for\n\t// camelCase or reserved-word collection and column names.\n\treturn `\"${identifier}\"`\n}\n\nfunction formatChange(change: SchemaDiff['changes'][number]): string {\n\tswitch (change.type) {\n\t\tcase 'collection-added':\n\t\t\treturn `+ collection ${change.collection}`\n\t\tcase 'collection-removed':\n\t\t\treturn `- collection ${change.collection}`\n\t\tcase 'field-added':\n\t\t\treturn `+ ${change.collection}.${change.field}`\n\t\tcase 'field-removed':\n\t\t\treturn `- ${change.collection}.${change.field}`\n\t\tcase 'field-changed':\n\t\t\treturn `~ ${change.collection}.${change.field}`\n\t\tcase 'index-added':\n\t\t\treturn `+ index ${change.collection}.${change.index}`\n\t\tcase 'index-removed':\n\t\t\treturn `- index ${change.collection}.${change.index}`\n\t}\n}\n","import type { FieldDescriptor, SchemaDefinition } from '@korajs/core'\n\nexport type SchemaChange =\n\t| { type: 'collection-added'; collection: string }\n\t| { type: 'collection-removed'; collection: string }\n\t| { type: 'field-added'; collection: string; field: string; descriptor: FieldDescriptor }\n\t| { type: 'field-removed'; collection: string; field: string; descriptor: FieldDescriptor }\n\t| {\n\t\t\ttype: 'field-changed'\n\t\t\tcollection: string\n\t\t\tfield: string\n\t\t\tbefore: FieldDescriptor\n\t\t\tafter: FieldDescriptor\n\t }\n\t| { type: 'index-added'; collection: string; index: string }\n\t| { type: 'index-removed'; collection: string; index: string }\n\nexport interface SchemaDiff {\n\tfromVersion: number\n\ttoVersion: number\n\tchanges: SchemaChange[]\n\thasChanges: boolean\n\thasBreakingChanges: boolean\n}\n\n/**\n * Computes a structural schema diff.\n */\nexport function diffSchemas(previous: SchemaDefinition, current: SchemaDefinition): SchemaDiff {\n\tconst changes: SchemaChange[] = []\n\n\tconst previousCollections = new Set(Object.keys(previous.collections))\n\tconst currentCollections = new Set(Object.keys(current.collections))\n\n\tfor (const collection of currentCollections) {\n\t\tif (!previousCollections.has(collection)) {\n\t\t\tchanges.push({ type: 'collection-added', collection })\n\t\t}\n\t}\n\n\tfor (const collection of previousCollections) {\n\t\tif (!currentCollections.has(collection)) {\n\t\t\tchanges.push({ type: 'collection-removed', collection })\n\t\t}\n\t}\n\n\tfor (const collection of currentCollections) {\n\t\tif (!previousCollections.has(collection)) continue\n\n\t\tconst previousDef = previous.collections[collection]\n\t\tconst currentDef = current.collections[collection]\n\t\tif (!previousDef || !currentDef) continue\n\n\t\tconst previousFields = previousDef.fields\n\t\tconst currentFields = currentDef.fields\n\n\t\tfor (const [fieldName, currentField] of Object.entries(currentFields)) {\n\t\t\tconst previousField = previousFields[fieldName]\n\t\t\tif (!previousField) {\n\t\t\t\tchanges.push({\n\t\t\t\t\ttype: 'field-added',\n\t\t\t\t\tcollection,\n\t\t\t\t\tfield: fieldName,\n\t\t\t\t\tdescriptor: currentField,\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (!fieldDescriptorsEqual(previousField, currentField)) {\n\t\t\t\tchanges.push({\n\t\t\t\t\ttype: 'field-changed',\n\t\t\t\t\tcollection,\n\t\t\t\t\tfield: fieldName,\n\t\t\t\t\tbefore: previousField,\n\t\t\t\t\tafter: currentField,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tfor (const [fieldName, previousField] of Object.entries(previousFields)) {\n\t\t\tif (!(fieldName in currentFields)) {\n\t\t\t\tchanges.push({\n\t\t\t\t\ttype: 'field-removed',\n\t\t\t\t\tcollection,\n\t\t\t\t\tfield: fieldName,\n\t\t\t\t\tdescriptor: previousField,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tconst previousIndexes = new Set(previousDef.indexes)\n\t\tconst currentIndexes = new Set(currentDef.indexes)\n\n\t\tfor (const index of currentIndexes) {\n\t\t\tif (!previousIndexes.has(index)) {\n\t\t\t\tchanges.push({ type: 'index-added', collection, index })\n\t\t\t}\n\t\t}\n\n\t\tfor (const index of previousIndexes) {\n\t\t\tif (!currentIndexes.has(index)) {\n\t\t\t\tchanges.push({ type: 'index-removed', collection, index })\n\t\t\t}\n\t\t}\n\t}\n\n\tchanges.sort(compareChanges)\n\n\treturn {\n\t\tfromVersion: previous.version,\n\t\ttoVersion: current.version,\n\t\tchanges,\n\t\thasChanges: changes.length > 0,\n\t\thasBreakingChanges: changes.some(isBreakingChange),\n\t}\n}\n\nexport function getChangedCollections(diff: SchemaDiff): string[] {\n\tconst collections = new Set<string>()\n\tfor (const change of diff.changes) {\n\t\tcollections.add(change.collection)\n\t}\n\treturn [...collections].sort()\n}\n\nfunction isBreakingChange(change: SchemaChange): boolean {\n\tif (change.type === 'collection-removed' || change.type === 'field-removed') return true\n\tif (change.type === 'field-changed') {\n\t\tif (change.before.kind !== change.after.kind) return true\n\t\tif (change.before.itemKind !== change.after.itemKind) return true\n\t\t// Adding enum values only widens the value domain (RT-101); removing one refuses\n\t\t// writes of it from then on.\n\t\tconst kept = new Set(change.after.enumValues ?? [])\n\t\tif ((change.before.enumValues ?? []).some((value) => !kept.has(value))) return true\n\t\tif (change.before.required !== change.after.required && change.after.required) return true\n\t\treturn false\n\t}\n\tif (change.type === 'field-added') {\n\t\tconst descriptor = change.descriptor\n\t\treturn descriptor.required && descriptor.defaultValue === undefined && !descriptor.auto\n\t}\n\treturn false\n}\n\nfunction fieldDescriptorsEqual(left: FieldDescriptor, right: FieldDescriptor): boolean {\n\treturn (\n\t\tleft.kind === right.kind &&\n\t\tleft.required === right.required &&\n\t\tleft.defaultValue === right.defaultValue &&\n\t\tleft.auto === right.auto &&\n\t\tleft.itemKind === right.itemKind &&\n\t\tserializeEnum(left.enumValues) === serializeEnum(right.enumValues)\n\t)\n}\n\nfunction serializeEnum(values: readonly string[] | null): string {\n\tif (!values) return ''\n\treturn values.join('|')\n}\n\nfunction compareChanges(left: SchemaChange, right: SchemaChange): number {\n\tif (left.collection < right.collection) return -1\n\tif (left.collection > right.collection) return 1\n\n\tif (left.type < right.type) return -1\n\tif (left.type > right.type) return 1\n\n\tconst leftKey = 'field' in left ? left.field : 'index' in left ? left.index : ''\n\tconst rightKey = 'field' in right ? right.field : 'index' in right ? right.index : ''\n\n\tif (leftKey < rightKey) return -1\n\tif (leftKey > rightKey) return 1\n\treturn 0\n}\n","import type { FieldDescriptor } from '@korajs/core'\nimport {\n\ttype SqliteQueryFn,\n\ttype SqliteTableCatalog,\n\tcollectionIndexName,\n\tisKoraInternalColumn,\n\tparseSqliteCheckConstraints,\n\treadSqliteTableCatalog,\n\tsqlDefaultLiteral,\n\tsqliteCheckConstraintDefinition,\n\tsqliteCheckReferencesColumn,\n} from '@korajs/core/internal'\n\n/**\n * A generated migration statement that is not SQL but a directive: evolve one collection\n * table to a new set of schema fields and indexes (RT-105).\n *\n * The collection table is not Kora's alone to describe: a client store keeps `_version`\n * and `_field_versions` on it (and the relation's `REFERENCES`), each store creates its\n * own indexes, and Postgres server tables use other column types (BIGINT, DOUBLE\n * PRECISION, JSONB, BYTEA) than SQLite ones. A fixed statement list that re-creates the\n * table from the schema loses all of that. So `kora migrate --apply` expands the directive\n * against each backend's live catalog, inside the migration's transaction, and touches\n * only the schema fields and indexes it names:\n *\n * - an added field: `ALTER TABLE ... ADD COLUMN` (nothing when the column already exists)\n * - a removed field, or a field whose kind changed: Postgres `DROP COLUMN` /\n * `ALTER COLUMN ... TYPE ... USING`; SQLite rebuilds the table from its catalog, copying\n * every other column, primary key, foreign key, `UNIQUE` constraint, index and trigger as\n * it is (only indexes on a removed column go)\n * - an added / removed index: `CREATE INDEX IF NOT EXISTS` / `DROP INDEX IF EXISTS`\n *\n * Expanding it on a table that already has the target shape yields nothing (idempotent).\n */\nexport const EVOLVE_TABLE_DIRECTIVE = '--kora:evolve-table'\n\n/** What a directive needs to know about a field (JSON-serializable). */\nexport interface EvolveFieldSpec {\n\tkind: FieldDescriptor['kind']\n\titemKind?: string\n\tenumValues?: string[]\n\t/** The field's default value (absent: no default) */\n\tdefault?: unknown\n\tauto?: boolean\n}\n\n/** The payload of an evolve-table directive. */\nexport interface EvolveTableTarget {\n\t/** The collection table */\n\ttable: string\n\t/** Fields of the target schema that the table does not have */\n\tadd: Record<string, EvolveFieldSpec>\n\t/** Fields the target schema no longer has */\n\tdrop: string[]\n\t/** Fields whose kind (or array item kind) changed */\n\tchange: Record<string, { from: EvolveFieldSpec; to: EvolveFieldSpec }>\n\t/** Fields that gained an index */\n\taddIndexes: string[]\n\t/** Fields that lost their index */\n\tremoveIndexes: string[]\n}\n\n/** The spec of a schema field descriptor. */\nexport function evolveFieldSpec(descriptor: FieldDescriptor): EvolveFieldSpec {\n\treturn {\n\t\tkind: descriptor.kind,\n\t\t...(descriptor.itemKind ? { itemKind: descriptor.itemKind } : {}),\n\t\t...(descriptor.enumValues ? { enumValues: [...descriptor.enumValues] } : {}),\n\t\t...(descriptor.defaultValue !== undefined ? { default: descriptor.defaultValue } : {}),\n\t\t...(descriptor.auto ? { auto: true } : {}),\n\t}\n}\n\n/** Render a directive statement for `target`. */\nexport function formatEvolveTableDirective(target: EvolveTableTarget): string {\n\treturn `${EVOLVE_TABLE_DIRECTIVE} ${JSON.stringify(target)}`\n}\n\n/** Whether a directive changes nothing. */\nexport function isEmptyEvolveTarget(target: EvolveTableTarget): boolean {\n\treturn (\n\t\tObject.keys(target.add).length === 0 &&\n\t\ttarget.drop.length === 0 &&\n\t\tObject.keys(target.change).length === 0 &&\n\t\ttarget.addIndexes.length === 0 &&\n\t\ttarget.removeIndexes.length === 0\n\t)\n}\n\n/**\n * The directive's target when `statement` is an evolve-table directive, otherwise null.\n *\n * @throws Error when the statement is a directive with a malformed payload\n */\nexport function parseEvolveTableDirective(statement: string): EvolveTableTarget | null {\n\tconst trimmed = statement.trimStart()\n\tif (!trimmed.startsWith(EVOLVE_TABLE_DIRECTIVE)) return null\n\tconst payload = trimmed.slice(EVOLVE_TABLE_DIRECTIVE.length).trim()\n\tlet parsed: unknown\n\ttry {\n\t\tparsed = JSON.parse(payload)\n\t} catch {\n\t\tparsed = null\n\t}\n\tconst target = parsed as Partial<EvolveTableTarget> | null\n\tconst isRecord = (value: unknown): value is Record<string, unknown> =>\n\t\ttypeof value === 'object' && value !== null && !Array.isArray(value)\n\tconst isStrings = (value: unknown): value is string[] =>\n\t\tArray.isArray(value) && value.every((item) => typeof item === 'string')\n\tconst isSpec = (value: unknown): value is EvolveFieldSpec =>\n\t\tisRecord(value) && typeof value.kind === 'string'\n\tif (\n\t\t!isRecord(target) ||\n\t\ttypeof target.table !== 'string' ||\n\t\t!isRecord(target.add) ||\n\t\t!Object.values(target.add).every(isSpec) ||\n\t\t!isStrings(target.drop) ||\n\t\t!isRecord(target.change) ||\n\t\t!Object.values(target.change).every(\n\t\t\t(change) => isRecord(change) && isSpec(change.from) && isSpec(change.to),\n\t\t) ||\n\t\t!isStrings(target.addIndexes) ||\n\t\t!isStrings(target.removeIndexes)\n\t) {\n\t\tthrow new Error(\n\t\t\t`Malformed migration directive \"${statement}\": expected ${EVOLVE_TABLE_DIRECTIVE} {\"table\", \"add\", \"drop\", \"change\", \"addIndexes\", \"removeIndexes\"}. Regenerate the migration with \\`kora migrate\\`.`,\n\t\t)\n\t}\n\treturn {\n\t\ttable: target.table,\n\t\tadd: target.add as Record<string, EvolveFieldSpec>,\n\t\tdrop: [...target.drop],\n\t\tchange: target.change as EvolveTableTarget['change'],\n\t\taddIndexes: [...target.addIndexes],\n\t\tremoveIndexes: [...target.removeIndexes],\n\t}\n}\n\n/**\n * The SQLite statements a directive expands to. Every column the directive does not name\n * (Kora's `id`, `_created_at`, `_updated_at`, `_version`, `_field_versions`, `_deleted`,\n * and anything else on the table) keeps its type, constraints, default and values.\n *\n * @param target - The directive's payload\n * @param query - Reads the catalog, inside the migration's transaction\n * @param now - Milliseconds since the epoch for `auto` timestamps of existing rows\n */\nexport async function expandEvolveTableForSqlite(\n\ttarget: EvolveTableTarget,\n\tquery: SqliteQueryFn,\n\tnow: number,\n): Promise<string[]> {\n\tconst catalog = await readSqliteTableCatalog(query, target.table)\n\tif (!catalog) return []\n\tconst table = quoteIdentifier(target.table)\n\tconst existing = new Map(\n\t\tcatalog.columns.map((column) => [column.name, column.type.toUpperCase()]),\n\t)\n\tconst plan = planColumns(target, existing, sqliteType)\n\tconst statements: string[] = []\n\n\tconst presentIndexes = await indexColumnsByName(query, target.table)\n\tconst removedIndexNames = new Set(\n\t\ttarget.removeIndexes\n\t\t\t.flatMap((field) => koraIndexNames(target.table, field))\n\t\t\t.filter((name) => presentIndexes.has(name)),\n\t)\n\tfor (const name of removedIndexNames) {\n\t\tstatements.push(`DROP INDEX IF EXISTS ${quoteIdentifier(name)}`)\n\t}\n\n\tif (plan.drop.length > 0 || plan.change.length > 0) {\n\t\tstatements.push(\n\t\t\t...(await sqliteRebuildStatements(catalog, plan, query, removedIndexNames, now)),\n\t\t)\n\t} else {\n\t\tfor (const [field, spec] of plan.add) {\n\t\t\tstatements.push(\n\t\t\t\t`ALTER TABLE ${table} ADD COLUMN ${quoteIdentifier(field)} ${sqliteType(spec)}${defaultClause(spec)}`,\n\t\t\t)\n\t\t\tif (spec.auto && spec.kind === 'timestamp' && spec.default === undefined) {\n\t\t\t\tstatements.push(`UPDATE ${table} SET ${quoteIdentifier(field)} = ${now}`)\n\t\t\t}\n\t\t}\n\t}\n\n\tconst indexed = await singleColumnIndexes(query, target.table, removedIndexNames)\n\tfor (const field of target.addIndexes) {\n\t\tif (indexed.has(field)) continue\n\t\tstatements.push(\n\t\t\t`CREATE INDEX IF NOT EXISTS ${koraIndexNames(target.table, field)[0]} ON ${table} (${quoteIdentifier(field)})`,\n\t\t)\n\t}\n\treturn statements\n}\n\n/**\n * The Postgres statements a directive expands to (a server store's table: its types are\n * the server's, see `@korajs/server` materialization). Columns the directive does not\n * name are never touched.\n *\n * @param target - The directive's payload\n * @param query - Reads the catalog, inside the migration's transaction\n * @param now - Milliseconds since the epoch for `auto` timestamps of existing rows\n */\nexport async function expandEvolveTableForPostgres(\n\ttarget: EvolveTableTarget,\n\tquery: SqliteQueryFn,\n\tnow: number,\n): Promise<string[]> {\n\tconst columns = await query(\n\t\t`SELECT column_name::text AS name, upper(data_type::text) AS type FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ${sqlText(target.table)}`,\n\t)\n\tif (columns.length === 0) return []\n\tconst table = quoteIdentifier(target.table)\n\tconst existing = new Map(columns.map((row) => [String(row.name), String(row.type)]))\n\tconst plan = planColumns(target, existing, postgresType)\n\tconst statements: string[] = []\n\n\tconst indexNames = new Set(\n\t\t(\n\t\t\tawait query(\n\t\t\t\t`SELECT indexname::text AS name FROM pg_indexes WHERE schemaname = current_schema() AND tablename = ${sqlText(target.table)}`,\n\t\t\t)\n\t\t).map((row) => String(row.name)),\n\t)\n\tfor (const field of target.removeIndexes) {\n\t\t// The server store creates `idx_<table>_<field>` unquoted, which Postgres folds to\n\t\t// lower case.\n\t\tconst [serverName, clientName] = koraIndexNames(target.table, field)\n\t\tif (indexNames.has(serverName.toLowerCase())) {\n\t\t\tstatements.push(`DROP INDEX IF EXISTS ${serverName}`)\n\t\t}\n\t\tif (indexNames.has(clientName)) {\n\t\t\tstatements.push(`DROP INDEX IF EXISTS ${quoteIdentifier(clientName)}`)\n\t\t}\n\t}\n\tfor (const field of plan.drop) {\n\t\t// Postgres drops the column's indexes and constraints with it.\n\t\tstatements.push(`ALTER TABLE ${table} DROP COLUMN IF EXISTS ${quoteIdentifier(field)}`)\n\t}\n\tfor (const [field, change] of plan.change) {\n\t\tconst column = quoteIdentifier(field)\n\t\tconst type = postgresType(change.to)\n\t\tstatements.push(`ALTER TABLE ${table} ALTER COLUMN ${column} DROP DEFAULT`)\n\t\tstatements.push(\n\t\t\t`ALTER TABLE ${table} ALTER COLUMN ${column} TYPE ${type} USING CAST((${postgresProjection(column, change.from, change.to, now)}) AS ${type})`,\n\t\t)\n\t\tif (change.to.default !== undefined) {\n\t\t\tstatements.push(\n\t\t\t\t`ALTER TABLE ${table} ALTER COLUMN ${column} SET DEFAULT ${sqlDefaultLiteral(change.to.default)}`,\n\t\t\t)\n\t\t}\n\t}\n\tfor (const [field, spec] of plan.add) {\n\t\tstatements.push(\n\t\t\t`ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${quoteIdentifier(field)} ${postgresType(spec)}${defaultClause(spec)}`,\n\t\t)\n\t\tif (spec.auto && spec.kind === 'timestamp' && spec.default === undefined) {\n\t\t\tstatements.push(`UPDATE ${table} SET ${quoteIdentifier(field)} = ${now}`)\n\t\t}\n\t}\n\tfor (const field of target.addIndexes) {\n\t\tconst name = koraIndexNames(target.table, field)[0]\n\t\tif (indexNames.has(name.toLowerCase())) continue\n\t\tstatements.push(`CREATE INDEX IF NOT EXISTS ${name} ON ${table} (${quoteIdentifier(field)})`)\n\t}\n\treturn statements\n}\n\ninterface ColumnPlan {\n\tadd: Array<[string, EvolveFieldSpec]>\n\tdrop: string[]\n\tchange: Array<[string, { from: EvolveFieldSpec; to: EvolveFieldSpec }]>\n}\n\n/**\n * What to do with each named column, given the columns the table has now (name -> its\n * declared type, upper case). A column that already has the target shape is left alone,\n * so expanding the directive again yields nothing.\n */\nfunction planColumns(\n\ttarget: EvolveTableTarget,\n\texisting: ReadonlyMap<string, string>,\n\ttypeOf: (spec: EvolveFieldSpec) => string,\n): ColumnPlan {\n\tconst plan: ColumnPlan = { add: [], drop: [], change: [] }\n\tfor (const [field, spec] of Object.entries(target.add)) {\n\t\t// A server that already started on the new schema added the column itself.\n\t\tif (!existing.has(field)) plan.add.push([field, spec])\n\t}\n\tfor (const [field, change] of Object.entries(target.change)) {\n\t\tconst current = existing.get(field)\n\t\tif (current === undefined) {\n\t\t\tplan.add.push([field, change.to])\n\t\t\tcontinue\n\t\t}\n\t\tconst from = typeOf(change.from)\n\t\tconst to = typeOf(change.to)\n\t\t// Already converted (the stored type is the target's and differs from the source's).\n\t\tif (from !== to && current === to) continue\n\t\tplan.change.push([field, change])\n\t}\n\tfor (const field of target.drop) {\n\t\tif (existing.has(field) && !(field in target.add) && !(field in target.change)) {\n\t\t\tif (isKoraInternalColumn(field)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Migration directive refuses to drop Kora's own column \"${field}\" of \"${target.table}\".`,\n\t\t\t\t)\n\t\t\t}\n\t\t\tplan.drop.push(field)\n\t\t}\n\t}\n\treturn plan\n}\n\n/**\n * SQLite's documented \"other kinds of table schema changes\" procedure, driven by the\n * live catalog: every column, constraint, index and trigger the directive does not name\n * is copied as it is.\n */\nasync function sqliteRebuildStatements(\n\tcatalog: SqliteTableCatalog,\n\tplan: ColumnPlan,\n\tquery: SqliteQueryFn,\n\tremovedIndexNames: ReadonlySet<string>,\n\tnow: number,\n): Promise<string[]> {\n\tconst table = catalog.table\n\tconst temp = `_kora_evolve_${table}`\n\tconst dropped = new Set(plan.drop)\n\tconst changed = new Map(plan.change)\n\tconst ordered = [...catalog.columns]\n\t\t.sort((a, b) => a.cid - b.cid)\n\t\t.filter((column) => !dropped.has(column.name))\n\tconst pkColumns = ordered.filter((c) => c.pk > 0).sort((a, b) => a.pk - b.pk)\n\n\tconst fkGroups = new Map<number, SqliteTableCatalog['foreignKeys'][number][]>()\n\tfor (const fk of catalog.foreignKeys) {\n\t\tconst group = fkGroups.get(fk.id) ?? []\n\t\tgroup.push(fk)\n\t\tfkGroups.set(fk.id, group)\n\t}\n\tconst columnReferences = new Map<string, string>()\n\tconst tableConstraints: string[] = []\n\tfor (const group of fkGroups.values()) {\n\t\tgroup.sort((a, b) => a.seq - b.seq)\n\t\tconst first = group[0]\n\t\tif (!first || group.some((fk) => dropped.has(fk.from))) continue\n\t\tconst actions = foreignKeyActions(first)\n\t\tconst targetRef = group.every((fk) => fk.to !== null && fk.to !== '')\n\t\t\t? `${quoteIdentifier(first.table)}(${group.map((fk) => quoteIdentifier(fk.to ?? '')).join(', ')})`\n\t\t\t: quoteIdentifier(first.table)\n\t\tif (group.length === 1) {\n\t\t\tcolumnReferences.set(first.from, `REFERENCES ${targetRef}${actions}`)\n\t\t} else {\n\t\t\ttableConstraints.push(\n\t\t\t\t`FOREIGN KEY (${group.map((fk) => quoteIdentifier(fk.from)).join(', ')}) REFERENCES ${targetRef}${actions}`,\n\t\t\t)\n\t\t}\n\t}\n\tif (pkColumns.length > 1) {\n\t\ttableConstraints.unshift(\n\t\t\t`PRIMARY KEY (${pkColumns.map((c) => quoteIdentifier(c.name)).join(', ')})`,\n\t\t)\n\t}\n\tfor (const unique of catalog.uniqueConstraints) {\n\t\tif (unique.some((column) => dropped.has(column))) continue\n\t\ttableConstraints.push(`UNIQUE (${unique.map(quoteIdentifier).join(', ')})`)\n\t}\n\t// CHECK constraints live only in the CREATE TABLE statement (the pragmas do not report\n\t// them): carry each one over, except a check that reads a dropped column, which goes\n\t// with it like an index on that column (RT-111).\n\tfor (const check of parseSqliteCheckConstraints(catalog.sql)) {\n\t\tif (sqliteCheckReferencesColumn(check, dropped)) continue\n\t\ttableConstraints.push(sqliteCheckConstraintDefinition(check))\n\t}\n\n\tconst definitions: string[] = []\n\tconst targetColumns: string[] = []\n\tconst selections: string[] = []\n\tfor (const column of ordered) {\n\t\tconst change = changed.get(column.name)\n\t\tconst parts = [quoteIdentifier(column.name)]\n\t\tif (change) {\n\t\t\tparts.push(sqliteType(change.to))\n\t\t} else if (column.type) {\n\t\t\tparts.push(column.type)\n\t\t}\n\t\tif (pkColumns.length === 1 && column.pk === 1) parts.push('PRIMARY KEY')\n\t\tif (column.notnull === 1) parts.push('NOT NULL')\n\t\tif (change) {\n\t\t\tif (change.to.default !== undefined) {\n\t\t\t\tparts.push(`DEFAULT ${sqlDefaultLiteral(change.to.default)}`)\n\t\t\t}\n\t\t} else if (column.dflt_value !== null) {\n\t\t\tparts.push(`DEFAULT (${column.dflt_value})`)\n\t\t}\n\t\tconst reference = columnReferences.get(column.name)\n\t\tif (reference) parts.push(reference)\n\t\tdefinitions.push(parts.join(' '))\n\t\ttargetColumns.push(quoteIdentifier(column.name))\n\t\tselections.push(\n\t\t\tchange\n\t\t\t\t? sqliteProjection(quoteIdentifier(column.name), change.from, change.to, now)\n\t\t\t\t: quoteIdentifier(column.name),\n\t\t)\n\t}\n\tfor (const [field, spec] of plan.add) {\n\t\tdefinitions.push(`${quoteIdentifier(field)} ${sqliteType(spec)}${defaultClause(spec)}`)\n\t\ttargetColumns.push(quoteIdentifier(field))\n\t\tselections.push(fallbackLiteral(spec, now))\n\t}\n\n\t// Indexes on a dropped column cannot be re-created; the directive's removed indexes\n\t// are gone already. Every other index and trigger comes back exactly as it was.\n\tconst indexColumns = await indexColumnsByName(query, table)\n\tconst dependents: string[] = []\n\tfor (const row of await query(\n\t\t`SELECT type, name, sql FROM sqlite_master WHERE type IN ('index', 'trigger') AND tbl_name = ${sqlText(table)} AND sql IS NOT NULL ORDER BY type, name`,\n\t)) {\n\t\tconst name = String(row.name)\n\t\tif (row.type === 'index') {\n\t\t\tif (removedIndexNames.has(name)) continue\n\t\t\tif ((indexColumns.get(name) ?? []).some((column) => dropped.has(column))) continue\n\t\t}\n\t\tdependents.push(String(row.sql))\n\t}\n\n\treturn [\n\t\t`DROP TABLE IF EXISTS ${quoteIdentifier(temp)}`,\n\t\t`CREATE TABLE ${quoteIdentifier(temp)} (\\n ${[...definitions, ...tableConstraints].join(',\\n ')}\\n)`,\n\t\t`INSERT INTO ${quoteIdentifier(temp)} (${targetColumns.join(', ')}) SELECT ${selections.join(', ')} FROM ${quoteIdentifier(table)}`,\n\t\t`DROP TABLE ${quoteIdentifier(table)}`,\n\t\t`ALTER TABLE ${quoteIdentifier(temp)} RENAME TO ${quoteIdentifier(table)}`,\n\t\t...dependents,\n\t]\n}\n\n/** Index name -> its columns (null entries for expression columns are skipped). */\nasync function indexColumnsByName(\n\tquery: SqliteQueryFn,\n\ttable: string,\n): Promise<Map<string, string[]>> {\n\tconst out = new Map<string, string[]>()\n\tfor (const index of await query(`SELECT name FROM pragma_index_list(${sqlText(table)})`)) {\n\t\tconst name = String(index.name)\n\t\tconst info = await query(`SELECT name FROM pragma_index_info(${sqlText(name)}) ORDER BY seqno`)\n\t\tout.set(\n\t\t\tname,\n\t\t\tinfo.filter((row) => typeof row.name === 'string').map((row) => String(row.name)),\n\t\t)\n\t}\n\treturn out\n}\n\n/** Columns that already have a single-column index (any name, any store). */\nasync function singleColumnIndexes(\n\tquery: SqliteQueryFn,\n\ttable: string,\n\tignore: ReadonlySet<string>,\n): Promise<Set<string>> {\n\tconst out = new Set<string>()\n\tfor (const [name, columns] of await indexColumnsByName(query, table)) {\n\t\tif (ignore.has(name)) continue\n\t\tconst only = columns[0]\n\t\tif (columns.length === 1 && only !== undefined) out.add(only)\n\t}\n\treturn out\n}\n\n/**\n * Names Kora gives the index on `field`: the server stores' (and earlier CLI's)\n * `idx_<table>_<field>`, which a new index gets, and the client store's\n * collision-free name (STORE-15).\n */\nfunction koraIndexNames(table: string, field: string): [string, string] {\n\tquoteIdentifier(table)\n\tquoteIdentifier(field)\n\treturn [`idx_${table}_${field}`, collectionIndexName(table, field)]\n}\n\nfunction defaultClause(spec: EvolveFieldSpec): string {\n\treturn spec.default !== undefined ? ` DEFAULT ${sqlDefaultLiteral(spec.default)}` : ''\n}\n\n/** The SQLite column type of a field (client and server stores agree). */\nexport function sqliteType(spec: EvolveFieldSpec): string {\n\tswitch (spec.kind) {\n\t\tcase 'number':\n\t\t\treturn 'REAL'\n\t\tcase 'boolean':\n\t\tcase 'timestamp':\n\t\t\treturn 'INTEGER'\n\t\tcase 'richtext':\n\t\t\treturn 'BLOB'\n\t\tdefault:\n\t\t\treturn 'TEXT'\n\t}\n}\n\n/** The Postgres column type of a field (the Postgres server store's mapping). */\nexport function postgresType(spec: EvolveFieldSpec): string {\n\tswitch (spec.kind) {\n\t\tcase 'number':\n\t\t\treturn 'DOUBLE PRECISION'\n\t\tcase 'boolean':\n\t\t\treturn 'INTEGER'\n\t\tcase 'timestamp':\n\t\t\treturn 'BIGINT'\n\t\tcase 'array':\n\t\tcase 'object':\n\t\tcase 'json':\n\t\t\treturn 'JSONB'\n\t\tcase 'richtext':\n\t\t\treturn 'BYTEA'\n\t\tdefault:\n\t\t\treturn 'TEXT'\n\t}\n}\n\nfunction fallbackLiteral(target: EvolveFieldSpec, now: number): string {\n\tif (target.auto && target.kind === 'timestamp') return String(now)\n\tif (target.default !== undefined) return sqlDefaultLiteral(target.default)\n\treturn 'NULL'\n}\n\nconst NUMERIC_SOURCES: ReadonlySet<string> = new Set(['number', 'timestamp', 'boolean'])\nconst TEXT_SOURCES: ReadonlySet<string> = new Set(['string', 'enum'])\nconst TRUE_WORDS = \"('1','true','t','yes','y','on')\"\nconst FALSE_WORDS = \"('0','false','f','no','n','off')\"\n\n/** The SQLite expression that converts a stored value of `source` kind to `target`. */\nexport function sqliteProjection(\n\tcolumn: string,\n\tsource: EvolveFieldSpec,\n\ttarget: EvolveFieldSpec,\n\tnow: number,\n): string {\n\tif (source.kind === target.kind && source.itemKind === target.itemKind) return column\n\tconst fallback = fallbackLiteral(target, now)\n\tif (target.kind === 'string') return `CAST(${column} AS TEXT)`\n\tif (target.kind === 'number' || target.kind === 'timestamp') {\n\t\tif (NUMERIC_SOURCES.has(source.kind) || TEXT_SOURCES.has(source.kind)) {\n\t\t\tconst castType = target.kind === 'number' ? 'REAL' : 'INTEGER'\n\t\t\treturn `CASE WHEN ${column} IS NULL THEN NULL ELSE CAST(${column} AS ${castType}) END`\n\t\t}\n\t}\n\tif (target.kind === 'boolean') {\n\t\tif (NUMERIC_SOURCES.has(source.kind)) {\n\t\t\treturn `CASE WHEN ${column} IS NULL THEN NULL WHEN CAST(${column} AS REAL) = 0 THEN 0 ELSE 1 END`\n\t\t}\n\t\tif (TEXT_SOURCES.has(source.kind)) {\n\t\t\tconst word = `LOWER(TRIM(CAST(${column} AS TEXT)))`\n\t\t\treturn `CASE WHEN ${column} IS NULL THEN NULL WHEN ${word} IN ${TRUE_WORDS} THEN 1 WHEN ${word} IN ${FALSE_WORDS} THEN 0 ELSE ${fallback} END`\n\t\t}\n\t}\n\tif (target.kind === 'enum' && target.enumValues && target.enumValues.length > 0) {\n\t\tif (TEXT_SOURCES.has(source.kind)) {\n\t\t\tconst allowed = target.enumValues.map((value) => sqlDefaultLiteral(value)).join(', ')\n\t\t\treturn `CASE WHEN ${column} IN (${allowed}) THEN ${column} ELSE ${fallback} END`\n\t\t}\n\t}\n\treturn fallback\n}\n\n/** The Postgres expression (for `USING`) that converts `source` kind to `target`. */\nexport function postgresProjection(\n\tcolumn: string,\n\tsource: EvolveFieldSpec,\n\ttarget: EvolveFieldSpec,\n\tnow: number,\n): string {\n\tif (source.kind === target.kind && source.itemKind === target.itemKind) return column\n\tconst fallback = fallbackLiteral(target, now)\n\tconst text = `(${column})::text`\n\tif (target.kind === 'string') return text\n\tif (target.kind === 'number' || target.kind === 'timestamp') {\n\t\tconst toTarget = (value: string): string =>\n\t\t\ttarget.kind === 'number' ? value : `round(${value})::bigint`\n\t\tif (NUMERIC_SOURCES.has(source.kind)) {\n\t\t\treturn `CASE WHEN ${column} IS NULL THEN NULL ELSE ${toTarget(`(${column})::double precision`)} END`\n\t\t}\n\t\tif (TEXT_SOURCES.has(source.kind)) {\n\t\t\tconst trimmed = `btrim(${text})`\n\t\t\treturn `CASE WHEN ${column} IS NULL THEN NULL WHEN ${trimmed} ~ '^[-+]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][-+]?[0-9]+)?$' THEN ${toTarget(`(${trimmed})::double precision`)} ELSE ${fallback} END`\n\t\t}\n\t}\n\tif (target.kind === 'boolean') {\n\t\tif (NUMERIC_SOURCES.has(source.kind)) {\n\t\t\treturn `CASE WHEN ${column} IS NULL THEN NULL WHEN (${column})::double precision = 0 THEN 0 ELSE 1 END`\n\t\t}\n\t\tif (TEXT_SOURCES.has(source.kind)) {\n\t\t\tconst word = `lower(btrim(${text}))`\n\t\t\treturn `CASE WHEN ${column} IS NULL THEN NULL WHEN ${word} IN ${TRUE_WORDS} THEN 1 WHEN ${word} IN ${FALSE_WORDS} THEN 0 ELSE ${fallback} END`\n\t\t}\n\t}\n\tif (target.kind === 'enum' && target.enumValues && target.enumValues.length > 0) {\n\t\tif (TEXT_SOURCES.has(source.kind)) {\n\t\t\tconst allowed = target.enumValues.map((value) => sqlDefaultLiteral(value)).join(', ')\n\t\t\treturn `CASE WHEN ${text} IN (${allowed}) THEN ${text} ELSE ${fallback} END`\n\t\t}\n\t}\n\treturn fallback\n}\n\nfunction foreignKeyActions(fk: SqliteTableCatalog['foreignKeys'][number]): string {\n\tlet out = ''\n\tconst onDelete = fk.on_delete?.toUpperCase()\n\tconst onUpdate = fk.on_update?.toUpperCase()\n\tif (onDelete && onDelete !== 'NO ACTION') out += ` ON DELETE ${onDelete}`\n\tif (onUpdate && onUpdate !== 'NO ACTION') out += ` ON UPDATE ${onUpdate}`\n\treturn out\n}\n\nfunction sqlText(value: string): string {\n\treturn `'${value.replaceAll(\"'\", \"''\")}'`\n}\n\nfunction quoteIdentifier(identifier: string): string {\n\tif (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(identifier)) {\n\t\tthrow new Error(`Invalid SQL identifier: ${identifier}`)\n\t}\n\treturn `\"${identifier}\"`\n}\n","import {\n\ttype SqliteQueryFn,\n\tplanPostgresConstraintRelaxation,\n\tplanSqliteConstraintRelaxation,\n} from '@korajs/core/internal'\n\n/**\n * A generated migration statement that is not SQL but a directive: relax the value-domain\n * constraints (enum `CHECK`, `NOT NULL` on schema fields) of one collection table (RT-101).\n * Table constraints cannot be written portably (SQLite needs a table rebuild that depends\n * on the live table, Postgres an `ALTER TABLE ... DROP CONSTRAINT` by the constraint's\n * name), so `kora migrate --apply` expands the directive against each backend's catalog,\n * inside the migration's transaction. Expanding it on a relaxed table yields nothing.\n */\nexport const RELAX_VALUE_DOMAIN_DIRECTIVE = '--kora:relax-value-domain'\n\n/** The payload of a relax-value-domain directive. */\nexport interface RelaxValueDomainTarget {\n\t/** The collection table */\n\ttable: string\n\t/** The collection's schema fields (before and after the change) */\n\tfields: string[]\n\t/**\n\t * The collection's enum fields (before and after the change, RT-108): their enum\n\t * checks are dropped in every form Postgres stores them in. Absent in directives\n\t * generated by release candidates: every field in `fields` then counts as one.\n\t */\n\tenums?: string[]\n}\n\n/** Render a directive statement for `target`. */\nexport function formatRelaxValueDomainDirective(target: RelaxValueDomainTarget): string {\n\treturn `${RELAX_VALUE_DOMAIN_DIRECTIVE} ${JSON.stringify(target)}`\n}\n\n/**\n * The directive's target when `statement` is a relax-value-domain directive, otherwise null.\n *\n * @throws Error when the statement is a directive with a malformed payload\n */\nexport function parseRelaxValueDomainDirective(statement: string): RelaxValueDomainTarget | null {\n\tconst trimmed = statement.trimStart()\n\tif (!trimmed.startsWith(RELAX_VALUE_DOMAIN_DIRECTIVE)) return null\n\tconst payload = trimmed.slice(RELAX_VALUE_DOMAIN_DIRECTIVE.length).trim()\n\tlet parsed: unknown\n\ttry {\n\t\tparsed = JSON.parse(payload)\n\t} catch {\n\t\tparsed = null\n\t}\n\tif (\n\t\ttypeof parsed !== 'object' ||\n\t\tparsed === null ||\n\t\ttypeof (parsed as { table?: unknown }).table !== 'string' ||\n\t\t!Array.isArray((parsed as { fields?: unknown }).fields) ||\n\t\t!(parsed as { fields: unknown[] }).fields.every((field) => typeof field === 'string') ||\n\t\t((parsed as { enums?: unknown }).enums !== undefined &&\n\t\t\t(!Array.isArray((parsed as { enums?: unknown }).enums) ||\n\t\t\t\t!(parsed as { enums: unknown[] }).enums.every((field) => typeof field === 'string')))\n\t) {\n\t\tthrow new Error(\n\t\t\t`Malformed migration directive \"${statement}\": expected ${RELAX_VALUE_DOMAIN_DIRECTIVE} {\"table\": \"...\", \"fields\": [\"...\"]}. Regenerate the migration with \\`kora migrate\\`.`,\n\t\t)\n\t}\n\tconst target = parsed as RelaxValueDomainTarget\n\treturn {\n\t\ttable: target.table,\n\t\tfields: [...target.fields],\n\t\t...(target.enums !== undefined ? { enums: [...target.enums] } : {}),\n\t}\n}\n\n/** The SQLite statements a directive expands to (a table rebuild, or nothing). */\nexport async function expandRelaxValueDomainForSqlite(\n\ttarget: RelaxValueDomainTarget,\n\tquery: SqliteQueryFn,\n): Promise<string[]> {\n\t// Only enum checks on the enum fields (before and after the change; an older directive\n\t// without them: any schema field) are Kora's; other checks are kept (RT-111).\n\treturn planSqliteConstraintRelaxation(query, [target.table], {\n\t\t[target.table]: target.enums ?? target.fields,\n\t})\n}\n\n/** The Postgres statements a directive expands to (`ALTER TABLE ... DROP ...`, or nothing). */\nexport async function expandRelaxValueDomainForPostgres(\n\ttarget: RelaxValueDomainTarget,\n\tquery: SqliteQueryFn,\n): Promise<string[]> {\n\treturn planPostgresConstraintRelaxation(\n\t\tquery,\n\t\t{ [target.table]: target.fields },\n\t\ttarget.enums !== undefined ? { [target.table]: target.enums } : {},\n\t)\n}\n","import {\n\texpandEvolveTableForPostgres,\n\texpandEvolveTableForSqlite,\n\tparseEvolveTableDirective,\n} from './table-evolution-directive'\nimport {\n\texpandRelaxValueDomainForPostgres,\n\texpandRelaxValueDomainForSqlite,\n\tparseRelaxValueDomainDirective,\n} from './value-domain-directive'\n\nexport interface RunMigrationOptions {\n\tupStatements: string[]\n\tmigrationId?: string\n\tfromVersion?: number\n\ttoVersion?: number\n\tsqlitePath?: string\n\tpostgresConnectionString?: string\n\tprojectRoot?: string\n\tsqliteDriver?: {\n\t\topen(path: string): {\n\t\t\texec(sql: string): void\n\t\t\tisMigrationApplied?(id: string): boolean\n\t\t\t/** Runs a SELECT/PRAGMA and returns its rows (needed by value-domain directives). */\n\t\t\tquery?(sql: string): Array<Record<string, unknown>>\n\t\t\tclose?(): void\n\t\t}\n\t}\n\tpostgresClientFactory?: (connectionString: string) => {\n\t\tunsafe(query: string): Promise<unknown>\n\t\tend?(): Promise<void>\n\t}\n}\n\nexport interface BackendApplyReport {\n\tbackend: 'sqlite' | 'postgres'\n\tstatementsApplied: number\n\thistoryRecorded: boolean\n\tskipped: boolean\n}\n\nexport interface RunMigrationReport {\n\tbackends: BackendApplyReport[]\n}\n\nexport class MigrationApplyError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly backend: 'sqlite' | 'postgres',\n\t\tpublic readonly report: RunMigrationReport,\n\t) {\n\t\tsuper(message)\n\t\tthis.name = 'MigrationApplyError'\n\t}\n}\n\n/**\n * Applies migration statements to configured backends.\n */\nexport async function runMigration(options: RunMigrationOptions): Promise<RunMigrationReport> {\n\tconst report: RunMigrationReport = { backends: [] }\n\tconst migrationId = options.migrationId ?? `migration-${Date.now()}`\n\tconst fromVersion = options.fromVersion ?? 0\n\tconst toVersion = options.toVersion ?? 0\n\n\tif (options.sqlitePath) {\n\t\ttry {\n\t\t\tconst sqliteReport = await runSqliteMigration(\n\t\t\t\toptions.sqlitePath,\n\t\t\t\toptions.upStatements,\n\t\t\t\tmigrationId,\n\t\t\t\tfromVersion,\n\t\t\t\ttoVersion,\n\t\t\t\toptions.projectRoot,\n\t\t\t\toptions.sqliteDriver,\n\t\t\t)\n\t\t\treport.backends.push(sqliteReport)\n\t\t} catch (error) {\n\t\t\tthrow new MigrationApplyError((error as Error).message, 'sqlite', report)\n\t\t}\n\t}\n\n\tif (options.postgresConnectionString) {\n\t\ttry {\n\t\t\tconst postgresReport = await runPostgresMigration(\n\t\t\t\toptions.postgresConnectionString,\n\t\t\t\toptions.upStatements,\n\t\t\t\tmigrationId,\n\t\t\t\tfromVersion,\n\t\t\t\ttoVersion,\n\t\t\t\toptions.postgresClientFactory,\n\t\t\t)\n\t\t\treport.backends.push(postgresReport)\n\t\t} catch (error) {\n\t\t\tthrow new MigrationApplyError((error as Error).message, 'postgres', report)\n\t\t}\n\t}\n\n\treturn report\n}\n\nasync function runSqliteMigration(\n\tpath: string,\n\tstatements: string[],\n\tmigrationId: string,\n\tfromVersion: number,\n\ttoVersion: number,\n\tprojectRoot?: string,\n\tdriverOverride?: RunMigrationOptions['sqliteDriver'],\n): Promise<BackendApplyReport> {\n\tconst driver = driverOverride ?? (await loadSqliteDriver(projectRoot))\n\tconst db = driver.open(path)\n\tlet statementsApplied = 0\n\n\t// SQLite's table-rebuild procedure (generated rebuilds, relax-value-domain directives)\n\t// needs foreign key enforcement off, and the pragma is a no-op inside a transaction.\n\tconst foreignKeysOn = Number(db.query?.('PRAGMA foreign_keys')[0]?.foreign_keys ?? 0) === 1\n\tif (foreignKeysOn) db.exec('PRAGMA foreign_keys = OFF')\n\n\ttry {\n\t\tdb.exec('BEGIN')\n\t\tdb.exec(\n\t\t\t'CREATE TABLE IF NOT EXISTS _kora_migrations (id TEXT PRIMARY KEY NOT NULL, from_version INTEGER NOT NULL, to_version INTEGER NOT NULL, applied_at INTEGER NOT NULL)',\n\t\t)\n\t\tconst alreadyApplied =\n\t\t\ttypeof db.isMigrationApplied === 'function' ? db.isMigrationApplied(migrationId) : false\n\t\tif (alreadyApplied) {\n\t\t\tdb.exec('COMMIT')\n\t\t\treturn {\n\t\t\t\tbackend: 'sqlite',\n\t\t\t\tstatementsApplied: 0,\n\t\t\t\thistoryRecorded: true,\n\t\t\t\tskipped: true,\n\t\t\t}\n\t\t}\n\t\tconst now = Date.now()\n\t\tconst catalogQuery = (\n\t\t\ttable: string,\n\t\t): ((text: string) => Promise<Array<Record<string, unknown>>>) => {\n\t\t\tconst query = db.query?.bind(db)\n\t\t\tif (!query) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Migration ${migrationId}: the SQLite driver cannot read the catalog needed to migrate \"${table}\".`,\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn async (text) => query(text)\n\t\t}\n\t\tfor (const statement of statements) {\n\t\t\tconst relax = parseRelaxValueDomainDirective(statement)\n\t\t\tconst evolve = relax ? null : parseEvolveTableDirective(statement)\n\t\t\tif (relax) {\n\t\t\t\tconst expanded = await expandRelaxValueDomainForSqlite(relax, catalogQuery(relax.table))\n\t\t\t\tfor (const rebuild of expanded) db.exec(rebuild)\n\t\t\t} else if (evolve) {\n\t\t\t\tconst expanded = await expandEvolveTableForSqlite(evolve, catalogQuery(evolve.table), now)\n\t\t\t\tfor (const change of expanded) db.exec(change)\n\t\t\t} else {\n\t\t\t\tdb.exec(statement)\n\t\t\t}\n\t\t\tstatementsApplied++\n\t\t}\n\t\t// Table rebuilds run with foreign key enforcement off: refuse to commit one that left\n\t\t// a dangling reference.\n\t\tconst violations = db.query?.('PRAGMA foreign_key_check') ?? []\n\t\tif (violations.length > 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Migration ${migrationId} left ${violations.length} foreign key violation(s) (first: ${JSON.stringify(violations[0])}); nothing was applied.`,\n\t\t\t)\n\t\t}\n\t\tdb.exec(\n\t\t\t`INSERT OR REPLACE INTO _kora_migrations (id, from_version, to_version, applied_at) VALUES (${sqlLiteral(migrationId)}, ${fromVersion}, ${toVersion}, ${Date.now()})`,\n\t\t)\n\t\tdb.exec('COMMIT')\n\n\t\treturn {\n\t\t\tbackend: 'sqlite',\n\t\t\tstatementsApplied,\n\t\t\thistoryRecorded: true,\n\t\t\tskipped: false,\n\t\t}\n\t} catch (error) {\n\t\ttry {\n\t\t\tdb.exec('ROLLBACK')\n\t\t} catch {\n\t\t\t// best effort\n\t\t}\n\t\tthrow error\n\t} finally {\n\t\tif (foreignKeysOn) {\n\t\t\ttry {\n\t\t\t\tdb.exec('PRAGMA foreign_keys = ON')\n\t\t\t} catch {\n\t\t\t\t// the connection is closed next; enforcement is per connection\n\t\t\t}\n\t\t}\n\t\tif (typeof db.close === 'function') {\n\t\t\tdb.close()\n\t\t}\n\t}\n}\n\nasync function loadSqliteDriver(projectRoot?: string): Promise<{\n\topen(path: string): {\n\t\texec(sql: string): void\n\t\tisMigrationApplied(id: string): boolean\n\t\tquery(sql: string): Array<Record<string, unknown>>\n\t\tclose(): void\n\t}\n}> {\n\ttry {\n\t\tconst { createRequire } = await import('node:module')\n\t\tconst requireFrom = createRequire(projectRoot ? `${projectRoot}/package.json` : import.meta.url)\n\t\tconst Database = requireFrom('better-sqlite3') as new (\n\t\t\tpath: string,\n\t\t) => {\n\t\t\texec(sql: string): void\n\t\t\tprepare(sql: string): {\n\t\t\t\tget(...params: unknown[]): { count?: number } | undefined\n\t\t\t\tall(...params: unknown[]): Array<Record<string, unknown>>\n\t\t\t}\n\t\t\tclose(): void\n\t\t}\n\n\t\treturn {\n\t\t\topen(path: string) {\n\t\t\t\tconst db = new Database(path)\n\t\t\t\treturn {\n\t\t\t\t\texec(sql: string) {\n\t\t\t\t\t\tdb.exec(sql)\n\t\t\t\t\t},\n\t\t\t\t\tisMigrationApplied(id: string) {\n\t\t\t\t\t\tconst row = db\n\t\t\t\t\t\t\t.prepare('SELECT COUNT(*) AS count FROM _kora_migrations WHERE id = ?')\n\t\t\t\t\t\t\t.get(id)\n\t\t\t\t\t\treturn (row?.count ?? 0) > 0\n\t\t\t\t\t},\n\t\t\t\t\tquery(sql: string) {\n\t\t\t\t\t\treturn db.prepare(sql).all()\n\t\t\t\t\t},\n\t\t\t\t\tclose() {\n\t\t\t\t\t\tdb.close()\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t},\n\t\t}\n\t} catch {\n\t\tthrow new Error(\n\t\t\t'SQLite migration apply requires the \"better-sqlite3\" package in the target project dependencies.',\n\t\t)\n\t}\n}\n\nasync function runPostgresMigration(\n\tconnectionString: string,\n\tstatements: string[],\n\tmigrationId: string,\n\tfromVersion: number,\n\ttoVersion: number,\n\tclientFactoryOverride?: RunMigrationOptions['postgresClientFactory'],\n): Promise<BackendApplyReport> {\n\tconst sql =\n\t\ttypeof clientFactoryOverride === 'function'\n\t\t\t? clientFactoryOverride(connectionString)\n\t\t\t: // One connection: BEGIN, the statements and COMMIT must share it (postgres.js\n\t\t\t\t// refuses a raw BEGIN on a pool, UNSAFE_TRANSACTION).\n\t\t\t\t(await loadPostgresModule()).default(connectionString, { max: 1 })\n\tlet statementsApplied = 0\n\n\ttry {\n\t\tawait sql.unsafe('BEGIN')\n\t\tawait sql.unsafe(\n\t\t\t'CREATE TABLE IF NOT EXISTS _kora_migrations (id TEXT PRIMARY KEY, from_version INTEGER NOT NULL, to_version INTEGER NOT NULL, applied_at BIGINT NOT NULL)',\n\t\t)\n\t\tconst existing = (await sql.unsafe(\n\t\t\t`SELECT COUNT(*)::int AS count FROM _kora_migrations WHERE id = ${sqlLiteral(migrationId)}`,\n\t\t)) as Array<{ count: number }>\n\t\tif ((existing[0]?.count ?? 0) > 0) {\n\t\t\tawait sql.unsafe('COMMIT')\n\t\t\treturn {\n\t\t\t\tbackend: 'postgres',\n\t\t\t\tstatementsApplied: 0,\n\t\t\t\thistoryRecorded: true,\n\t\t\t\tskipped: true,\n\t\t\t}\n\t\t}\n\t\tconst now = Date.now()\n\t\tconst query = async (text: string) => (await sql.unsafe(text)) as Array<Record<string, unknown>>\n\t\tfor (const statement of statements) {\n\t\t\tconst relax = parseRelaxValueDomainDirective(statement)\n\t\t\tconst evolve = relax ? null : parseEvolveTableDirective(statement)\n\t\t\tif (relax) {\n\t\t\t\tconst expanded = await expandRelaxValueDomainForPostgres(relax, query)\n\t\t\t\tfor (const alter of expanded) await sql.unsafe(alter)\n\t\t\t} else if (evolve) {\n\t\t\t\tconst expanded = await expandEvolveTableForPostgres(evolve, query, now)\n\t\t\t\tfor (const alter of expanded) await sql.unsafe(alter)\n\t\t\t} else {\n\t\t\t\tassertNotLegacyRebuild(statement, migrationId)\n\t\t\t\tawait sql.unsafe(statement)\n\t\t\t}\n\t\t\tstatementsApplied++\n\t\t}\n\t\tawait sql.unsafe(\n\t\t\t`INSERT INTO _kora_migrations (id, from_version, to_version, applied_at) VALUES (${sqlLiteral(migrationId)}, ${fromVersion}, ${toVersion}, ${Date.now()}) ON CONFLICT (id) DO UPDATE SET from_version = EXCLUDED.from_version, to_version = EXCLUDED.to_version, applied_at = EXCLUDED.applied_at`,\n\t\t)\n\t\tawait sql.unsafe('COMMIT')\n\n\t\treturn {\n\t\t\tbackend: 'postgres',\n\t\t\tstatementsApplied,\n\t\t\thistoryRecorded: true,\n\t\t\tskipped: false,\n\t\t}\n\t} catch (error) {\n\t\ttry {\n\t\t\tawait sql.unsafe('ROLLBACK')\n\t\t} catch {\n\t\t\t// best effort\n\t\t}\n\t\tthrow error\n\t} finally {\n\t\tif (typeof sql.end === 'function') {\n\t\t\tawait sql.end()\n\t\t}\n\t}\n}\n\n/**\n * Migrations generated before RT-105 rebuilt a changed collection table with fixed SQLite\n * statements (`CREATE TABLE \"_kora_mig_<collection>_new\" ...`). On Postgres they cannot\n * work (INTEGER/REAL/TEXT/BLOB columns, `strftime`): refuse them with the fix instead of\n * failing half-way or rewriting the server store's column types.\n */\nfunction assertNotLegacyRebuild(statement: string, migrationId: string): void {\n\tif (/^\\s*CREATE\\s+TABLE\\s+\"?_kora_mig_[A-Za-z0-9_]+_new\"?/i.test(statement)) {\n\t\tthrow new Error(\n\t\t\t`Migration ${migrationId} was generated by an earlier \\`kora migrate\\` as a SQLite-only table rebuild, which cannot run on Postgres. Regenerate it: restore kora/schema.snapshot.json to the schema version it migrates from, delete the migration's files, and run \\`kora migrate\\` again.`,\n\t\t)\n\t}\n}\n\nfunction sqlLiteral(value: string): string {\n\treturn `'${value.replaceAll(\"'\", \"''\")}'`\n}\n\nasync function loadPostgresModule(): Promise<{\n\tdefault: (\n\t\tconnectionString: string,\n\t\toptions?: { max?: number },\n\t) => {\n\t\tunsafe: (query: string) => Promise<unknown>\n\t\tend?: () => Promise<void>\n\t}\n}> {\n\ttry {\n\t\tconst dynamicImport = new Function('specifier', 'return import(specifier)') as (\n\t\t\tspecifier: string,\n\t\t) => Promise<unknown>\n\t\tconst mod = await dynamicImport('postgres')\n\t\tif (typeof mod === 'object' && mod !== null && 'default' in mod) {\n\t\t\treturn mod as {\n\t\t\t\tdefault: (\n\t\t\t\t\tconnectionString: string,\n\t\t\t\t\toptions?: { max?: number },\n\t\t\t\t) => {\n\t\t\t\t\tunsafe: (query: string) => Promise<unknown>\n\t\t\t\t\tend?: () => Promise<void>\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthrow new Error('Invalid postgres module')\n\t} catch {\n\t\tthrow new Error(\n\t\t\t'PostgreSQL migration apply requires the \"postgres\" package in the target project dependencies.',\n\t\t)\n\t}\n}\n","/**\n * Generates a stub operation-transform module for sync-time op log migration.\n */\nexport function generateOperationTransformModule(fromVersion: number, toVersion: number): string {\n\treturn [\n\t\t\"import type { Operation, OperationTransform } from '@korajs/core'\",\n\t\t'',\n\t\t'/**',\n\t\t` * Operation transforms for schema v${fromVersion} → v${toVersion}.`,\n\t\t' * Implement `transform` to rewrite or drop legacy operations during sync.',\n\t\t' * @see https://korajs.dev/docs/migrations',\n\t\t' */',\n\t\t'export const operationTransforms: OperationTransform[] = [',\n\t\t' {',\n\t\t` fromVersion: ${fromVersion},`,\n\t\t` toVersion: ${toVersion},`,\n\t\t' transform(operation: Operation): Operation | null {',\n\t\t' // Return null to drop unmigratable operations.',\n\t\t' return operation',\n\t\t' },',\n\t\t' },',\n\t\t']',\n\t\t'',\n\t].join('\\n')\n}\n","import { defineCommand } from 'citty'\nimport { createLogger } from '../../utils/logger'\n\nconst DEFAULT_SYNC_PORT = 3001\nconst STATUS_ENDPOINT = '/__kora/status'\n\ninterface ServerStatusResponse {\n\trunning: boolean\n\tconnectedClients: number\n\tport: number | null\n\ttotalOperations: number\n\tuptime: number\n\tversion: string\n\tschemaVersion: number\n\tconnectedNodeIds: string[]\n\tpeakConnections: number\n\tconnectionsTotal: number\n\toperationsReceived: number\n\toperationsSent: number\n\terrorCount: number\n}\n\n/**\n * Fetch server status from a Kora sync server.\n */\nasync function fetchServerStatus(url: string, token?: string): Promise<ServerStatusResponse> {\n\tconst statusUrl = `${url.replace(/\\/$/, '')}${STATUS_ENDPOINT}`\n\tconst response = await fetch(statusUrl, {\n\t\theaders: token ? { Authorization: `Bearer ${token}` } : undefined,\n\t})\n\tif (!response.ok) {\n\t\tthrow new Error(\n\t\t\t`Failed to fetch status from ${statusUrl}: ${response.status} ${response.statusText}`,\n\t\t)\n\t}\n\n\treturn (await response.json()) as ServerStatusResponse\n}\n\nfunction formatUptime(ms: number): string {\n\tconst seconds = Math.floor(ms / 1000)\n\tconst minutes = Math.floor(seconds / 60)\n\tconst hours = Math.floor(minutes / 60)\n\tconst days = Math.floor(hours / 24)\n\tconst parts: string[] = []\n\tif (days > 0) parts.push(`${days}d`)\n\tif (hours % 24 > 0) parts.push(`${hours % 24}h`)\n\tif (minutes % 60 > 0) parts.push(`${minutes % 60}m`)\n\tparts.push(`${seconds % 60}s`)\n\treturn parts.join(' ')\n}\n\n/**\n * The `status` command — shows the current status of a Kora sync server.\n */\nexport const statusCommand = defineCommand({\n\tmeta: {\n\t\tname: 'status',\n\t\tdescription: 'Show Kora sync server status',\n\t},\n\targs: {\n\t\turl: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Sync server URL (default: http://localhost:3001)',\n\t\t\tdefault: `http://localhost:${DEFAULT_SYNC_PORT}`,\n\t\t},\n\t\twatch: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Live-updating status (like htop)',\n\t\t\tdefault: false,\n\t\t\talias: 'w',\n\t\t},\n\t\ttoken: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Admin token (defaults to KORA_ADMIN_TOKEN)',\n\t\t},\n\t},\n\tasync run({ args }) {\n\t\tconst logger = createLogger()\n\t\tconst url = typeof args.url === 'string' ? args.url : `http://localhost:${DEFAULT_SYNC_PORT}`\n\t\tconst watch = args.watch === true\n\t\tconst token =\n\t\t\ttypeof args.token === 'string' ? args.token : (process.env.KORA_ADMIN_TOKEN ?? undefined)\n\n\t\ttry {\n\t\t\tif (watch) {\n\t\t\t\t// Live-updating mode\n\t\t\t\tconsole.clear()\n\t\t\t\tlogger.banner()\n\t\t\t\tlogger.info(`Connecting to ${url}...`)\n\n\t\t\t\tconst interval = setInterval(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst status = await fetchServerStatus(url, token)\n\t\t\t\t\t\tprintStatus(status, url, logger)\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Clear the previous status output\n\t\t\t\t\t\t// On next iteration, we'll try again\n\t\t\t\t\t}\n\t\t\t\t}, 2000)\n\n\t\t\t\t// Initial fetch\n\t\t\t\ttry {\n\t\t\t\t\tconst status = await fetchServerStatus(url, token)\n\t\t\t\t\tprintStatus(status, url, logger)\n\t\t\t\t} catch {\n\t\t\t\t\t// Will retry on interval\n\t\t\t\t}\n\n\t\t\t\t// Keep running until Ctrl+C\n\t\t\t\tawait new Promise(() => {\n\t\t\t\t\tprocess.on('SIGINT', () => {\n\t\t\t\t\t\tclearInterval(interval)\n\t\t\t\t\t\tprocess.exit(0)\n\t\t\t\t\t})\n\t\t\t\t\tprocess.on('SIGTERM', () => {\n\t\t\t\t\t\tclearInterval(interval)\n\t\t\t\t\t\tprocess.exit(0)\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tconst status = await fetchServerStatus(url, token)\n\t\t\t\tprintStatus(status, url, logger)\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(`Failed to connect to ${url}`)\n\t\t\tif (error instanceof Error) {\n\t\t\t\tlogger.error(error.message)\n\t\t\t}\n\t\t\tlogger.blank()\n\t\t\tlogger.step('Make sure the Kora sync server is running.')\n\t\t\tlogger.step('Start it with: kora dev')\n\t\t\tprocess.exit(1)\n\t\t}\n\t},\n})\n\nfunction printStatus(\n\tstatus: ServerStatusResponse,\n\turl: string,\n\tlogger: ReturnType<typeof createLogger>,\n): void {\n\tconsole.clear()\n\tlogger.banner()\n\tlogger.info(`Kora Sync Server — ${url}`)\n\tlogger.blank()\n\n\tif (!status.running) {\n\t\tlogger.error('Server is not running')\n\t\treturn\n\t}\n\n\t// Server info\n\tlogger.step(`Status: Running (uptime: ${formatUptime(status.uptime)}) — v${status.version}`)\n\tlogger.step(`Schema: v${status.schemaVersion}`)\n\tlogger.blank()\n\n\t// Connections\n\tlogger.step(`Connections: ${status.connectedClients} connected`)\n\tlogger.step(` Peak: ${status.peakConnections}`)\n\tlogger.step(` Total: ${status.connectionsTotal}`)\n\n\tif (status.connectedNodeIds.length > 0) {\n\t\tlogger.step(' Active nodes:')\n\t\tfor (const nodeId of status.connectedNodeIds) {\n\t\t\tlogger.step(` • ${nodeId}`)\n\t\t}\n\t}\n\tlogger.blank()\n\n\t// Operations\n\tlogger.step('Operations:')\n\tlogger.step(` Received: ${status.operationsReceived.toLocaleString()}`)\n\tlogger.step(` Sent: ${status.operationsSent.toLocaleString()}`)\n\tlogger.step(` Total: ${status.totalOperations.toLocaleString()}`)\n\tlogger.blank()\n\n\t// Errors\n\tif (status.errorCount > 0) {\n\t\tlogger.warn(`Errors: ${status.errorCount}`)\n\t} else {\n\t\tlogger.step('Errors: 0')\n\t}\n}\n","import { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { defineCommand } from 'citty'\nimport { createLogger } from '../../utils/logger'\n\n/**\n * `kora studio` — the visual window into Kora's data plane.\n *\n * FILE mode (`--db path`): read-only inspection of any Kora database —\n * records with per-field last writers, operation history, causal DAG, time\n * travel, merge audit, sync state.\n *\n * LAB mode (`--lab`): an interactive multi-device sync laboratory running\n * REAL stores, sync engines, and a real server in-process. Create devices,\n * edit data on each, disconnect them, inject chaos (drops, duplicates,\n * reordering, latency), and watch conflicts resolve and devices converge —\n * live, with evidence.\n */\nexport const studioCommand = defineCommand({\n\tmeta: {\n\t\tname: 'studio',\n\t\tdescription: 'Kora Studio: visualize records, operations, and sync — or run the sync lab',\n\t},\n\targs: {\n\t\tdb: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Path to a Kora SQLite database file (file mode, read-only)',\n\t\t},\n\t\tlab: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Start the interactive multi-device sync laboratory',\n\t\t},\n\t\tconnect: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Spectator mode: WebSocket URL of a live Kora sync server (read-only replica)',\n\t\t},\n\t\ttoken: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Spectator mode: bearer token for the sync auth handshake',\n\t\t},\n\t\tdevices: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Lab mode: number of initial devices (default 2)',\n\t\t},\n\t\tschema: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Lab mode: path to a schema file (defaults to a built-in demo schema)',\n\t\t},\n\t\tport: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Port for the Studio UI (default 4321, 0 for a random free port)',\n\t\t},\n\t},\n\tasync run({ args }) {\n\t\tconst logger = createLogger()\n\n\t\tconst port = args.port !== undefined ? Number.parseInt(args.port, 10) : 4321\n\t\tif (Number.isNaN(port) || port < 0 || port > 65535) {\n\t\t\tthrow new Error(`Invalid port \"${args.port}\"`)\n\t\t}\n\n\t\tconst { startStudioServer } = await import('./studio-server')\n\n\t\tif (typeof args.connect === 'string') {\n\t\t\t// SPECTATOR: live read-only replica of a production sync server.\n\t\t\tif (typeof args.schema !== 'string') {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Spectator mode needs your schema to materialize records: kora studio --connect wss://… --schema ./kora/schema.ts',\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst { loadSchemaDefinition } = await import('../migrate/schema-loader')\n\t\t\tconst schema = await loadSchemaDefinition(resolve(process.cwd(), args.schema), process.cwd())\n\n\t\t\tconst { SpectatorManager } = await import('./spectator-manager')\n\t\t\tconst spectator = new SpectatorManager({\n\t\t\t\turl: args.connect,\n\t\t\t\tschema,\n\t\t\t\t...(typeof args.token === 'string' ? { token: args.token } : {}),\n\t\t\t})\n\t\t\tawait spectator.start()\n\t\t\tconst server = await startStudioServer({ port, spectator })\n\n\t\t\tlogger.banner()\n\t\t\tlogger.success(`Kora Studio SPECTATOR running at ${server.url}`)\n\t\t\tlogger.step(`Watching ${args.connect} (read-only replica — nothing is ever pushed)`)\n\t\t\tlogger.step('Press Ctrl+C to stop.')\n\n\t\t\tconst shutdown = async (): Promise<void> => {\n\t\t\t\tawait server.close()\n\t\t\t\tawait spectator.close()\n\t\t\t\tprocess.exit(0)\n\t\t\t}\n\t\t\tprocess.on('SIGINT', () => void shutdown())\n\t\t\tprocess.on('SIGTERM', () => void shutdown())\n\t\t\treturn\n\t\t}\n\n\t\tif (args.lab) {\n\t\t\tconst { LabManager, defaultLabSchema } = await import('./lab-manager')\n\n\t\t\tlet schema = defaultLabSchema()\n\t\t\tif (typeof args.schema === 'string') {\n\t\t\t\tconst { loadSchemaDefinition } = await import('../migrate/schema-loader')\n\t\t\t\tschema = await loadSchemaDefinition(resolve(process.cwd(), args.schema), process.cwd())\n\t\t\t}\n\n\t\t\tconst initialDevices =\n\t\t\t\targs.devices !== undefined ? Math.max(1, Number.parseInt(args.devices, 10) || 2) : 2\n\n\t\t\tconst lab = new LabManager(schema)\n\t\t\tawait lab.start(initialDevices)\n\t\t\tconst server = await startStudioServer({ port, lab })\n\n\t\t\tlogger.banner()\n\t\t\tlogger.success(`Kora Studio LAB running at ${server.url}`)\n\t\t\tlogger.step(`${initialDevices} device(s) started against an in-process sync server.`)\n\t\t\tlogger.step('Everything in the lab is throwaway — experiment freely.')\n\t\t\tlogger.step('Press Ctrl+C to stop.')\n\n\t\t\tconst shutdown = async (): Promise<void> => {\n\t\t\t\tawait server.close()\n\t\t\t\tawait lab.close()\n\t\t\t\tprocess.exit(0)\n\t\t\t}\n\t\t\tprocess.on('SIGINT', () => void shutdown())\n\t\t\tprocess.on('SIGTERM', () => void shutdown())\n\t\t\treturn\n\t\t}\n\n\t\tif (typeof args.db !== 'string') {\n\t\t\tthrow new Error(\n\t\t\t\t'Pass --db <path> to inspect a database, --lab for the sync laboratory, or --connect <wss url> for live spectator mode.',\n\t\t\t)\n\t\t}\n\t\tconst dbPath = resolve(process.cwd(), args.db)\n\t\tif (!existsSync(dbPath)) {\n\t\t\tthrow new Error(`Database file not found: ${dbPath}`)\n\t\t}\n\n\t\tconst server = await startStudioServer({ port, dbPath })\n\n\t\tlogger.banner()\n\t\tlogger.success(`Kora Studio running at ${server.url}`)\n\t\tlogger.step(`Database: ${dbPath} (read-only)`)\n\t\tlogger.step('Press Ctrl+C to stop.')\n\n\t\tconst shutdown = async (): Promise<void> => {\n\t\t\tawait server.close()\n\t\t\tprocess.exit(0)\n\t\t}\n\t\tprocess.on('SIGINT', () => void shutdown())\n\t\tprocess.on('SIGTERM', () => void shutdown())\n\t},\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,iBAAAA,iBAAe,eAAe;;;ACAvC,SAAS,UAAU,iBAAiB;AACpC,OAAqB;AACrB,SAAS,qBAAqB;AAG9B,IAAM,oBAAoB;AAKnB,IAAM,gBAAgB,cAAc;AAAA,EAC1C,MAAM;AAAA,IACL,MAAM;AAAA,IACN,aAAa;AAAA,EACd;AAAA,EACA,aAAa;AAAA,IACZ,QAAQ,cAAc;AAAA,MACrB,MAAM;AAAA,QACL,MAAM;AAAA,QACN,aAAa;AAAA,MACd;AAAA,MACA,MAAM;AAAA,QACL,KAAK;AAAA,UACJ,MAAM;AAAA,UACN,aAAa;AAAA,UACb,SAAS,oBAAoB,iBAAiB;AAAA,QAC/C;AAAA,QACA,KAAK;AAAA,UACJ,MAAM;AAAA,UACN,aAAa;AAAA,QACd;AAAA,QACA,OAAO;AAAA,UACN,MAAM;AAAA,UACN,aAAa;AAAA,QACd;AAAA,MACD;AAAA,MACA,MAAM,IAAI,EAAE,KAAK,GAAG;AACnB,cAAM,SAAS,aAAa;AAC5B,cAAM,MACL,OAAO,KAAK,QAAQ,WAAW,KAAK,MAAM,oBAAoB,iBAAiB;AAChF,cAAM,UAAU,OAAO,KAAK,QAAQ,WAAW,KAAK,MAAM,eAAe,KAAK,IAAI,CAAC;AACnF,cAAM,QACL,OAAO,KAAK,UAAU,WACnB,KAAK,QACJ,QAAQ,IAAI,qBAAqB,QAAQ,IAAI;AAElD,eAAO,OAAO;AACd,eAAO,KAAK,yBAAyB,GAAG,KAAK;AAE7C,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,WAAO,KAAK,aAAa,MAAM,cAAc;AAC7C,WAAO,KAAK,uBAAuB;AAEnC,UAAM,WAAW,YAA2B;AAC3C,YAAM,OAAO,MAAM;AACnB,cAAQ,KAAK,CAAC;AAAA,IACf;AACA,YAAQ,GAAG,UAAU,MAAM,KAAK,SAAS,CAAC;AAC1C,YAAQ,GAAG,WAAW,MAAM,KAAK,SAAS,CAAC;AAAA,EAC5C;AACD,CAAC;;;ApB3ID,IAAM,OAAOC,gBAAc;AAAA,EAC1B,MAAM;AAAA,IACL,MAAM;AAAA,IACN,aAAa;AAAA,EACd;AAAA,EACA,aAAa;AAAA,IACZ,aAAa;AAAA,IACb,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,MAAM;AAAA,IACN,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,QAAQ;AAAA,EACT;AACD,CAAC;AAED,QAAQ,IAAI;","names":["defineCommand","defineCommand","join","loaded","join","resolve","defineCommand","access","join","resolve","defineCommand","resolve","spawn","join","join","resolve","spawn","defineCommand","join","resolve","access","defineCommand","access","readFile","join","resolve","resolve","access","join","readFile","defineCommand","writeFile","resolve","defineCommand","defineCommand","resolve","writeFile","defineCommand","DEFAULT_SYNC_PORT","defineCommand","mkdir","readFile","writeFile","dirname","join","resolve","defineCommand","quoteIdentifier","defineCommand","resolve","join","mkdir","readFile","dirname","writeFile","defineCommand","DEFAULT_SYNC_PORT","STATUS_ENDPOINT","defineCommand","watch","existsSync","resolve","defineCommand","defineCommand","loadSchemaDefinition","resolve","server","shutdown","existsSync","defineCommand"]}
|