@korajs/cli 0.1.15 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +49 -0
- package/dist/bin.cjs +2517 -332
- package/dist/bin.cjs.map +1 -1
- package/dist/bin.js +12 -10
- package/dist/bin.js.map +1 -1
- package/dist/chunk-E4JG7THU.js +1550 -0
- package/dist/chunk-E4JG7THU.js.map +1 -0
- package/dist/chunk-KTSRAPSE.js +752 -0
- package/dist/chunk-KTSRAPSE.js.map +1 -0
- package/dist/chunk-ZGYRDYXS.js +609 -0
- package/dist/chunk-ZGYRDYXS.js.map +1 -0
- package/dist/create.cjs +974 -159
- package/dist/create.cjs.map +1 -1
- package/dist/create.js +2 -2
- package/dist/index.cjs +2103 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +617 -1
- package/dist/index.d.ts +617 -1
- package/dist/index.js +91 -5
- package/package.json +8 -2
- package/dist/chunk-N36PFOSA.js +0 -103
- package/dist/chunk-N36PFOSA.js.map +0 -1
- package/dist/chunk-SYOFLJLB.js +0 -437
- package/dist/chunk-SYOFLJLB.js.map +0 -1
- package/dist/chunk-VGOOQ56H.js +0 -103
- package/dist/chunk-VGOOQ56H.js.map +0 -1
package/dist/bin.js
CHANGED
|
@@ -1,21 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
|
-
createCommand
|
|
3
|
+
createCommand
|
|
4
|
+
} from "./chunk-ZGYRDYXS.js";
|
|
5
|
+
import {
|
|
6
|
+
deployCommand,
|
|
7
|
+
generateTypes
|
|
8
|
+
} from "./chunk-E4JG7THU.js";
|
|
9
|
+
import {
|
|
10
|
+
DevServerError,
|
|
11
|
+
InvalidProjectError,
|
|
12
|
+
SchemaNotFoundError,
|
|
4
13
|
createLogger,
|
|
5
14
|
findProjectRoot,
|
|
6
15
|
findSchemaFile,
|
|
7
16
|
hasTsxInstalled,
|
|
8
17
|
promptConfirm,
|
|
9
18
|
resolveProjectBinaryEntryPoint
|
|
10
|
-
} from "./chunk-
|
|
11
|
-
import {
|
|
12
|
-
generateTypes
|
|
13
|
-
} from "./chunk-N36PFOSA.js";
|
|
14
|
-
import {
|
|
15
|
-
DevServerError,
|
|
16
|
-
InvalidProjectError,
|
|
17
|
-
SchemaNotFoundError
|
|
18
|
-
} from "./chunk-VGOOQ56H.js";
|
|
19
|
+
} from "./chunk-KTSRAPSE.js";
|
|
19
20
|
|
|
20
21
|
// src/bin.ts
|
|
21
22
|
import { defineCommand as defineCommand4, runMain } from "citty";
|
|
@@ -1622,6 +1623,7 @@ var main = defineCommand4({
|
|
|
1622
1623
|
subCommands: {
|
|
1623
1624
|
create: createCommand,
|
|
1624
1625
|
dev: devCommand,
|
|
1626
|
+
deploy: deployCommand,
|
|
1625
1627
|
generate: generateCommand,
|
|
1626
1628
|
migrate: migrateCommand
|
|
1627
1629
|
}
|
package/dist/bin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/bin.ts","../src/commands/dev/dev-command.ts","../src/commands/dev/kora-config.ts","../src/commands/dev/process-manager.ts","../src/commands/dev/schema-watcher.ts","../src/commands/generate/generate-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/schema-loader.ts"],"sourcesContent":["import { defineCommand, runMain } from 'citty'\nimport { createCommand } from './commands/create/create-command'\nimport { devCommand } from './commands/dev/dev-command'\nimport { generateCommand } from './commands/generate/generate-command'\nimport { migrateCommand } from './commands/migrate/migrate-command'\n\nconst main = defineCommand({\n\tmeta: {\n\t\tname: 'kora',\n\t\tdescription: 'Kora.js — Offline-first application framework',\n\t},\n\tsubCommands: {\n\t\tcreate: createCommand,\n\t\tdev: devCommand,\n\t\tgenerate: generateCommand,\n\t\tmigrate: migrateCommand,\n\t},\n})\n\nrunMain(main)\n","import { 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 { 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\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 (syncAllowed && syncServerFile === null && managedSyncStore === null && postgresEnvRequested) {\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(`Configured schema file not found: ${candidate}. Falling back to auto-detection.`)\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\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\tonExit: onManagedProcessExit,\n\t\t})\n\n\t\tif (shouldStartSync && hasTsx && syncServerFile) {\n\t\t\tprocessManager.spawn({\n\t\t\t\tlabel: 'sync',\n\t\t\t\tcommand: process.execPath,\n\t\t\t\targs: ['--import', 'tsx', syncServerFile],\n\t\t\t\tcwd: projectRoot,\n\t\t\t\tenv: {\n\t\t\t\t\tPORT: String(syncPort),\n\t\t\t\t\tKORA_SYNC_PORT: String(syncPort),\n\t\t\t\t},\n\t\t\t\tonExit: onManagedProcessExit,\n\t\t\t})\n\t\t}\n\n\t\tif (shouldStartSync && syncServerFile === null && managedSyncStore !== null) {\n\t\t\tprocessManager.spawn({\n\t\t\t\tlabel: 'sync',\n\t\t\t\tcommand: process.execPath,\n\t\t\t\targs: ['--input-type=module', '--eval', MANAGED_SYNC_BOOTSTRAP_SCRIPT],\n\t\t\t\tcwd: projectRoot,\n\t\t\t\tenv: {\n\t\t\t\t\tKORA_DEV_SYNC_CONFIG: JSON.stringify({\n\t\t\t\t\t\tport: Number(syncPort),\n\t\t\t\t\t\tstore: managedSyncStore,\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t\tonExit: onManagedProcessExit,\n\t\t\t})\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\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 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') return 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 } 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\t\tsync?:\n\t\t\t\t| boolean\n\t\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\ttype: 'memory'\n\t\t\t\t\t\t}\n\t\t\t\t\t\t| {\n\t\t\t\t\t\t\ttype: 'sqlite'\n\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\ttype: 'postgres'\n\t\t\t\t\t\t\tconnectionString: string\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\twatch?:\n\t\t\t| boolean\n\t\t\t| {\n\t\t\t\tenabled?: boolean\n\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 { 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\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 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'\n\nexport interface SchemaWatcherConfig {\n\tschemaPath: string\n\tprojectRoot: string\n\tdebounceMs?: number\n\tonRegenerate?: () => 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\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\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(this.config.projectRoot, 'node_modules', '@korajs', 'cli', 'dist', 'bin.js')\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}\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 { 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 { 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},\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 { 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 { loadSchemaDefinition } from './schema-loader'\nimport { diffSchemas } from './schema-differ'\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(outputDir, diff.fromVersion, diff.toVersion, generated)\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)\nconst 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\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\treturn {\n\t\tfromVersion: Number.parseInt(match[1], 10),\n\t\ttoVersion: Number.parseInt(match[2], 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 (targetDescriptor.required && targetDescriptor.defaultValue === undefined && !targetDescriptor.auto) {\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 (column === 'id' || column === '_created_at' || column === '_updated_at' || column === '_deleted') {\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 '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\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)) 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","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(\n\t\t\tprojectRoot ? `${projectRoot}/package.json` : import.meta.url,\n\t\t)\n\t\tconst Database = requireFrom('better-sqlite3') as new (path: string) => {\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<{ count: number }[]>(\n\t\t\t`SELECT COUNT(*)::int AS count FROM _kora_migrations WHERE id = ${sqlLiteral(migrationId)}`,\n\t\t)\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","import { spawn } from 'node:child_process'\nimport { extname } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { SchemaDefinition } from '@korajs/core'\nimport { hasTsxInstalled } from '../../utils/fs-helpers'\n\n/**\n * Loads a schema definition from a TS/JS module.\n */\nexport async function loadSchemaDefinition(\n\tschemaPath: string,\n\tprojectRoot: string,\n): Promise<SchemaDefinition> {\n\tconst ext = extname(schemaPath)\n\tconst moduleValue =\n\t\text === '.ts' || ext === '.mts' || ext === '.cts'\n\t\t\t? await loadTypeScriptModule(schemaPath, projectRoot)\n\t\t\t: await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}-${Math.random()}`)\n\n\treturn extractSchema(moduleValue)\n}\n\nfunction extractSchema(value: unknown): SchemaDefinition {\n\tif (typeof value !== 'object' || value === null) {\n\t\tthrow new Error('Schema module must export an object.')\n\t}\n\n\tconst moduleRecord = value as Record<string, unknown>\n\tconst candidate = moduleRecord.default ?? moduleRecord\n\n\tif (!isSchemaDefinition(candidate)) {\n\t\tthrow new Error('Schema module must export a valid SchemaDefinition as default export.')\n\t}\n\n\treturn candidate\n}\n\nfunction isSchemaDefinition(value: unknown): value is SchemaDefinition {\n\tif (typeof value !== 'object' || value === null) return false\n\tconst object = value as Record<string, unknown>\n\treturn (\n\t\ttypeof object.version === 'number' &&\n\t\ttypeof object.collections === 'object' &&\n\t\tobject.collections !== null &&\n\t\ttypeof object.relations === 'object' &&\n\t\tobject.relations !== null\n\t)\n}\n\nasync function loadTypeScriptModule(schemaPath: string, projectRoot: string): Promise<unknown> {\n\tif (!(await hasTsxInstalled(projectRoot))) {\n\t\tthrow new Error(\n\t\t\t`Schema file is TypeScript (${schemaPath}) but local \"tsx\" was not found. Install tsx in the project.`,\n\t\t)\n\t}\n\n\tconst script =\n\t\t'const modulePath = process.argv[process.argv.length - 1];' +\n\t\t\"import('node:url').then(u => import(u.pathToFileURL(modulePath).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, schemaPath],\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 schema module output for ${schemaPath}`)\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(\n\t\t\t\tnew Error(`Failed to load TypeScript schema (exit ${code ?? 'unknown'}): ${stderr.trim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M;AAAA,EACnB;AAEA,SAAO;AACR;;;ANhaA,IAAM,OAAOI,eAAc;AAAA,EAC1B,MAAM;AAAA,IACL,MAAM;AAAA,IACN,aAAa;AAAA,EACd;AAAA,EACA,aAAa;AAAA,IACZ,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,UAAU;AAAA,IACV,SAAS;AAAA,EACV;AACD,CAAC;AAED,QAAQ,IAAI;","names":["defineCommand","access","join","loaded","resolve","resolve","spawn","join","join","resolve","spawn","join","resolve","access","resolve","defineCommand","defineCommand","resolve","mkdir","writeFile","dirname","join","resolve","defineCommand","sqlLiteral","spawn","extname","pathToFileURL","extname","pathToFileURL","extractSchema","isSchemaDefinition","runCommand","resolve","spawn","defineCommand","resolve","join","mkdir","dirname","writeFile","defineCommand"]}
|
|
1
|
+
{"version":3,"sources":["../src/bin.ts","../src/commands/dev/dev-command.ts","../src/commands/dev/kora-config.ts","../src/commands/dev/process-manager.ts","../src/commands/dev/schema-watcher.ts","../src/commands/generate/generate-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/schema-loader.ts"],"sourcesContent":["import { defineCommand, runMain } from 'citty'\nimport { createCommand } from './commands/create/create-command'\nimport { deployCommand } from './commands/deploy/deploy-command'\nimport { devCommand } from './commands/dev/dev-command'\nimport { generateCommand } from './commands/generate/generate-command'\nimport { migrateCommand } from './commands/migrate/migrate-command'\n\nconst main = defineCommand({\n\tmeta: {\n\t\tname: 'kora',\n\t\tdescription: 'Kora.js — Offline-first application framework',\n\t},\n\tsubCommands: {\n\t\tcreate: createCommand,\n\t\tdev: devCommand,\n\t\tdeploy: deployCommand,\n\t\tgenerate: generateCommand,\n\t\tmigrate: migrateCommand,\n\t},\n})\n\nrunMain(main)\n","import { 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 { 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\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 (syncAllowed && syncServerFile === null && managedSyncStore === null && postgresEnvRequested) {\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(`Configured schema file not found: ${candidate}. Falling back to auto-detection.`)\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\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\tonExit: onManagedProcessExit,\n\t\t})\n\n\t\tif (shouldStartSync && hasTsx && syncServerFile) {\n\t\t\tprocessManager.spawn({\n\t\t\t\tlabel: 'sync',\n\t\t\t\tcommand: process.execPath,\n\t\t\t\targs: ['--import', 'tsx', syncServerFile],\n\t\t\t\tcwd: projectRoot,\n\t\t\t\tenv: {\n\t\t\t\t\tPORT: String(syncPort),\n\t\t\t\t\tKORA_SYNC_PORT: String(syncPort),\n\t\t\t\t},\n\t\t\t\tonExit: onManagedProcessExit,\n\t\t\t})\n\t\t}\n\n\t\tif (shouldStartSync && syncServerFile === null && managedSyncStore !== null) {\n\t\t\tprocessManager.spawn({\n\t\t\t\tlabel: 'sync',\n\t\t\t\tcommand: process.execPath,\n\t\t\t\targs: ['--input-type=module', '--eval', MANAGED_SYNC_BOOTSTRAP_SCRIPT],\n\t\t\t\tcwd: projectRoot,\n\t\t\t\tenv: {\n\t\t\t\t\tKORA_DEV_SYNC_CONFIG: JSON.stringify({\n\t\t\t\t\t\tport: Number(syncPort),\n\t\t\t\t\t\tstore: managedSyncStore,\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t\tonExit: onManagedProcessExit,\n\t\t\t})\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\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 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') return 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 } 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\t\tsync?:\n\t\t\t\t| boolean\n\t\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\ttype: 'memory'\n\t\t\t\t\t\t}\n\t\t\t\t\t\t| {\n\t\t\t\t\t\t\ttype: 'sqlite'\n\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\ttype: 'postgres'\n\t\t\t\t\t\t\tconnectionString: string\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\twatch?:\n\t\t\t| boolean\n\t\t\t| {\n\t\t\t\tenabled?: boolean\n\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 { 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\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 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'\n\nexport interface SchemaWatcherConfig {\n\tschemaPath: string\n\tprojectRoot: string\n\tdebounceMs?: number\n\tonRegenerate?: () => 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\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\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(this.config.projectRoot, 'node_modules', '@korajs', 'cli', 'dist', 'bin.js')\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}\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 { 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 { 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},\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 { 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 { loadSchemaDefinition } from './schema-loader'\nimport { diffSchemas } from './schema-differ'\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(outputDir, diff.fromVersion, diff.toVersion, generated)\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)\nconst 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\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\treturn {\n\t\tfromVersion: Number.parseInt(match[1], 10),\n\t\ttoVersion: Number.parseInt(match[2], 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 (targetDescriptor.required && targetDescriptor.defaultValue === undefined && !targetDescriptor.auto) {\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 (column === 'id' || column === '_created_at' || column === '_updated_at' || column === '_deleted') {\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 '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\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)) 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","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(\n\t\t\tprojectRoot ? `${projectRoot}/package.json` : import.meta.url,\n\t\t)\n\t\tconst Database = requireFrom('better-sqlite3') as new (path: string) => {\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<{ count: number }[]>(\n\t\t\t`SELECT COUNT(*)::int AS count FROM _kora_migrations WHERE id = ${sqlLiteral(migrationId)}`,\n\t\t)\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","import { spawn } from 'node:child_process'\nimport { extname } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { SchemaDefinition } from '@korajs/core'\nimport { hasTsxInstalled } from '../../utils/fs-helpers'\n\n/**\n * Loads a schema definition from a TS/JS module.\n */\nexport async function loadSchemaDefinition(\n\tschemaPath: string,\n\tprojectRoot: string,\n): Promise<SchemaDefinition> {\n\tconst ext = extname(schemaPath)\n\tconst moduleValue =\n\t\text === '.ts' || ext === '.mts' || ext === '.cts'\n\t\t\t? await loadTypeScriptModule(schemaPath, projectRoot)\n\t\t\t: await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}-${Math.random()}`)\n\n\treturn extractSchema(moduleValue)\n}\n\nfunction extractSchema(value: unknown): SchemaDefinition {\n\tif (typeof value !== 'object' || value === null) {\n\t\tthrow new Error('Schema module must export an object.')\n\t}\n\n\tconst moduleRecord = value as Record<string, unknown>\n\tconst candidate = moduleRecord.default ?? moduleRecord\n\n\tif (!isSchemaDefinition(candidate)) {\n\t\tthrow new Error('Schema module must export a valid SchemaDefinition as default export.')\n\t}\n\n\treturn candidate\n}\n\nfunction isSchemaDefinition(value: unknown): value is SchemaDefinition {\n\tif (typeof value !== 'object' || value === null) return false\n\tconst object = value as Record<string, unknown>\n\treturn (\n\t\ttypeof object.version === 'number' &&\n\t\ttypeof object.collections === 'object' &&\n\t\tobject.collections !== null &&\n\t\ttypeof object.relations === 'object' &&\n\t\tobject.relations !== null\n\t)\n}\n\nasync function loadTypeScriptModule(schemaPath: string, projectRoot: string): Promise<unknown> {\n\tif (!(await hasTsxInstalled(projectRoot))) {\n\t\tthrow new Error(\n\t\t\t`Schema file is TypeScript (${schemaPath}) but local \"tsx\" was not found. Install tsx in the project.`,\n\t\t)\n\t}\n\n\tconst script =\n\t\t'const modulePath = process.argv[process.argv.length - 1];' +\n\t\t\"import('node:url').then(u => import(u.pathToFileURL(modulePath).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, schemaPath],\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 schema module output for ${schemaPath}`)\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(\n\t\t\t\tnew Error(`Failed to load TypeScript schema (exit ${code ?? 'unknown'}): ${stderr.trim()}`),\n\t\t\t)\n\t\t})\n\t})\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,S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AAM;AAAA,IACL,MAAM;AAAA,IACN,aAAa;AAAA,EACd;AAAA,EACA,aAAa;AAAA,IACZ,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,SAAS;AAAA,EACV;AACD,CAAC;AAED,QAAQ,IAAI;","names":["defineCommand","access","join","loaded","resolve","resolve","spawn","join","join","resolve","spawn","join","resolve","access","resolve","defineCommand","defineCommand","resolve","mkdir","writeFile","dirname","join","resolve","defineCommand","sqlLiteral","spawn","extname","pathToFileURL","extname","pathToFileURL","extractSchema","isSchemaDefinition","runCommand","resolve","spawn","defineCommand","resolve","join","mkdir","dirname","writeFile","defineCommand"]}
|