@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.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/bin.ts","../src/commands/create/create-command.ts","../src/errors.ts","../src/types.ts","../src/utils/fs-helpers.ts","../src/utils/logger.ts","../src/utils/package-manager.ts","../src/utils/prompt.ts","../src/commands/create/template-engine.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/generate/type-generator.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 { execSync } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { dirname, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { defineCommand } from 'citty'\nimport { ProjectExistsError } from '../../errors'\nimport { PACKAGE_MANAGERS, TEMPLATES, TEMPLATE_INFO } from '../../types'\nimport type { PackageManager, TemplateName } from '../../types'\nimport { directoryExists } from '../../utils/fs-helpers'\nimport { createLogger } from '../../utils/logger'\nimport {\n\tdetectPackageManager,\n\tgetInstallCommand,\n\tgetRunDevCommand,\n} from '../../utils/package-manager'\nimport { promptSelect, promptText } from '../../utils/prompt'\nimport { scaffoldTemplate } from './template-engine'\n\n/**\n * The `create` command — scaffolds a new Kora project.\n * Used as `kora create <name>` or `create-kora-app <name>`.\n */\nexport const createCommand = defineCommand({\n\tmeta: {\n\t\tname: 'create',\n\t\tdescription: 'Create a new Kora application',\n\t},\n\targs: {\n\t\tname: {\n\t\t\ttype: 'positional',\n\t\t\tdescription: 'Project directory name',\n\t\t\trequired: false,\n\t\t},\n\t\ttemplate: {\n\t\t\ttype: 'string',\n\t\t\tdescription:\n\t\t\t\t'Project template (react-tailwind-sync, react-tailwind, react-sync, react-basic)',\n\t\t},\n\t\tpm: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Package manager (pnpm, npm, yarn, bun)',\n\t\t},\n\t\t'skip-install': {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Skip installing dependencies',\n\t\t\tdefault: false,\n\t\t},\n\t\tyes: {\n\t\t\ttype: 'boolean',\n\t\t\talias: 'y',\n\t\t\tdescription: 'Accept all defaults (react-tailwind-sync + detected package manager)',\n\t\t\tdefault: false,\n\t\t},\n\t\ttailwind: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Use Tailwind CSS (use --no-tailwind to skip)',\n\t\t},\n\t\tsync: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Include sync server (use --no-sync to skip)',\n\t\t},\n\t},\n\tasync run({ args }) {\n\t\tconst logger = createLogger()\n\t\tlogger.banner()\n\n\t\tconst useDefaults = args.yes === true\n\n\t\t// Resolve project name\n\t\tconst projectName =\n\t\t\targs.name || (useDefaults ? 'my-kora-app' : await promptText('Project name', 'my-kora-app'))\n\t\tif (!projectName) {\n\t\t\tlogger.error('Project name is required')\n\t\t\tprocess.exitCode = 1\n\t\t\treturn\n\t\t}\n\n\t\t// Resolve template\n\t\tlet template: TemplateName\n\t\tif (args.template && isValidTemplate(args.template)) {\n\t\t\t// Explicit --template flag takes priority\n\t\t\ttemplate = args.template\n\t\t} else if (useDefaults) {\n\t\t\t// --yes defaults to recommended template\n\t\t\ttemplate = 'react-tailwind-sync'\n\t\t} else if (args.tailwind !== undefined || args.sync !== undefined) {\n\t\t\t// Derive template from --tailwind and --sync flags\n\t\t\ttemplate = resolveTemplateFromFlags(args.tailwind, args.sync)\n\t\t} else {\n\t\t\ttemplate = await promptSelect(\n\t\t\t\t'Select a template:',\n\t\t\t\tTEMPLATE_INFO.map((t) => ({ label: `${t.label} — ${t.description}`, value: t.name })),\n\t\t\t)\n\t\t}\n\n\t\t// Resolve package manager\n\t\tlet pm: PackageManager\n\t\tif (args.pm && isValidPackageManager(args.pm)) {\n\t\t\tpm = args.pm\n\t\t} else if (useDefaults) {\n\t\t\tpm = detectPackageManager()\n\t\t} else {\n\t\t\tconst detected = detectPackageManager()\n\t\t\tpm = await promptSelect(\n\t\t\t\t'Package manager:',\n\t\t\t\tPACKAGE_MANAGERS.map((p) => ({\n\t\t\t\t\tlabel: p === detected ? `${p} (detected)` : p,\n\t\t\t\t\tvalue: p,\n\t\t\t\t})),\n\t\t\t)\n\t\t}\n\n\t\t// Validate target directory\n\t\tconst targetDir = resolve(process.cwd(), projectName)\n\t\tif (await directoryExists(targetDir)) {\n\t\t\tthrow new ProjectExistsError(projectName)\n\t\t}\n\n\t\t// Resolve kora version from this package's own package.json\n\t\tconst koraVersion = resolveKoraVersion()\n\n\t\t// Scaffold\n\t\tlogger.step(`Creating ${projectName} with ${template} template...`)\n\t\tawait scaffoldTemplate(template, targetDir, {\n\t\t\tprojectName,\n\t\t\tpackageManager: pm,\n\t\t\tkoraVersion,\n\t\t})\n\t\tlogger.success('Project scaffolded')\n\n\t\t// Install dependencies\n\t\tif (!args['skip-install']) {\n\t\t\tlogger.step('Installing dependencies...')\n\t\t\ttry {\n\t\t\t\texecSync(getInstallCommand(pm), { cwd: targetDir, stdio: 'inherit' })\n\t\t\t\tlogger.success('Dependencies installed')\n\t\t\t} catch {\n\t\t\t\tlogger.warn('Failed to install dependencies. Run install manually.')\n\t\t\t}\n\t\t}\n\n\t\t// Print next steps\n\t\tlogger.blank()\n\t\tlogger.info('Done! Next steps:')\n\t\tlogger.blank()\n\t\tlogger.step(` cd ${projectName}`)\n\t\tlogger.step(` ${getRunDevCommand(pm)}`)\n\t\tlogger.blank()\n\t},\n})\n\nfunction isValidTemplate(value: string): value is TemplateName {\n\treturn (TEMPLATES as readonly string[]).includes(value)\n}\n\nfunction isValidPackageManager(value: string): value is PackageManager {\n\treturn (PACKAGE_MANAGERS as readonly string[]).includes(value)\n}\n\n/**\n * Derives the template name from --tailwind and --sync boolean flags.\n * Unspecified flags default to true (tailwind and sync are the recommended defaults).\n */\nfunction resolveTemplateFromFlags(\n\ttailwind: boolean | undefined,\n\tsync: boolean | undefined,\n): TemplateName {\n\tconst useTailwind = tailwind !== false\n\tconst useSync = sync !== false\n\tif (useTailwind && useSync) return 'react-tailwind-sync'\n\tif (useTailwind && !useSync) return 'react-tailwind'\n\tif (!useTailwind && useSync) return 'react-sync'\n\treturn 'react-basic'\n}\n\n/**\n * Reads the version from @korajs/cli's own package.json and derives a\n * compatible version range for all @korajs packages.\n *\n * The CLI may be a patch ahead of other packages (e.g. CLI-only fixes),\n * so we use the major.minor range (^major.minor.0) which matches all\n * packages in the same release series.\n */\nfunction resolveKoraVersion(): string {\n\ttry {\n\t\tlet dir = dirname(fileURLToPath(import.meta.url))\n\t\tfor (let i = 0; i < 5; i++) {\n\t\t\tconst pkgPath = resolve(dir, 'package.json')\n\t\t\tif (existsSync(pkgPath)) {\n\t\t\t\tconst pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')) as { name?: string; version: string }\n\t\t\t\tif (pkg.name === '@korajs/cli') {\n\t\t\t\t\tif (pkg.version === '0.0.0') return 'latest'\n\t\t\t\t\t// Use ^major.minor.0 so all packages in the series match\n\t\t\t\t\tconst parts = pkg.version.split('.')\n\t\t\t\t\treturn `^${parts[0]}.${parts[1]}.0`\n\t\t\t\t}\n\t\t\t}\n\t\t\tdir = dirname(dir)\n\t\t}\n\t\treturn 'latest'\n\t} catch {\n\t\treturn 'latest'\n\t}\n}\n","import { KoraError } from '@korajs/core'\n\n/**\n * Base error class for all CLI errors.\n */\nexport class CliError extends KoraError {\n\tconstructor(message: string, context?: Record<string, unknown>) {\n\t\tsuper(message, 'CLI_ERROR', context)\n\t\tthis.name = 'CliError'\n\t}\n}\n\n/**\n * Thrown when the target project directory already exists.\n */\nexport class ProjectExistsError extends KoraError {\n\tconstructor(public readonly directory: string) {\n\t\tsuper(\n\t\t\t`Directory \"${directory}\" already exists. Choose a different name or remove the existing directory.`,\n\t\t\t'PROJECT_EXISTS',\n\t\t\t{ directory },\n\t\t)\n\t\tthis.name = 'ProjectExistsError'\n\t}\n}\n\n/**\n * Thrown when a schema file cannot be found in the project.\n */\nexport class SchemaNotFoundError extends KoraError {\n\tconstructor(public readonly searchedPaths: string[]) {\n\t\tsuper(\n\t\t\t`Could not find a schema file. Searched: ${searchedPaths.join(', ')}. Create a schema file using defineSchema() from @korajs/core.`,\n\t\t\t'SCHEMA_NOT_FOUND',\n\t\t\t{ searchedPaths },\n\t\t)\n\t\tthis.name = 'SchemaNotFoundError'\n\t}\n}\n\n/**\n * Thrown when a command is run outside a valid Kora project.\n */\nexport class InvalidProjectError extends KoraError {\n\tconstructor(public readonly directory: string) {\n\t\tsuper(\n\t\t\t`\"${directory}\" is not a valid Kora project. No package.json with a kora dependency found. Run this command from inside a Kora project.`,\n\t\t\t'INVALID_PROJECT',\n\t\t\t{ directory },\n\t\t)\n\t\tthis.name = 'InvalidProjectError'\n\t}\n}\n\n/**\n * Thrown when a required local dev server binary cannot be found.\n */\nexport class DevServerError extends KoraError {\n\tconstructor(\n\t\tpublic readonly binary: string,\n\t\tpublic readonly searchPath: string,\n\t) {\n\t\tsuper(\n\t\t\t`Could not find required binary \"${binary}\" at ${searchPath}. Install project dependencies and try again.`,\n\t\t\t'DEV_SERVER_ERROR',\n\t\t\t{ binary, searchPath },\n\t\t)\n\t\tthis.name = 'DevServerError'\n\t}\n}\n","/** Supported package managers */\nexport const PACKAGE_MANAGERS = ['pnpm', 'npm', 'yarn', 'bun'] as const\nexport type PackageManager = (typeof PACKAGE_MANAGERS)[number]\n\n/** Available project templates */\nexport const TEMPLATES = [\n\t'react-tailwind-sync',\n\t'react-tailwind',\n\t'react-sync',\n\t'react-basic',\n] as const\nexport type TemplateName = (typeof TEMPLATES)[number]\n\n/** Metadata for a project template */\nexport interface TemplateInfo {\n\tname: TemplateName\n\tlabel: string\n\tdescription: string\n}\n\n/** Available templates with their descriptions */\nexport const TEMPLATE_INFO: readonly TemplateInfo[] = [\n\t{\n\t\tname: 'react-tailwind-sync',\n\t\tlabel: 'React + Tailwind (with sync)',\n\t\tdescription: 'Polished dark-themed app with Tailwind CSS and sync server (Recommended)',\n\t},\n\t{\n\t\tname: 'react-tailwind',\n\t\tlabel: 'React + Tailwind (local-only)',\n\t\tdescription: 'Polished dark-themed app with Tailwind CSS — no sync server',\n\t},\n\t{\n\t\tname: 'react-sync',\n\t\tlabel: 'React + CSS (with sync)',\n\t\tdescription: 'Clean CSS app with sync server included',\n\t},\n\t{\n\t\tname: 'react-basic',\n\t\tlabel: 'React + CSS (local-only)',\n\t\tdescription: 'Clean CSS app — no sync server',\n\t},\n] as const\n\n/** Variables available for template substitution */\nexport interface TemplateContext {\n\tprojectName: string\n\tpackageManager: PackageManager\n\tkoraVersion: string\n}\n","import { access, readFile } from 'node:fs/promises'\nimport { dirname, join, resolve } from 'node:path'\n\n/** Checks if a directory exists at the given path */\nexport async function directoryExists(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\n/**\n * Walks up the directory tree from startDir looking for a package.json\n * that contains a kora or @korajs/* dependency.\n *\n * @param startDir - Directory to start searching from (defaults to cwd)\n * @returns Absolute path to the project root, or null if not found\n */\nexport async function findProjectRoot(startDir?: string): Promise<string | null> {\n\tlet current = resolve(startDir ?? process.cwd())\n\n\t// Walk up until the filesystem root (where dirname(x) === x)\n\tfor (;;) {\n\t\tconst pkgPath = join(current, 'package.json')\n\t\ttry {\n\t\t\tconst content = await readFile(pkgPath, 'utf-8')\n\t\t\tconst pkg: unknown = JSON.parse(content)\n\t\t\tif (isKoraProject(pkg)) {\n\t\t\t\treturn current\n\t\t\t}\n\t\t} catch {\n\t\t\t// No package.json at this level, keep walking up\n\t\t}\n\t\tconst parent = dirname(current)\n\t\tif (parent === current) break\n\t\tcurrent = parent\n\t}\n\n\treturn null\n}\n\n/**\n * Searches for a schema file in common locations within a project.\n *\n * @param projectRoot - The project root directory\n * @returns Absolute path to the schema file, or null if not found\n */\nexport async function findSchemaFile(projectRoot: string): Promise<string | null> {\n\tconst candidates = [\n\t\tjoin(projectRoot, 'src', 'schema.ts'),\n\t\tjoin(projectRoot, 'schema.ts'),\n\t\tjoin(projectRoot, 'src', 'schema.js'),\n\t\tjoin(projectRoot, 'schema.js'),\n\t]\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// Not found, try next\n\t\t}\n\t}\n\n\treturn null\n}\n\n/**\n * Resolves a binary from a project's local node_modules/.bin directory.\n * On Windows, npm creates .cmd shims instead of extensionless files.\n *\n * @param projectRoot - The project root directory\n * @param binaryName - Binary filename (for example: vite, tsx, kora)\n * @returns Absolute path to the binary, or null if not found\n */\nexport async function resolveProjectBinary(\n\tprojectRoot: string,\n\tbinaryName: string,\n): Promise<string | null> {\n\tconst binDir = join(projectRoot, 'node_modules', '.bin')\n\t// On Windows, try .cmd first (npm/pnpm create .cmd shims)\n\tconst candidates =\n\t\tprocess.platform === 'win32'\n\t\t\t? [join(binDir, `${binaryName}.cmd`), join(binDir, binaryName)]\n\t\t\t: [join(binDir, binaryName)]\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\treturn null\n}\n\n/**\n * Checks whether the `tsx` package is installed in the project's node_modules.\n * Used to determine if we can use `--import tsx` with process.execPath.\n */\nexport async function hasTsxInstalled(projectRoot: string): Promise<boolean> {\n\ttry {\n\t\tawait access(join(projectRoot, 'node_modules', 'tsx', 'package.json'))\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Resolves the JS entry point for a package binary.\n * Reads the package.json bin field to find the actual JS file,\n * avoiding .cmd shims and shell:true on Windows.\n *\n * @returns Absolute path to the JS entry point, or null if not found\n */\nexport async function resolveProjectBinaryEntryPoint(\n\tprojectRoot: string,\n\tpackageName: string,\n\tbinaryName: string,\n): Promise<string | null> {\n\tconst pkgJsonPath = join(projectRoot, 'node_modules', packageName, 'package.json')\n\ttry {\n\t\tconst content = await readFile(pkgJsonPath, 'utf-8')\n\t\tconst pkg = JSON.parse(content) as { bin?: string | Record<string, string> }\n\t\tlet binPath: string | undefined\n\t\tif (typeof pkg.bin === 'string') {\n\t\t\tbinPath = pkg.bin\n\t\t} else if (typeof pkg.bin === 'object' && pkg.bin !== null) {\n\t\t\tbinPath = pkg.bin[binaryName]\n\t\t}\n\t\tif (!binPath) return null\n\t\tconst fullPath = join(projectRoot, 'node_modules', packageName, binPath)\n\t\tawait access(fullPath)\n\t\treturn fullPath\n\t} catch {\n\t\treturn null\n\t}\n}\n\nfunction isKoraProject(pkg: unknown): boolean {\n\tif (typeof pkg !== 'object' || pkg === null) return false\n\tconst record = pkg as Record<string, unknown>\n\treturn hasKoraDep(record.dependencies) || hasKoraDep(record.devDependencies)\n}\n\nfunction hasKoraDep(deps: unknown): boolean {\n\tif (typeof deps !== 'object' || deps === null) return false\n\treturn Object.keys(deps).some((key) => key === 'kora' || key.startsWith('@korajs/'))\n}\n","/** ANSI escape codes for terminal colors */\nconst RESET = '\\x1b[0m'\nconst BOLD = '\\x1b[1m'\nconst DIM = '\\x1b[2m'\nconst GREEN = '\\x1b[32m'\nconst YELLOW = '\\x1b[33m'\nconst RED = '\\x1b[31m'\nconst CYAN = '\\x1b[36m'\n\nexport interface LoggerOptions {\n\t/** Disable ANSI colors */\n\tnoColor?: boolean\n}\n\nexport interface Logger {\n\tinfo(message: string): void\n\tsuccess(message: string): void\n\twarn(message: string): void\n\terror(message: string): void\n\tstep(message: string): void\n\tblank(): void\n\tbanner(): void\n}\n\n/**\n * Creates a logger with optional ANSI color support.\n * Respects the NO_COLOR environment variable and TTY detection.\n */\nexport function createLogger(options?: LoggerOptions): Logger {\n\tconst colorDisabled =\n\t\toptions?.noColor === true || process.env.NO_COLOR !== undefined || !process.stdout.isTTY\n\n\tfunction color(code: string, text: string): string {\n\t\treturn colorDisabled ? text : `${code}${text}${RESET}`\n\t}\n\n\treturn {\n\t\tinfo(message: string): void {\n\t\t\tconsole.log(color(CYAN, message))\n\t\t},\n\t\tsuccess(message: string): void {\n\t\t\tconsole.log(color(GREEN, ` ✓ ${message}`))\n\t\t},\n\t\twarn(message: string): void {\n\t\t\tconsole.warn(color(YELLOW, ` ⚠ ${message}`))\n\t\t},\n\t\terror(message: string): void {\n\t\t\tconsole.error(color(RED, ` ✗ ${message}`))\n\t\t},\n\t\tstep(message: string): void {\n\t\t\tconsole.log(color(DIM, ` ${message}`))\n\t\t},\n\t\tblank(): void {\n\t\t\tconsole.log()\n\t\t},\n\t\tbanner(): void {\n\t\t\tconsole.log()\n\t\t\tconsole.log(\n\t\t\t\tcolor(BOLD + CYAN, ' Kora.js') + color(DIM, ' — Offline-first application framework'),\n\t\t\t)\n\t\t\tconsole.log()\n\t\t},\n\t}\n}\n","import { execSync } from 'node:child_process'\nimport type { PackageManager } from '../types'\n\n/**\n * Detects the package manager used to invoke the current process\n * by reading the npm_config_user_agent environment variable.\n * Falls back to 'npm' if detection fails.\n */\nexport function detectPackageManager(): PackageManager {\n\tconst userAgent = process.env.npm_config_user_agent\n\tif (!userAgent) return 'npm'\n\n\tif (userAgent.startsWith('pnpm/')) return 'pnpm'\n\tif (userAgent.startsWith('yarn/')) return 'yarn'\n\tif (userAgent.startsWith('bun/')) return 'bun'\n\treturn 'npm'\n}\n\n/** Returns the install command for the given package manager */\nexport function getInstallCommand(pm: PackageManager): string {\n\treturn pm === 'yarn' ? 'yarn' : `${pm} install`\n}\n\n/** Returns the dev server run command for the given package manager */\nexport function getRunDevCommand(pm: PackageManager): string {\n\tif (pm === 'npm') return 'npm run dev'\n\treturn `${pm} dev`\n}\n\n/** Checks if a package manager is available on PATH */\nexport function isPackageManagerAvailable(pm: PackageManager): boolean {\n\ttry {\n\t\texecSync(`${pm} --version`, { stdio: 'ignore' })\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n","import { type Interface as ReadlineInterface, createInterface } from 'node:readline'\n\nexport interface PromptOptions {\n\t/** Input stream (defaults to process.stdin) */\n\tinput?: NodeJS.ReadableStream\n\t/** Output stream (defaults to process.stdout) */\n\toutput?: NodeJS.WritableStream\n}\n\n/**\n * Prompts the user for text input.\n *\n * @param message - The prompt message to display\n * @param defaultValue - Optional default value shown in brackets\n * @param options - Optional input/output streams for testing\n */\nexport function promptText(\n\tmessage: string,\n\tdefaultValue?: string,\n\toptions?: PromptOptions,\n): Promise<string> {\n\treturn new Promise((resolve) => {\n\t\tconst rl = createReadline(options)\n\t\tconst suffix = defaultValue !== undefined ? ` (${defaultValue})` : ''\n\t\trl.question(` ? ${message}${suffix}: `, (answer) => {\n\t\t\trl.close()\n\t\t\tconst trimmed = answer.trim()\n\t\t\tresolve(trimmed || defaultValue || '')\n\t\t})\n\t})\n}\n\n/**\n * Prompts the user to select from a numbered list of options.\n *\n * @param message - The prompt message to display\n * @param choices - Array of { label, value } options\n * @param options - Optional input/output streams for testing\n */\nexport function promptSelect<T extends string>(\n\tmessage: string,\n\tchoices: readonly { label: string; value: T }[],\n\toptions?: PromptOptions,\n): Promise<T> {\n\treturn new Promise((resolve) => {\n\t\tconst rl = createReadline(options)\n\t\tconst out = options?.output ?? process.stdout\n\n\t\tout.write(` ? ${message}\\n`)\n\t\tfor (let i = 0; i < choices.length; i++) {\n\t\t\tconst choice = choices[i]\n\t\t\tif (choice) {\n\t\t\t\tout.write(` ${i + 1}) ${choice.label}\\n`)\n\t\t\t}\n\t\t}\n\n\t\tconst ask = (): void => {\n\t\t\trl.question(' > ', (answer) => {\n\t\t\t\tconst index = Number.parseInt(answer.trim(), 10) - 1\n\t\t\t\tconst selected = choices[index]\n\t\t\t\tif (selected) {\n\t\t\t\t\trl.close()\n\t\t\t\t\tresolve(selected.value)\n\t\t\t\t} else {\n\t\t\t\t\tout.write(` Please enter a number between 1 and ${choices.length}\\n`)\n\t\t\t\t\task()\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\n\t\task()\n\t})\n}\n\n/**\n * Prompts the user with a yes/no confirmation.\n *\n * @param message - The prompt message to display\n * @param defaultValue - Default when input is empty (true => yes)\n * @param options - Optional input/output streams for testing\n */\nexport function promptConfirm(\n\tmessage: string,\n\tdefaultValue = false,\n\toptions?: PromptOptions,\n): Promise<boolean> {\n\treturn new Promise((resolve) => {\n\t\tconst rl = createReadline(options)\n\t\tconst suffix = defaultValue ? 'Y/n' : 'y/N'\n\n\t\tconst ask = (): void => {\n\t\t\trl.question(` ? ${message} (${suffix}): `, (answer) => {\n\t\t\t\tconst normalized = answer.trim().toLowerCase()\n\t\t\t\tif (normalized.length === 0) {\n\t\t\t\t\trl.close()\n\t\t\t\t\tresolve(defaultValue)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif (normalized === 'y' || normalized === 'yes') {\n\t\t\t\t\trl.close()\n\t\t\t\t\tresolve(true)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif (normalized === 'n' || normalized === 'no') {\n\t\t\t\t\trl.close()\n\t\t\t\t\tresolve(false)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t(options?.output ?? process.stdout).write(' Please answer with y or n\\n')\n\t\t\t\task()\n\t\t\t})\n\t\t}\n\n\t\task()\n\t})\n}\n\nfunction createReadline(options?: PromptOptions): ReadlineInterface {\n\treturn createInterface({\n\t\tinput: options?.input ?? process.stdin,\n\t\toutput: options?.output ?? process.stdout,\n\t})\n}\n","import { existsSync } from 'node:fs'\nimport { copyFile, mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises'\nimport { dirname, join, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport type { TemplateContext, TemplateName } from '../../types'\n\n/**\n * Replaces {{variable}} placeholders in a template string with context values.\n *\n * @param template - The template string containing {{variable}} placeholders\n * @param context - Key-value pairs to substitute\n * @returns The template with all placeholders replaced\n */\nexport function substituteVariables(template: string, context: Record<string, string>): string {\n\treturn template.replace(/\\{\\{(\\w+)\\}\\}/g, (_match, key: string) => {\n\t\tconst value = context[key]\n\t\treturn value !== undefined ? value : `{{${key}}}`\n\t})\n}\n\n/**\n * Resolves the absolute path to a bundled template directory.\n *\n * After tsup bundling, import.meta.url points to dist/<file>.js (1 level from root).\n * In source, it's src/commands/create/template-engine.ts (3 levels from root).\n * We walk up from the current file to find the package root containing templates/.\n *\n * @param templateName - Name of the template (e.g. 'react-basic')\n * @returns Absolute path to the template directory\n */\nexport function getTemplatePath(templateName: TemplateName): string {\n\tlet dir = dirname(fileURLToPath(import.meta.url))\n\tfor (let i = 0; i < 5; i++) {\n\t\tif (existsSync(resolve(dir, 'templates'))) {\n\t\t\treturn resolve(dir, 'templates', templateName)\n\t\t}\n\t\tdir = dirname(dir)\n\t}\n\t// Fallback: assume bundled (1 level from package root)\n\tconst currentDir = dirname(fileURLToPath(import.meta.url))\n\treturn resolve(currentDir, '..', 'templates', templateName)\n}\n\n/**\n * Scaffolds a project from a bundled template.\n * Copies all files from the template directory to the target, applying\n * variable substitution to .hbs files and stripping the .hbs extension.\n *\n * @param templateName - Which template to use\n * @param targetDir - Destination directory (must not exist yet)\n * @param context - Variables for template substitution\n */\nexport async function scaffoldTemplate(\n\ttemplateName: TemplateName,\n\ttargetDir: string,\n\tcontext: TemplateContext,\n): Promise<void> {\n\tconst templateDir = getTemplatePath(templateName)\n\tconst vars: Record<string, string> = {\n\t\tprojectName: context.projectName,\n\t\tpackageManager: context.packageManager,\n\t\tkoraVersion: context.koraVersion,\n\t}\n\tawait copyDirectory(templateDir, targetDir, vars)\n}\n\nasync function copyDirectory(\n\tsrc: string,\n\tdest: string,\n\tvars: Record<string, string>,\n): Promise<void> {\n\tawait mkdir(dest, { recursive: true })\n\tconst entries = await readdir(src)\n\n\tfor (const entry of entries) {\n\t\tconst srcPath = join(src, entry)\n\t\tconst srcStat = await stat(srcPath)\n\n\t\tif (srcStat.isDirectory()) {\n\t\t\tawait copyDirectory(srcPath, join(dest, entry), vars)\n\t\t} else if (entry.endsWith('.hbs')) {\n\t\t\t// Template file: substitute variables and strip .hbs extension\n\t\t\tconst content = await readFile(srcPath, 'utf-8')\n\t\t\tconst outputName = entry.slice(0, -4) // Remove .hbs\n\t\t\tawait writeFile(join(dest, outputName), substituteVariables(content, vars), 'utf-8')\n\t\t} else {\n\t\t\t// Regular file: copy as-is\n\t\t\tawait copyFile(srcPath, join(dest, entry))\n\t\t}\n\t}\n}\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 type { FieldDescriptor, FieldKind, SchemaDefinition } from '@korajs/core'\n\n/**\n * Generates TypeScript interfaces from a SchemaDefinition.\n * For each collection, produces three interfaces:\n * - {Name}Record: full record type (all fields + id)\n * - {Name}InsertInput: insert input (omit auto fields, optional for fields with defaults)\n * - {Name}UpdateInput: update input (all non-auto fields optional)\n *\n * @param schema - A validated SchemaDefinition from defineSchema()\n * @returns A complete TypeScript file as a string\n */\nexport function generateTypes(schema: SchemaDefinition): string {\n\tconst lines: string[] = [\n\t\t'// Auto-generated by @korajs/cli — do not edit manually',\n\t\t`// Generated from schema version ${String(schema.version)}`,\n\t\t'',\n\t]\n\n\tconst collectionNames = Object.keys(schema.collections)\n\tif (collectionNames.length === 0) {\n\t\treturn lines.join('\\n')\n\t}\n\n\tfor (const [name, collection] of Object.entries(schema.collections)) {\n\t\tconst pascal = toPascalCase(name)\n\t\tconst fields = collection.fields\n\n\t\t// Record type: all fields + id\n\t\tlines.push(`export interface ${pascal}Record {`)\n\t\tlines.push('\\treadonly id: string')\n\t\tfor (const [fieldName, descriptor] of Object.entries(fields)) {\n\t\t\tconst tsType = fieldKindToTypeScript(descriptor)\n\t\t\tconst optional = !descriptor.required && !descriptor.auto ? '?' : ''\n\t\t\tlines.push(`\\treadonly ${fieldName}${optional}: ${tsType}`)\n\t\t}\n\t\tlines.push('}')\n\t\tlines.push('')\n\n\t\t// Insert input: omit auto fields, optional for fields with defaults\n\t\tlines.push(`export interface ${pascal}InsertInput {`)\n\t\tfor (const [fieldName, descriptor] of Object.entries(fields)) {\n\t\t\tif (descriptor.auto) continue\n\t\t\tconst tsType = fieldKindToTypeScript(descriptor)\n\t\t\tconst optional = !descriptor.required || descriptor.defaultValue !== undefined ? '?' : ''\n\t\t\tlines.push(`\\t${fieldName}${optional}: ${tsType}`)\n\t\t}\n\t\tlines.push('}')\n\t\tlines.push('')\n\n\t\t// Update input: all non-auto fields optional\n\t\tlines.push(`export interface ${pascal}UpdateInput {`)\n\t\tfor (const [fieldName, descriptor] of Object.entries(fields)) {\n\t\t\tif (descriptor.auto) continue\n\t\t\tconst tsType = fieldKindToTypeScript(descriptor)\n\t\t\tlines.push(`\\t${fieldName}?: ${tsType}`)\n\t\t}\n\t\tlines.push('}')\n\t\tlines.push('')\n\t}\n\n\treturn lines.join('\\n')\n}\n\n/** Maps a FieldDescriptor to its TypeScript type string */\nfunction fieldKindToTypeScript(descriptor: FieldDescriptor): string {\n\tswitch (descriptor.kind) {\n\t\tcase 'string':\n\t\t\treturn 'string'\n\t\tcase 'number':\n\t\t\treturn 'number'\n\t\tcase 'boolean':\n\t\t\treturn 'boolean'\n\t\tcase 'timestamp':\n\t\t\treturn 'number'\n\t\tcase 'richtext':\n\t\t\treturn 'string'\n\t\tcase 'enum': {\n\t\t\tif (descriptor.enumValues && descriptor.enumValues.length > 0) {\n\t\t\t\treturn descriptor.enumValues.map((v) => `'${v}'`).join(' | ')\n\t\t\t}\n\t\t\treturn 'string'\n\t\t}\n\t\tcase 'array': {\n\t\t\tconst itemType = itemKindToTypeScript(descriptor.itemKind)\n\t\t\treturn `Array<${itemType}>`\n\t\t}\n\t\tdefault:\n\t\t\treturn 'unknown'\n\t}\n}\n\n/** Maps an item FieldKind to its TypeScript type string */\nfunction itemKindToTypeScript(kind: FieldKind | null): string {\n\tswitch (kind) {\n\t\tcase 'string':\n\t\t\treturn 'string'\n\t\tcase 'number':\n\t\t\treturn 'number'\n\t\tcase 'boolean':\n\t\t\treturn 'boolean'\n\t\tcase 'timestamp':\n\t\t\treturn 'number'\n\t\tcase 'richtext':\n\t\t\treturn 'string'\n\t\tcase 'enum':\n\t\t\treturn 'string'\n\t\tcase 'array':\n\t\t\treturn 'unknown[]'\n\t\tdefault:\n\t\t\treturn 'unknown'\n\t}\n}\n\n/** Converts a snake_case or kebab-case name to PascalCase */\nfunction toPascalCase(name: string): string {\n\treturn name\n\t\t.split(/[_-]/)\n\t\t.map((part) => {\n\t\t\tif (part.length === 0) return ''\n\t\t\tconst first = part[0]\n\t\t\treturn first ? first.toUpperCase() + part.slice(1) : ''\n\t\t})\n\t\t.join('')\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,IAAAA,gBAAuC;;;ACAvC,IAAAC,6BAAyB;AACzB,IAAAC,kBAAyC;AACzC,IAAAC,oBAAiC;AACjC,IAAAC,mBAA8B;AAC9B,mBAA8B;;;ACJ9B,kBAA0B;AAenB,IAAM,qBAAN,cAAiC,sBAAU;AAAA,EACjD,YAA4B,WAAmB;AAC9C;AAAA,MACC,cAAc,SAAS;AAAA,MACvB;AAAA,MACA,EAAE,UAAU;AAAA,IACb;AAL2B;AAM3B,SAAK,OAAO;AAAA,EACb;AAAA,EAP4B;AAQ7B;AAKO,IAAM,sBAAN,cAAkC,sBAAU;AAAA,EAClD,YAA4B,eAAyB;AACpD;AAAA,MACC,2CAA2C,cAAc,KAAK,IAAI,CAAC;AAAA,MACnE;AAAA,MACA,EAAE,cAAc;AAAA,IACjB;AAL2B;AAM3B,SAAK,OAAO;AAAA,EACb;AAAA,EAP4B;AAQ7B;AAKO,IAAM,sBAAN,cAAkC,sBAAU;AAAA,EAClD,YAA4B,WAAmB;AAC9C;AAAA,MACC,IAAI,SAAS;AAAA,MACb;AAAA,MACA,EAAE,UAAU;AAAA,IACb;AAL2B;AAM3B,SAAK,OAAO;AAAA,EACb;AAAA,EAP4B;AAQ7B;AAKO,IAAM,iBAAN,cAA6B,sBAAU;AAAA,EAC7C,YACiB,QACA,YACf;AACD;AAAA,MACC,mCAAmC,MAAM,QAAQ,UAAU;AAAA,MAC3D;AAAA,MACA,EAAE,QAAQ,WAAW;AAAA,IACtB;AAPgB;AACA;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AAK,MAAM,SAAS,UAAU;AAC1F,UAAI,OAAO,KAAK,MAAM,aAAa,YAAY,KAAK,MAAM,SAAS,SAAS,GAAG;AAC9E,mBAAO,4BAAQ,aAAa,KAAK,MAAM,QAAQ;AAAA,MAChD;AACA,iBAAO,yBAAK,aAAa,cAAc;AAAA,IACxC;AAAA,EACD;AAEA,SAAO;AACR;AAEA,SAAS,gCACR,QACqB;AACrB,QAAM,OAAO,QAAQ,KAAK;AAC1B,MAAI,OAAO,SAAS,YAAY,SAAS,KAAM,QAAO;AAEtD,MAAI,KAAK,UAAU,YAAY;AAC9B,WAAO,QAAQ,IAAI;AAAA,EACpB;AAEA,MAAI,OAAO,KAAK,UAAU,YAAY,KAAK,UAAU,QAAQ,KAAK,MAAM,SAAS,YAAY;AAC5F,WAAO,KAAK,MAAM;AAAA,EACnB;AAEA,SAAO;AACR;;;AfhaA,IAAM,WAAO,6BAAc;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;AAAA,IAED,uBAAQ,IAAI;","names":["import_citty","import_node_child_process","import_node_fs","import_node_path","import_node_url","resolve","import_promises","import_node_path","import_meta","import_promises","import_node_path","import_citty","import_node_child_process","import_promises","import_node_path","import_node_url","loaded","resolve","import_node_child_process","spawnChild","resolve","import_node_child_process","import_node_fs","import_node_path","resolve","resolve","import_promises","import_node_path","import_citty","import_promises","import_node_path","import_citty","import_core","import_meta","sqlLiteral","import_node_child_process","import_node_path","import_node_url","extractSchema","isSchemaDefinition","runCommand","resolve"]}
|
|
1
|
+
{"version":3,"sources":["../src/bin.ts","../src/commands/create/create-command.ts","../src/errors.ts","../src/prompts/preferences.ts","../src/prompts/prompt-client.ts","../src/utils/prompt.ts","../src/types.ts","../src/utils/fs-helpers.ts","../src/utils/logger.ts","../src/utils/package-manager.ts","../src/commands/create/environment-detection.ts","../src/commands/create/options.ts","../src/commands/create/preferences-flow.ts","../src/commands/create/project-name.ts","../src/commands/create/sync-provider-preset.ts","../src/templates/composer.ts","../src/commands/create/template-engine.ts","../src/commands/deploy/deploy-command.ts","../src/commands/deploy/adapters/adapter.ts","../src/commands/deploy/adapters/fly-adapter.ts","../src/commands/deploy/artifacts/fly-toml-generator.ts","../src/commands/deploy/builder/client-builder.ts","../src/commands/deploy/builder/server-bundler.ts","../src/commands/deploy/adapters/railway-adapter.ts","../src/commands/deploy/artifacts/railway-json-generator.ts","../src/commands/deploy/adapters/stub-adapter.ts","../src/commands/deploy/adapters/factory.ts","../src/commands/deploy/artifacts/dockerfile-generator.ts","../src/commands/deploy/state/deploy-state.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/generate/type-generator.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 { execSync } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { dirname, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { defineCommand } from 'citty'\nimport { ProjectExistsError } from '../../errors'\nimport { PreferenceStore } from '../../prompts/preferences'\nimport { PromptCancelledError, createPromptClient } from '../../prompts/prompt-client'\nimport { PACKAGE_MANAGERS, TEMPLATES } from '../../types'\nimport type { PackageManager, TemplateName } from '../../types'\nimport { directoryExists } from '../../utils/fs-helpers'\nimport { createLogger } from '../../utils/logger'\nimport {\n\tdetectPackageManager,\n\tgetInstallCommand,\n\tgetRunDevCommand,\n} from '../../utils/package-manager'\nimport {\n\tapplyEditorWorkspacePreset,\n\tdetectEditorFromEnvironment,\n\tdetectGitContext,\n\tdetectMonorepoContext,\n\tresolveMonorepoTargetDirectory,\n} from './environment-detection'\nimport {\n\ttype CreateFlags,\n\tresolveCreatePreferencesFlow,\n\tsaveResolvedPreferences,\n\tshouldSavePreferences,\n} from './preferences-flow'\nimport { validateProjectName } from './project-name'\nimport { applySyncProviderPreset } from './sync-provider-preset'\nimport { scaffoldTemplate } from './template-engine'\n\n/**\n * The `create` command — scaffolds a new Kora project.\n * Used as `kora create <name>` or `create-kora-app <name>`.\n */\nexport const createCommand = defineCommand({\n\tmeta: {\n\t\tname: 'create',\n\t\tdescription: 'Create a new Kora application',\n\t},\n\targs: {\n\t\tname: {\n\t\t\ttype: 'positional',\n\t\t\tdescription: 'Project directory name',\n\t\t\trequired: false,\n\t\t},\n\t\ttemplate: {\n\t\t\ttype: 'string',\n\t\t\tdescription:\n\t\t\t\t'Project template (react-tailwind-sync, react-tailwind, react-sync, react-basic)',\n\t\t},\n\t\tpm: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Package manager (pnpm, npm, yarn, bun)',\n\t\t},\n\t\tframework: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'UI framework (react, vue, svelte, solid)',\n\t\t},\n\t\tdb: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Database backend for sync templates (sqlite, postgres)',\n\t\t},\n\t\t'db-provider': {\n\t\t\ttype: 'string',\n\t\t\tdescription:\n\t\t\t\t'Database provider for postgres (local, supabase, neon, railway, vercel-postgres, custom)',\n\t\t},\n\t\tauth: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Authentication mode (none, email-password, oauth)',\n\t\t},\n\t\t'skip-install': {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Skip installing dependencies',\n\t\t\tdefault: false,\n\t\t},\n\t\tyes: {\n\t\t\ttype: 'boolean',\n\t\t\talias: 'y',\n\t\t\tdescription: 'Accept all defaults (react-tailwind-sync + detected package manager)',\n\t\t\tdefault: false,\n\t\t},\n\t\ttailwind: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Use Tailwind CSS (use --no-tailwind to skip)',\n\t\t},\n\t\tsync: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Include sync server (use --no-sync to skip)',\n\t\t},\n\t},\n\tasync run({ args }) {\n\t\tconst logger = createLogger()\n\t\tconst prompts = createPromptClient()\n\t\tconst preferenceStore = new PreferenceStore()\n\t\tlogger.banner()\n\t\ttry {\n\t\t\tconst useDefaults = args.yes === true\n\t\t\tif (!useDefaults) {\n\t\t\t\tprompts.intro('Kora.js — Offline-first application framework')\n\t\t\t}\n\n\t\t\t// Resolve project name\n\t\t\tconst projectName =\n\t\t\t\targs.name ||\n\t\t\t\t(useDefaults ? 'my-kora-app' : await prompts.text('Project name', 'my-kora-app'))\n\t\t\tif (!projectName) {\n\t\t\t\tlogger.error('Project name is required')\n\t\t\t\tprocess.exitCode = 1\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst nameValidation = validateProjectName(projectName)\n\t\t\tif (!nameValidation.valid) {\n\t\t\t\tlogger.error('Invalid project name.')\n\t\t\t\tfor (const issue of nameValidation.issues) {\n\t\t\t\t\tlogger.step(`- ${issue}`)\n\t\t\t\t}\n\t\t\t\tif (!useDefaults) {\n\t\t\t\t\tprompts.outro('Project creation aborted.')\n\t\t\t\t}\n\t\t\t\tprocess.exitCode = 1\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconst preferenceFlags: CreateFlags = {\n\t\t\t\tframework: typeof args.framework === 'string' ? args.framework : undefined,\n\t\t\t\tauth: typeof args.auth === 'string' ? args.auth : undefined,\n\t\t\t\tdb: typeof args.db === 'string' ? args.db : undefined,\n\t\t\t\tdbProvider: typeof args['db-provider'] === 'string' ? args['db-provider'] : undefined,\n\t\t\t\ttailwind: args.tailwind,\n\t\t\t\tsync: args.sync,\n\t\t\t\tuseDefaults,\n\t\t\t}\n\n\t\t\tconst selection = await resolveCreatePreferencesFlow({\n\t\t\t\tflags: preferenceFlags,\n\t\t\t\tprompts,\n\t\t\t\tstore: preferenceStore,\n\t\t\t})\n\t\t\tif (selection.framework !== 'react') {\n\t\t\t\tlogger.error(`Framework \"${selection.framework}\" is not available yet. Use \"react\".`)\n\t\t\t\tif (!useDefaults) {\n\t\t\t\t\tprompts.outro('Project creation aborted.')\n\t\t\t\t}\n\t\t\t\tprocess.exitCode = 1\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (selection.auth !== 'none') {\n\t\t\t\tlogger.error(`Auth mode \"${selection.auth}\" is not available yet. Use \"none\".`)\n\t\t\t\tif (!useDefaults) {\n\t\t\t\t\tprompts.outro('Project creation aborted.')\n\t\t\t\t}\n\t\t\t\tprocess.exitCode = 1\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Resolve template (explicit --template still overrides all selections).\n\t\t\tconst template: TemplateName =\n\t\t\t\targs.template && isValidTemplate(args.template) ? args.template : selection.template\n\n\t\t\t// Resolve package manager\n\t\t\tlet pm: PackageManager\n\t\t\tif (args.pm && isValidPackageManager(args.pm)) {\n\t\t\t\tpm = args.pm\n\t\t\t} else if (useDefaults) {\n\t\t\t\tpm = detectPackageManager()\n\t\t\t} else if (selection.usedStoredPreferences) {\n\t\t\t\tpm = preferenceStore.getCreatePreferences()?.packageManager ?? detectPackageManager()\n\t\t\t} else {\n\t\t\t\tconst detected = detectPackageManager()\n\t\t\t\tpm = await prompts.select(\n\t\t\t\t\t'Package manager:',\n\t\t\t\t\tPACKAGE_MANAGERS.map((p) => ({\n\t\t\t\t\t\tlabel: p === detected ? `${p} (detected)` : p,\n\t\t\t\t\t\tvalue: p,\n\t\t\t\t\t})),\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst editorDetection = detectEditorFromEnvironment()\n\t\t\tconst gitContext = await detectGitContext(process.cwd())\n\t\t\tconst monorepoContext = await detectMonorepoContext(process.cwd())\n\n\t\t\tlet targetDir = resolve(process.cwd(), projectName)\n\t\t\tif (!useDefaults && monorepoContext.isMonorepo && monorepoContext.root !== null) {\n\t\t\t\tconst useWorkspaceTarget = await prompts.confirm(\n\t\t\t\t\t`Detected ${formatMonorepoKind(monorepoContext.kind)} at ${monorepoContext.root}. Create app under packages/${projectName}?`,\n\t\t\t\t\ttrue,\n\t\t\t\t)\n\t\t\t\tif (useWorkspaceTarget) {\n\t\t\t\t\ttargetDir = resolveMonorepoTargetDirectory(monorepoContext.root, projectName)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Validate target directory\n\t\t\tif (await directoryExists(targetDir)) {\n\t\t\t\tthrow new ProjectExistsError(projectName)\n\t\t\t}\n\n\t\t\t// Resolve kora version from this package's own package.json\n\t\t\tconst koraVersion = resolveKoraVersion()\n\n\t\t\t// Scaffold\n\t\t\tlogger.step(`Creating ${projectName} with ${template} template...`)\n\t\t\tawait scaffoldTemplate(template, targetDir, {\n\t\t\t\tprojectName,\n\t\t\t\tpackageManager: pm,\n\t\t\t\tkoraVersion,\n\t\t\t\tdbProvider: selection.dbProvider,\n\t\t\t})\n\t\t\tawait applySyncProviderPreset({\n\t\t\t\ttargetDir,\n\t\t\t\ttemplate,\n\t\t\t\tdb: selection.db,\n\t\t\t\tdbProvider: selection.dbProvider,\n\t\t\t})\n\t\t\tif (!useDefaults && editorDetection.editor !== 'unknown') {\n\t\t\t\tconst shouldApplyEditorPreset = await prompts.confirm(\n\t\t\t\t\t`Detected ${formatEditor(editorDetection.editor)}. Add workspace recommendations for ${formatEditor(editorDetection.editor)}?`,\n\t\t\t\t\ttrue,\n\t\t\t\t)\n\t\t\t\tif (shouldApplyEditorPreset) {\n\t\t\t\t\tconst appliedPreset = await applyEditorWorkspacePreset({\n\t\t\t\t\t\ttargetDir,\n\t\t\t\t\t\teditor: editorDetection.editor,\n\t\t\t\t\t})\n\t\t\t\t\tif (appliedPreset.applied) {\n\t\t\t\t\t\tlogger.step(\n\t\t\t\t\t\t\t`Added editor recommendations at ${relativeToTarget(targetDir, appliedPreset.filePath)}`,\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\tif (selection.db === 'postgres' && isSyncTemplate(template)) {\n\t\t\t\tlogger.info(\n\t\t\t\t\t`Applied PostgreSQL sync preset (${formatDbProviderForLog(selection.dbProvider)}). Update DATABASE_URL in .env.example before running the sync server.`,\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (gitContext.hasRepository) {\n\t\t\t\tlogger.step(\n\t\t\t\t\t`Detected existing git repository at ${gitContext.repositoryRoot}. Skipping git initialization.`,\n\t\t\t\t)\n\t\t\t}\n\t\t\tlogger.success('Project scaffolded')\n\n\t\t\tif (shouldSavePreferences(preferenceFlags)) {\n\t\t\t\tsaveResolvedPreferences(preferenceStore, {\n\t\t\t\t\tframework: selection.framework,\n\t\t\t\t\tauth: selection.auth,\n\t\t\t\t\tdb: selection.db,\n\t\t\t\t\tdbProvider: selection.dbProvider,\n\t\t\t\t\ttailwind: selection.tailwind,\n\t\t\t\t\tsync: selection.sync,\n\t\t\t\t\tpackageManager: pm,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// Install dependencies\n\t\t\tif (!args['skip-install']) {\n\t\t\t\tlogger.step('Installing dependencies...')\n\t\t\t\ttry {\n\t\t\t\t\texecSync(getInstallCommand(pm), { cwd: targetDir, stdio: 'inherit' })\n\t\t\t\t\tlogger.success('Dependencies installed')\n\t\t\t\t} catch {\n\t\t\t\t\tlogger.warn('Failed to install dependencies. Run install manually.')\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Print next steps\n\t\t\tlogger.blank()\n\t\t\tlogger.info('Done! Next steps:')\n\t\t\tlogger.blank()\n\t\t\tlogger.step(` cd ${targetDir}`)\n\t\t\tlogger.step(` ${getRunDevCommand(pm)}`)\n\t\t\tlogger.blank()\n\t\t\tif (!useDefaults) {\n\t\t\t\tprompts.outro('Project ready. Happy building with Kora!')\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (error instanceof PromptCancelledError) {\n\t\t\t\tprocess.exitCode = 1\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (error instanceof Error && error.message.startsWith('Invalid --')) {\n\t\t\t\tlogger.error(error.message)\n\t\t\t\tif (!args.yes) {\n\t\t\t\t\tprompts.outro('Project creation aborted.')\n\t\t\t\t}\n\t\t\t\tprocess.exitCode = 1\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthrow error\n\t\t}\n\t},\n})\n\nfunction isValidTemplate(value: string): value is TemplateName {\n\treturn (TEMPLATES as readonly string[]).includes(value)\n}\n\nfunction isValidPackageManager(value: string): value is PackageManager {\n\treturn (PACKAGE_MANAGERS as readonly string[]).includes(value)\n}\n\nfunction isSyncTemplate(template: TemplateName): boolean {\n\treturn template === 'react-sync' || template === 'react-tailwind-sync'\n}\n\nfunction formatDbProviderForLog(dbProvider: string): string {\n\tswitch (dbProvider) {\n\t\tcase 'supabase':\n\t\t\treturn 'Supabase'\n\t\tcase 'neon':\n\t\t\treturn 'Neon'\n\t\tcase 'railway':\n\t\t\treturn 'Railway'\n\t\tcase 'vercel-postgres':\n\t\t\treturn 'Vercel Postgres'\n\t\tcase 'custom':\n\t\t\treturn 'Custom'\n\t\tcase 'local':\n\t\t\treturn 'Local Postgres'\n\t\tcase 'none':\n\t\t\treturn 'PostgreSQL'\n\t\tdefault:\n\t\t\treturn dbProvider\n\t}\n}\n\nfunction formatEditor(editor: string): string {\n\tswitch (editor) {\n\t\tcase 'vscode':\n\t\t\treturn 'VS Code'\n\t\tcase 'cursor':\n\t\t\treturn 'Cursor'\n\t\tcase 'windsurf':\n\t\t\treturn 'Windsurf'\n\t\tcase 'zed':\n\t\t\treturn 'Zed'\n\t\tdefault:\n\t\t\treturn editor\n\t}\n}\n\nfunction formatMonorepoKind(kind: string): string {\n\tswitch (kind) {\n\t\tcase 'pnpm-workspace':\n\t\t\treturn 'pnpm workspace'\n\t\tcase 'npm-workspaces':\n\t\t\treturn 'npm workspace'\n\t\tcase 'turborepo':\n\t\t\treturn 'Turborepo'\n\t\tdefault:\n\t\t\treturn 'monorepo'\n\t}\n}\n\nfunction relativeToTarget(targetDir: string, filePath: string | null): string {\n\tif (filePath === null) return '.'\n\tconst normalizedTarget = targetDir.endsWith('/') ? targetDir : `${targetDir}/`\n\tif (filePath.startsWith(normalizedTarget)) {\n\t\treturn filePath.slice(normalizedTarget.length)\n\t}\n\tif (filePath === targetDir) {\n\t\treturn '.'\n\t}\n\treturn filePath\n}\n\n/**\n * Reads the version from @korajs/cli's own package.json and derives a\n * compatible version range for all @korajs packages.\n *\n * The CLI may be a patch ahead of other packages (e.g. CLI-only fixes),\n * so we use the major.minor range (^major.minor.0) which matches all\n * packages in the same release series.\n */\nfunction resolveKoraVersion(): string {\n\ttry {\n\t\tlet dir = dirname(fileURLToPath(import.meta.url))\n\t\tfor (let i = 0; i < 5; i++) {\n\t\t\tconst pkgPath = resolve(dir, 'package.json')\n\t\t\tif (existsSync(pkgPath)) {\n\t\t\t\tconst pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')) as { name?: string; version: string }\n\t\t\t\tif (pkg.name === '@korajs/cli') {\n\t\t\t\t\tif (pkg.version === '0.0.0') return 'latest'\n\t\t\t\t\t// Use ^major.minor.0 so all packages in the series match\n\t\t\t\t\tconst parts = pkg.version.split('.')\n\t\t\t\t\treturn `^${parts[0]}.${parts[1]}.0`\n\t\t\t\t}\n\t\t\t}\n\t\t\tdir = dirname(dir)\n\t\t}\n\t\treturn 'latest'\n\t} catch {\n\t\treturn 'latest'\n\t}\n}\n","import { KoraError } from '@korajs/core'\n\n/**\n * Base error class for all CLI errors.\n */\nexport class CliError extends KoraError {\n\tconstructor(message: string, context?: Record<string, unknown>) {\n\t\tsuper(message, 'CLI_ERROR', context)\n\t\tthis.name = 'CliError'\n\t}\n}\n\n/**\n * Thrown when the target project directory already exists.\n */\nexport class ProjectExistsError extends KoraError {\n\tconstructor(public readonly directory: string) {\n\t\tsuper(\n\t\t\t`Directory \"${directory}\" already exists. Choose a different name or remove the existing directory.`,\n\t\t\t'PROJECT_EXISTS',\n\t\t\t{ directory },\n\t\t)\n\t\tthis.name = 'ProjectExistsError'\n\t}\n}\n\n/**\n * Thrown when a schema file cannot be found in the project.\n */\nexport class SchemaNotFoundError extends KoraError {\n\tconstructor(public readonly searchedPaths: string[]) {\n\t\tsuper(\n\t\t\t`Could not find a schema file. Searched: ${searchedPaths.join(', ')}. Create a schema file using defineSchema() from @korajs/core.`,\n\t\t\t'SCHEMA_NOT_FOUND',\n\t\t\t{ searchedPaths },\n\t\t)\n\t\tthis.name = 'SchemaNotFoundError'\n\t}\n}\n\n/**\n * Thrown when a command is run outside a valid Kora project.\n */\nexport class InvalidProjectError extends KoraError {\n\tconstructor(public readonly directory: string) {\n\t\tsuper(\n\t\t\t`\"${directory}\" is not a valid Kora project. No package.json with a kora dependency found. Run this command from inside a Kora project.`,\n\t\t\t'INVALID_PROJECT',\n\t\t\t{ directory },\n\t\t)\n\t\tthis.name = 'InvalidProjectError'\n\t}\n}\n\n/**\n * Thrown when a required local dev server binary cannot be found.\n */\nexport class DevServerError extends KoraError {\n\tconstructor(\n\t\tpublic readonly binary: string,\n\t\tpublic readonly searchPath: string,\n\t) {\n\t\tsuper(\n\t\t\t`Could not find required binary \"${binary}\" at ${searchPath}. Install project dependencies and try again.`,\n\t\t\t'DEV_SERVER_ERROR',\n\t\t\t{ binary, searchPath },\n\t\t)\n\t\tthis.name = 'DevServerError'\n\t}\n}\n","import Conf from 'conf'\nimport type { AuthOption, DatabaseOption, DatabaseProviderOption, FrameworkOption } from '../commands/create/options'\nimport type { PackageManager } from '../types'\n\nexport interface CreatePreferences {\n\tframework: FrameworkOption\n\ttailwind: boolean\n\tsync: boolean\n\tdb: DatabaseOption\n\tdbProvider: DatabaseProviderOption\n\tauth: AuthOption\n\tpackageManager: PackageManager\n}\n\nconst DEFAULT_PREFERENCES: CreatePreferences = {\n\tframework: 'react',\n\ttailwind: true,\n\tsync: true,\n\tdb: 'sqlite',\n\tdbProvider: 'none',\n\tauth: 'none',\n\tpackageManager: 'pnpm',\n}\n\nconst PREFERENCES_KEY = 'create.defaults'\n\n/**\n * Preference store for scaffold-time defaults in `create-kora-app`.\n */\nexport class PreferenceStore {\n\tprivate readonly store: Conf<{ [PREFERENCES_KEY]?: CreatePreferences }>\n\n\tpublic constructor() {\n\t\tthis.store = new Conf<{ [PREFERENCES_KEY]?: CreatePreferences }>({\n\t\t\tprojectName: 'korajs-cli',\n\t\t})\n\t}\n\n\tpublic getCreatePreferences(): CreatePreferences | null {\n\t\treturn this.store.get(PREFERENCES_KEY) ?? null\n\t}\n\n\tpublic saveCreatePreferences(preferences: CreatePreferences): void {\n\t\tthis.store.set(PREFERENCES_KEY, preferences)\n\t}\n\n\tpublic clearCreatePreferences(): void {\n\t\tthis.store.delete(PREFERENCES_KEY)\n\t}\n}\n\n/**\n * Gets preferences from storage or returns defaults when not available.\n */\nexport function getCreatePreferencesOrDefault(store: PreferenceStore): CreatePreferences {\n\treturn store.getCreatePreferences() ?? DEFAULT_PREFERENCES\n}\n\nexport function getDefaultCreatePreferences(): CreatePreferences {\n\treturn { ...DEFAULT_PREFERENCES }\n}\n","import {\n\tcancel as clackCancel,\n\tconfirm as clackConfirm,\n\tintro as clackIntro,\n\tisCancel as clackIsCancel,\n\toutro as clackOutro,\n\tselect as clackSelect,\n\ttext as clackText,\n} from '@clack/prompts'\nimport { promptConfirm, promptSelect, promptText } from '../utils/prompt'\n\nexport interface SelectOption<T extends string> {\n\tlabel: string\n\tvalue: T\n\thint?: string\n\tdisabled?: boolean\n}\n\ntype ClackSelectOption<T extends string> = {\n\tvalue: T\n\tlabel?: string\n\thint?: string\n\tdisabled?: boolean\n}\n\nexport interface PromptClient {\n\ttext(message: string, defaultValue?: string): Promise<string>\n\tselect<T extends string>(message: string, options: readonly SelectOption<T>[]): Promise<T>\n\tconfirm(message: string, defaultValue?: boolean): Promise<boolean>\n\tintro(message: string): void\n\toutro(message: string): void\n}\n\nexport class PromptCancelledError extends Error {\n\tpublic constructor(message = 'Prompt cancelled by user') {\n\t\tsuper(message)\n\t\tthis.name = 'PromptCancelledError'\n\t}\n}\n\n/**\n * Prompt client backed by the current readline helpers.\n *\n * Phase 12 will introduce a richer prompt backend. This adapter keeps command\n * logic decoupled from the prompt implementation so we can migrate without\n * reshaping command behavior.\n */\nexport class ReadlinePromptClient implements PromptClient {\n\tpublic async text(message: string, defaultValue?: string): Promise<string> {\n\t\treturn promptText(message, defaultValue)\n\t}\n\n\tpublic async select<T extends string>(\n\t\tmessage: string,\n\t\toptions: readonly SelectOption<T>[],\n\t): Promise<T> {\n\t\treturn promptSelect(\n\t\t\tmessage,\n\t\t\toptions\n\t\t\t\t.filter((option) => option.disabled !== true)\n\t\t\t\t.map((option) => ({ label: option.label, value: option.value })),\n\t\t)\n\t}\n\n\tpublic async confirm(message: string, defaultValue = false): Promise<boolean> {\n\t\treturn promptConfirm(message, defaultValue)\n\t}\n\n\tpublic intro(message: string): void {\n\t\t// The readline backend does not provide intro/outro framing.\n\t\t// Keep no-op semantics for compatibility.\n\t\tvoid message\n\t}\n\n\tpublic outro(message: string): void {\n\t\t// The readline backend does not provide intro/outro framing.\n\t\t// Keep no-op semantics for compatibility.\n\t\tvoid message\n\t}\n}\n\n/**\n * Returns the default prompt client for interactive CLI flows.\n */\nexport function createPromptClient(): PromptClient {\n\tconst canUseInteractiveClack = typeof process !== 'undefined' && process.stdin.isTTY && process.stdout.isTTY\n\tif (canUseInteractiveClack) {\n\t\treturn new ClackPromptClient()\n\t}\n\treturn new ReadlinePromptClient()\n}\n\n/**\n * Prompt client backed by @clack/prompts for richer interactive UX.\n * Falls back to readline in non-interactive contexts.\n */\nexport class ClackPromptClient implements PromptClient {\n\tpublic async text(message: string, defaultValue?: string): Promise<string> {\n\t\tconst result = await clackText({\n\t\t\tmessage,\n\t\t\tplaceholder: defaultValue,\n\t\t\tdefaultValue,\n\t\t})\n\t\tif (clackIsCancel(result)) {\n\t\t\tclackCancel('Operation cancelled.')\n\t\t\tthrow new PromptCancelledError()\n\t\t}\n\t\tconst value = result.trim()\n\t\tif (value.length > 0) return value\n\t\treturn defaultValue ?? ''\n\t}\n\n\tpublic async select<T extends string>(\n\t\tmessage: string,\n\t\toptions: readonly SelectOption<T>[],\n\t): Promise<T> {\n\t\tconst mappedOptions: ClackSelectOption<T>[] = options.map((option) => ({\n\t\t\tlabel: option.label,\n\t\t\tvalue: option.value,\n\t\t\thint: option.hint,\n\t\t\tdisabled: option.disabled,\n\t\t}))\n\t\tconst result = await clackSelect({\n\t\t\tmessage,\n\t\t\toptions: mappedOptions as unknown as Parameters<typeof clackSelect>[0]['options'],\n\t\t})\n\t\tif (clackIsCancel(result)) {\n\t\t\tclackCancel('Operation cancelled.')\n\t\t\tthrow new PromptCancelledError()\n\t\t}\n\t\treturn result as T\n\t}\n\n\tpublic async confirm(message: string, defaultValue = false): Promise<boolean> {\n\t\tconst result = await clackConfirm({\n\t\t\tmessage,\n\t\t\tinitialValue: defaultValue,\n\t\t})\n\t\tif (clackIsCancel(result)) {\n\t\t\tclackCancel('Operation cancelled.')\n\t\t\tthrow new PromptCancelledError()\n\t\t}\n\t\treturn result\n\t}\n\n\tpublic intro(message: string): void {\n\t\tclackIntro(message)\n\t}\n\n\tpublic outro(message: string): void {\n\t\tclackOutro(message)\n\t}\n}\n","import { type Interface as ReadlineInterface, createInterface } from 'node:readline'\n\nexport interface PromptOptions {\n\t/** Input stream (defaults to process.stdin) */\n\tinput?: NodeJS.ReadableStream\n\t/** Output stream (defaults to process.stdout) */\n\toutput?: NodeJS.WritableStream\n}\n\n/**\n * Prompts the user for text input.\n *\n * @param message - The prompt message to display\n * @param defaultValue - Optional default value shown in brackets\n * @param options - Optional input/output streams for testing\n */\nexport function promptText(\n\tmessage: string,\n\tdefaultValue?: string,\n\toptions?: PromptOptions,\n): Promise<string> {\n\treturn new Promise((resolve) => {\n\t\tconst rl = createReadline(options)\n\t\tconst suffix = defaultValue !== undefined ? ` (${defaultValue})` : ''\n\t\trl.question(` ? ${message}${suffix}: `, (answer) => {\n\t\t\trl.close()\n\t\t\tconst trimmed = answer.trim()\n\t\t\tresolve(trimmed || defaultValue || '')\n\t\t})\n\t})\n}\n\n/**\n * Prompts the user to select from a numbered list of options.\n *\n * @param message - The prompt message to display\n * @param choices - Array of { label, value } options\n * @param options - Optional input/output streams for testing\n */\nexport function promptSelect<T extends string>(\n\tmessage: string,\n\tchoices: readonly { label: string; value: T }[],\n\toptions?: PromptOptions,\n): Promise<T> {\n\treturn new Promise((resolve) => {\n\t\tconst rl = createReadline(options)\n\t\tconst out = options?.output ?? process.stdout\n\n\t\tout.write(` ? ${message}\\n`)\n\t\tfor (let i = 0; i < choices.length; i++) {\n\t\t\tconst choice = choices[i]\n\t\t\tif (choice) {\n\t\t\t\tout.write(` ${i + 1}) ${choice.label}\\n`)\n\t\t\t}\n\t\t}\n\n\t\tconst ask = (): void => {\n\t\t\trl.question(' > ', (answer) => {\n\t\t\t\tconst index = Number.parseInt(answer.trim(), 10) - 1\n\t\t\t\tconst selected = choices[index]\n\t\t\t\tif (selected) {\n\t\t\t\t\trl.close()\n\t\t\t\t\tresolve(selected.value)\n\t\t\t\t} else {\n\t\t\t\t\tout.write(` Please enter a number between 1 and ${choices.length}\\n`)\n\t\t\t\t\task()\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\n\t\task()\n\t})\n}\n\n/**\n * Prompts the user with a yes/no confirmation.\n *\n * @param message - The prompt message to display\n * @param defaultValue - Default when input is empty (true => yes)\n * @param options - Optional input/output streams for testing\n */\nexport function promptConfirm(\n\tmessage: string,\n\tdefaultValue = false,\n\toptions?: PromptOptions,\n): Promise<boolean> {\n\treturn new Promise((resolve) => {\n\t\tconst rl = createReadline(options)\n\t\tconst suffix = defaultValue ? 'Y/n' : 'y/N'\n\n\t\tconst ask = (): void => {\n\t\t\trl.question(` ? ${message} (${suffix}): `, (answer) => {\n\t\t\t\tconst normalized = answer.trim().toLowerCase()\n\t\t\t\tif (normalized.length === 0) {\n\t\t\t\t\trl.close()\n\t\t\t\t\tresolve(defaultValue)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif (normalized === 'y' || normalized === 'yes') {\n\t\t\t\t\trl.close()\n\t\t\t\t\tresolve(true)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif (normalized === 'n' || normalized === 'no') {\n\t\t\t\t\trl.close()\n\t\t\t\t\tresolve(false)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t(options?.output ?? process.stdout).write(' Please answer with y or n\\n')\n\t\t\t\task()\n\t\t\t})\n\t\t}\n\n\t\task()\n\t})\n}\n\nfunction createReadline(options?: PromptOptions): ReadlineInterface {\n\treturn createInterface({\n\t\tinput: options?.input ?? process.stdin,\n\t\toutput: options?.output ?? process.stdout,\n\t})\n}\n","/** Supported package managers */\nexport const PACKAGE_MANAGERS = ['pnpm', 'npm', 'yarn', 'bun'] as const\nexport type PackageManager = (typeof PACKAGE_MANAGERS)[number]\n\n/** Available project templates */\nexport const TEMPLATES = [\n\t'react-tailwind-sync',\n\t'react-tailwind',\n\t'react-sync',\n\t'react-basic',\n] as const\nexport type TemplateName = (typeof TEMPLATES)[number]\n\n/** Metadata for a project template */\nexport interface TemplateInfo {\n\tname: TemplateName\n\tlabel: string\n\tdescription: string\n}\n\n/** Available templates with their descriptions */\nexport const TEMPLATE_INFO: readonly TemplateInfo[] = [\n\t{\n\t\tname: 'react-tailwind-sync',\n\t\tlabel: 'React + Tailwind (with sync)',\n\t\tdescription: 'Polished dark-themed app with Tailwind CSS and sync server (Recommended)',\n\t},\n\t{\n\t\tname: 'react-tailwind',\n\t\tlabel: 'React + Tailwind (local-only)',\n\t\tdescription: 'Polished dark-themed app with Tailwind CSS — no sync server',\n\t},\n\t{\n\t\tname: 'react-sync',\n\t\tlabel: 'React + CSS (with sync)',\n\t\tdescription: 'Clean CSS app with sync server included',\n\t},\n\t{\n\t\tname: 'react-basic',\n\t\tlabel: 'React + CSS (local-only)',\n\t\tdescription: 'Clean CSS app — no sync server',\n\t},\n] as const\n\n/** Variables available for template substitution */\nexport interface TemplateContext {\n\tprojectName: string\n\tpackageManager: PackageManager\n\tkoraVersion: string\n\tdbProvider?: string\n}\n","import { access, readFile } from 'node:fs/promises'\nimport { dirname, join, resolve } from 'node:path'\n\n/** Checks if a directory exists at the given path */\nexport async function directoryExists(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\n/**\n * Walks up the directory tree from startDir looking for a package.json\n * that contains a kora or @korajs/* dependency.\n *\n * @param startDir - Directory to start searching from (defaults to cwd)\n * @returns Absolute path to the project root, or null if not found\n */\nexport async function findProjectRoot(startDir?: string): Promise<string | null> {\n\tlet current = resolve(startDir ?? process.cwd())\n\n\t// Walk up until the filesystem root (where dirname(x) === x)\n\tfor (;;) {\n\t\tconst pkgPath = join(current, 'package.json')\n\t\ttry {\n\t\t\tconst content = await readFile(pkgPath, 'utf-8')\n\t\t\tconst pkg: unknown = JSON.parse(content)\n\t\t\tif (isKoraProject(pkg)) {\n\t\t\t\treturn current\n\t\t\t}\n\t\t} catch {\n\t\t\t// No package.json at this level, keep walking up\n\t\t}\n\t\tconst parent = dirname(current)\n\t\tif (parent === current) break\n\t\tcurrent = parent\n\t}\n\n\treturn null\n}\n\n/**\n * Searches for a schema file in common locations within a project.\n *\n * @param projectRoot - The project root directory\n * @returns Absolute path to the schema file, or null if not found\n */\nexport async function findSchemaFile(projectRoot: string): Promise<string | null> {\n\tconst candidates = [\n\t\tjoin(projectRoot, 'src', 'schema.ts'),\n\t\tjoin(projectRoot, 'schema.ts'),\n\t\tjoin(projectRoot, 'src', 'schema.js'),\n\t\tjoin(projectRoot, 'schema.js'),\n\t]\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// Not found, try next\n\t\t}\n\t}\n\n\treturn null\n}\n\n/**\n * Resolves a binary from a project's local node_modules/.bin directory.\n * On Windows, npm creates .cmd shims instead of extensionless files.\n *\n * @param projectRoot - The project root directory\n * @param binaryName - Binary filename (for example: vite, tsx, kora)\n * @returns Absolute path to the binary, or null if not found\n */\nexport async function resolveProjectBinary(\n\tprojectRoot: string,\n\tbinaryName: string,\n): Promise<string | null> {\n\tconst binDir = join(projectRoot, 'node_modules', '.bin')\n\t// On Windows, try .cmd first (npm/pnpm create .cmd shims)\n\tconst candidates =\n\t\tprocess.platform === 'win32'\n\t\t\t? [join(binDir, `${binaryName}.cmd`), join(binDir, binaryName)]\n\t\t\t: [join(binDir, binaryName)]\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\treturn null\n}\n\n/**\n * Checks whether the `tsx` package is installed in the project's node_modules.\n * Used to determine if we can use `--import tsx` with process.execPath.\n */\nexport async function hasTsxInstalled(projectRoot: string): Promise<boolean> {\n\ttry {\n\t\tawait access(join(projectRoot, 'node_modules', 'tsx', 'package.json'))\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Resolves the JS entry point for a package binary.\n * Reads the package.json bin field to find the actual JS file,\n * avoiding .cmd shims and shell:true on Windows.\n *\n * @returns Absolute path to the JS entry point, or null if not found\n */\nexport async function resolveProjectBinaryEntryPoint(\n\tprojectRoot: string,\n\tpackageName: string,\n\tbinaryName: string,\n): Promise<string | null> {\n\tconst pkgJsonPath = join(projectRoot, 'node_modules', packageName, 'package.json')\n\ttry {\n\t\tconst content = await readFile(pkgJsonPath, 'utf-8')\n\t\tconst pkg = JSON.parse(content) as { bin?: string | Record<string, string> }\n\t\tlet binPath: string | undefined\n\t\tif (typeof pkg.bin === 'string') {\n\t\t\tbinPath = pkg.bin\n\t\t} else if (typeof pkg.bin === 'object' && pkg.bin !== null) {\n\t\t\tbinPath = pkg.bin[binaryName]\n\t\t}\n\t\tif (!binPath) return null\n\t\tconst fullPath = join(projectRoot, 'node_modules', packageName, binPath)\n\t\tawait access(fullPath)\n\t\treturn fullPath\n\t} catch {\n\t\treturn null\n\t}\n}\n\nfunction isKoraProject(pkg: unknown): boolean {\n\tif (typeof pkg !== 'object' || pkg === null) return false\n\tconst record = pkg as Record<string, unknown>\n\treturn hasKoraDep(record.dependencies) || hasKoraDep(record.devDependencies)\n}\n\nfunction hasKoraDep(deps: unknown): boolean {\n\tif (typeof deps !== 'object' || deps === null) return false\n\treturn Object.keys(deps).some((key) => key === 'kora' || key.startsWith('@korajs/'))\n}\n","/** ANSI escape codes for terminal colors */\nconst RESET = '\\x1b[0m'\nconst BOLD = '\\x1b[1m'\nconst DIM = '\\x1b[2m'\nconst GREEN = '\\x1b[32m'\nconst YELLOW = '\\x1b[33m'\nconst RED = '\\x1b[31m'\nconst CYAN = '\\x1b[36m'\n\nexport interface LoggerOptions {\n\t/** Disable ANSI colors */\n\tnoColor?: boolean\n}\n\nexport interface Logger {\n\tinfo(message: string): void\n\tsuccess(message: string): void\n\twarn(message: string): void\n\terror(message: string): void\n\tstep(message: string): void\n\tblank(): void\n\tbanner(): void\n}\n\n/**\n * Creates a logger with optional ANSI color support.\n * Respects the NO_COLOR environment variable and TTY detection.\n */\nexport function createLogger(options?: LoggerOptions): Logger {\n\tconst colorDisabled =\n\t\toptions?.noColor === true || process.env.NO_COLOR !== undefined || !process.stdout.isTTY\n\n\tfunction color(code: string, text: string): string {\n\t\treturn colorDisabled ? text : `${code}${text}${RESET}`\n\t}\n\n\treturn {\n\t\tinfo(message: string): void {\n\t\t\tconsole.log(color(CYAN, message))\n\t\t},\n\t\tsuccess(message: string): void {\n\t\t\tconsole.log(color(GREEN, ` ✓ ${message}`))\n\t\t},\n\t\twarn(message: string): void {\n\t\t\tconsole.warn(color(YELLOW, ` ⚠ ${message}`))\n\t\t},\n\t\terror(message: string): void {\n\t\t\tconsole.error(color(RED, ` ✗ ${message}`))\n\t\t},\n\t\tstep(message: string): void {\n\t\t\tconsole.log(color(DIM, ` ${message}`))\n\t\t},\n\t\tblank(): void {\n\t\t\tconsole.log()\n\t\t},\n\t\tbanner(): void {\n\t\t\tconsole.log()\n\t\t\tconsole.log(\n\t\t\t\tcolor(BOLD + CYAN, ' Kora.js') + color(DIM, ' — Offline-first application framework'),\n\t\t\t)\n\t\t\tconsole.log()\n\t\t},\n\t}\n}\n","import { execSync } from 'node:child_process'\nimport type { PackageManager } from '../types'\n\n/**\n * Detects the package manager used to invoke the current process\n * by reading the npm_config_user_agent environment variable.\n * Falls back to 'npm' if detection fails.\n */\nexport function detectPackageManager(): PackageManager {\n\tconst userAgent = process.env.npm_config_user_agent\n\tif (!userAgent) return 'npm'\n\n\tif (userAgent.startsWith('pnpm/')) return 'pnpm'\n\tif (userAgent.startsWith('yarn/')) return 'yarn'\n\tif (userAgent.startsWith('bun/')) return 'bun'\n\treturn 'npm'\n}\n\n/** Returns the install command for the given package manager */\nexport function getInstallCommand(pm: PackageManager): string {\n\treturn pm === 'yarn' ? 'yarn' : `${pm} install`\n}\n\n/** Returns the dev server run command for the given package manager */\nexport function getRunDevCommand(pm: PackageManager): string {\n\tif (pm === 'npm') return 'npm run dev'\n\treturn `${pm} dev`\n}\n\n/** Checks if a package manager is available on PATH */\nexport function isPackageManagerAvailable(pm: PackageManager): boolean {\n\ttry {\n\t\texecSync(`${pm} --version`, { stdio: 'ignore' })\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n","import { access, mkdir, readFile, stat, writeFile } from 'node:fs/promises'\nimport { dirname, join, resolve } from 'node:path'\n\nexport type SupportedEditor = 'vscode' | 'cursor' | 'windsurf' | 'zed' | 'unknown'\n\nexport interface EditorDetectionResult {\n\teditor: SupportedEditor\n\tsource: 'env' | 'none'\n}\n\nexport interface GitContextResult {\n\thasRepository: boolean\n\trepositoryRoot: string | null\n}\n\nexport interface MonorepoContextResult {\n\tisMonorepo: boolean\n\troot: string | null\n\tkind: 'pnpm-workspace' | 'npm-workspaces' | 'turborepo' | 'none'\n}\n\nexport interface EditorWorkspacePresetResult {\n\tapplied: boolean\n\tfilePath: string | null\n}\n\n/**\n * Detects which editor is most likely being used by inspecting environment\n * variables commonly set by integrated terminals.\n */\nexport function detectEditorFromEnvironment(\n\tenv: Record<string, string | undefined> = process.env,\n): EditorDetectionResult {\n\tconst termProgram = String(env.TERM_PROGRAM ?? '').toLowerCase()\n\tconst editorValue = `${String(env.EDITOR ?? '')} ${String(env.VISUAL ?? '')}`.toLowerCase()\n\n\tif (\n\t\ttermProgram.includes('cursor') ||\n\t\tenv.CURSOR_TRACE_ID !== undefined ||\n\t\tenv.CURSOR_SESSION_ID !== undefined ||\n\t\teditorValue.includes('cursor')\n\t) {\n\t\treturn { editor: 'cursor', source: 'env' }\n\t}\n\tif (\n\t\ttermProgram.includes('windsurf') ||\n\t\tenv.WINDSURF_SESSION_ID !== undefined ||\n\t\teditorValue.includes('windsurf')\n\t) {\n\t\treturn { editor: 'windsurf', source: 'env' }\n\t}\n\tif (\n\t\ttermProgram.includes('vscode') ||\n\t\tenv.VSCODE_GIT_IPC_HANDLE !== undefined ||\n\t\tenv.VSCODE_IPC_HOOK !== undefined ||\n\t\tenv.VSCODE_PID !== undefined ||\n\t\teditorValue.includes('code')\n\t) {\n\t\treturn { editor: 'vscode', source: 'env' }\n\t}\n\tif (termProgram.includes('zed') || env.ZED_TERM !== undefined || editorValue.includes('zed')) {\n\t\treturn { editor: 'zed', source: 'env' }\n\t}\n\treturn { editor: 'unknown', source: 'none' }\n}\n\n/**\n * Finds the nearest ancestor directory that contains a `.git` entry.\n */\nexport async function detectGitContext(startDir: string): Promise<GitContextResult> {\n\tconst root = await findNearestAncestorWithEntry(startDir, '.git')\n\treturn {\n\t\thasRepository: root !== null,\n\t\trepositoryRoot: root,\n\t}\n}\n\n/**\n * Detects whether the given path is inside a monorepo workspace.\n * Detection currently supports pnpm workspaces, npm workspaces, and Turborepo.\n */\nexport async function detectMonorepoContext(startDir: string): Promise<MonorepoContextResult> {\n\tlet current = resolve(startDir)\n\tfor (;;) {\n\t\tif (await fileExists(join(current, 'pnpm-workspace.yaml'))) {\n\t\t\treturn { isMonorepo: true, root: current, kind: 'pnpm-workspace' }\n\t\t}\n\n\t\tif (await fileExists(join(current, 'turbo.json'))) {\n\t\t\treturn { isMonorepo: true, root: current, kind: 'turborepo' }\n\t\t}\n\n\t\tconst packageJsonPath = join(current, 'package.json')\n\t\tif (await fileExists(packageJsonPath)) {\n\t\t\ttry {\n\t\t\t\tconst packageJsonRaw = await readFile(packageJsonPath, 'utf-8')\n\t\t\t\tconst parsed = JSON.parse(packageJsonRaw) as { workspaces?: unknown }\n\t\t\t\tif (Array.isArray(parsed.workspaces) || isNpmWorkspaceObject(parsed.workspaces)) {\n\t\t\t\t\treturn { isMonorepo: true, root: current, kind: 'npm-workspaces' }\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Ignore malformed package.json and keep walking upward.\n\t\t\t}\n\t\t}\n\n\t\tconst parent = dirname(current)\n\t\tif (parent === current) {\n\t\t\treturn { isMonorepo: false, root: null, kind: 'none' }\n\t\t}\n\t\tcurrent = parent\n\t}\n}\n\n/**\n * Applies editor-specific workspace configuration. For VS Code-compatible\n * editors this creates or updates `.vscode/extensions.json` recommendations.\n */\nexport async function applyEditorWorkspacePreset(params: {\n\ttargetDir: string\n\teditor: SupportedEditor\n}): Promise<EditorWorkspacePresetResult> {\n\tconst { targetDir, editor } = params\n\tif (editor !== 'vscode' && editor !== 'cursor' && editor !== 'windsurf') {\n\t\treturn { applied: false, filePath: null }\n\t}\n\n\tconst vscodeDir = join(targetDir, '.vscode')\n\tconst extensionsPath = join(vscodeDir, 'extensions.json')\n\tawait mkdir(vscodeDir, { recursive: true })\n\n\tconst recommendations = ['korajs.kora-devtools']\n\tconst existing = await readJsonObject(extensionsPath)\n\tconst existingRecommendations = Array.isArray(existing?.recommendations)\n\t\t? existing.recommendations.filter((item): item is string => typeof item === 'string')\n\t\t: []\n\tconst mergedRecommendations = dedupeStrings([...existingRecommendations, ...recommendations])\n\n\tconst next = {\n\t\trecommendations: mergedRecommendations,\n\t}\n\tawait writeFile(extensionsPath, `${JSON.stringify(next, null, 2)}\\n`, 'utf-8')\n\treturn { applied: true, filePath: extensionsPath }\n}\n\n/**\n * Returns a workspace-aware target directory under the detected monorepo root.\n * This keeps generated apps in conventional package folders.\n */\nexport function resolveMonorepoTargetDirectory(monorepoRoot: string, projectName: string): string {\n\treturn join(monorepoRoot, 'packages', projectName)\n}\n\nfunction dedupeStrings(values: readonly string[]): string[] {\n\treturn Array.from(new Set(values))\n}\n\nasync function readJsonObject(path: string): Promise<Record<string, unknown> | null> {\n\ttry {\n\t\tconst content = await readFile(path, 'utf-8')\n\t\tconst parsed: unknown = JSON.parse(content)\n\t\tif (typeof parsed === 'object' && parsed !== null) {\n\t\t\treturn parsed as Record<string, unknown>\n\t\t}\n\t\treturn null\n\t} catch {\n\t\treturn null\n\t}\n}\n\nfunction isNpmWorkspaceObject(value: unknown): value is { packages: unknown } {\n\tif (typeof value !== 'object' || value === null) return false\n\tconst record = value as Record<string, unknown>\n\treturn Array.isArray(record.packages)\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\nasync function findNearestAncestorWithEntry(\n\tstartDir: string,\n\tentryName: string,\n): Promise<string | null> {\n\tlet current = resolve(startDir)\n\tfor (;;) {\n\t\tconst candidate = join(current, entryName)\n\t\ttry {\n\t\t\tawait stat(candidate)\n\t\t\treturn current\n\t\t} catch {\n\t\t\t// keep walking upward\n\t\t}\n\t\tconst parent = dirname(current)\n\t\tif (parent === current) {\n\t\t\treturn null\n\t\t}\n\t\tcurrent = parent\n\t}\n}\n","import type { TemplateName } from '../../types'\n\nexport type FrameworkOption = 'react' | 'vue' | 'svelte' | 'solid'\nexport type AuthOption = 'none' | 'email-password' | 'oauth'\nexport type DatabaseOption = 'none' | 'sqlite' | 'postgres'\nexport type DatabaseProviderOption =\n\t| 'none'\n\t| 'local'\n\t| 'supabase'\n\t| 'neon'\n\t| 'railway'\n\t| 'vercel-postgres'\n\t| 'custom'\n\nexport interface TemplateSelectionInput {\n\ttailwind: boolean\n\tsync: boolean\n\tdb: DatabaseOption\n}\n\n/**\n * Converts high-level scaffold selections into the currently supported\n * concrete template names.\n */\nexport function determineTemplateFromSelections(input: TemplateSelectionInput): TemplateName {\n\tconst shouldSync = input.sync && input.db !== 'none'\n\tif (input.tailwind && shouldSync) return 'react-tailwind-sync'\n\tif (input.tailwind && !shouldSync) return 'react-tailwind'\n\tif (!input.tailwind && shouldSync) return 'react-sync'\n\treturn 'react-basic'\n}\n\nexport function isFrameworkValue(value: string): value is FrameworkOption {\n\treturn value === 'react' || value === 'vue' || value === 'svelte' || value === 'solid'\n}\n\nexport function isAuthValue(value: string): value is AuthOption {\n\treturn value === 'none' || value === 'email-password' || value === 'oauth'\n}\n\nexport function isDatabaseValue(value: string): value is DatabaseOption {\n\treturn value === 'none' || value === 'sqlite' || value === 'postgres'\n}\n\nexport function isDatabaseProviderValue(value: string): value is DatabaseProviderOption {\n\treturn (\n\t\tvalue === 'none' ||\n\t\tvalue === 'local' ||\n\t\tvalue === 'supabase' ||\n\t\tvalue === 'neon' ||\n\t\tvalue === 'railway' ||\n\t\tvalue === 'vercel-postgres' ||\n\t\tvalue === 'custom'\n\t)\n}\n","import type { PromptClient } from '../../prompts/prompt-client'\nimport {\n\tgetDefaultCreatePreferences,\n\tgetCreatePreferencesOrDefault,\n\ttype CreatePreferences,\n\ttype PreferenceStore,\n} from '../../prompts/preferences'\nimport {\n\tdetermineTemplateFromSelections,\n\tisAuthValue,\n\tisDatabaseProviderValue,\n\tisDatabaseValue,\n\tisFrameworkValue,\n\ttype AuthOption,\n\ttype DatabaseOption,\n\ttype DatabaseProviderOption,\n\ttype FrameworkOption,\n} from './options'\n\nexport interface CreateFlags {\n\tframework?: string\n\tauth?: string\n\tdb?: string\n\tdbProvider?: string\n\ttailwind?: boolean\n\tsync?: boolean\n\tuseDefaults: boolean\n}\n\nexport interface PreferenceResolutionResult {\n\tframework: FrameworkOption\n\tauth: AuthOption\n\tdb: DatabaseOption\n\tdbProvider: DatabaseProviderOption\n\ttailwind: boolean\n\tsync: boolean\n\ttemplate: ReturnType<typeof determineTemplateFromSelections>\n\tusedStoredPreferences: boolean\n}\n\n/**\n * Resolves scaffold options with precedence:\n * CLI flags > --yes defaults > stored preferences > interactive prompts.\n */\nexport async function resolveCreatePreferencesFlow(params: {\n\tflags: CreateFlags\n\tprompts: PromptClient\n\tstore: PreferenceStore\n}): Promise<PreferenceResolutionResult> {\n\tconst { flags, prompts, store } = params\n\tconst stored = store.getCreatePreferences()\n\tconst base = getCreatePreferencesOrDefault(store)\n\tconst hasExplicitFlags = hasExplicitPreferenceFlags(flags)\n\tconst canOfferStored =\n\t\t!flags.useDefaults && !hasExplicitFlags && stored !== null && promptSupportsRichOptions()\n\n\tlet effective: CreatePreferences = { ...base }\n\tlet usedStoredPreferences = false\n\n\tif (flags.useDefaults) {\n\t\teffective = getDefaultCreatePreferences()\n\t} else if (canOfferStored && stored !== null) {\n\t\tconst reuseStored = await prompts.select('Welcome back! Choose setup mode:', [\n\t\t\t{ label: formatStoredPreferenceLabel(stored), value: 'reuse' },\n\t\t\t{ label: 'Customize', value: 'customize' },\n\t\t])\n\t\tif (reuseStored === 'reuse') {\n\t\t\teffective = { ...stored }\n\t\t\tusedStoredPreferences = true\n\t\t}\n\t}\n\n\tif (flags.framework !== undefined) {\n\t\tif (!isFrameworkValue(flags.framework)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid --framework value \"${flags.framework}\". Expected one of: react, vue, svelte, solid.`,\n\t\t\t)\n\t\t}\n\t\teffective.framework = flags.framework\n\t} else if (!flags.useDefaults && !usedStoredPreferences) {\n\t\teffective.framework = await prompts.select('UI framework:', [\n\t\t\t{ label: 'React', value: 'react' },\n\t\t\t{ label: 'Vue (coming soon)', value: 'vue', disabled: true },\n\t\t\t{ label: 'Svelte (coming soon)', value: 'svelte', disabled: true },\n\t\t\t{ label: 'Solid (coming soon)', value: 'solid', disabled: true },\n\t\t])\n\t}\n\n\tif (flags.auth !== undefined) {\n\t\tif (!isAuthValue(flags.auth)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid --auth value \"${flags.auth}\". Expected one of: none, email-password, oauth.`,\n\t\t\t)\n\t\t}\n\t\teffective.auth = flags.auth\n\t} else if (!flags.useDefaults && !usedStoredPreferences) {\n\t\teffective.auth = await prompts.select('Authentication:', [\n\t\t\t{ label: 'None', value: 'none' },\n\t\t\t{ label: 'Email + Password (coming soon)', value: 'email-password', disabled: true },\n\t\t\t{ label: 'OAuth (coming soon)', value: 'oauth', disabled: true },\n\t\t])\n\t}\n\n\tif (flags.tailwind !== undefined) {\n\t\teffective.tailwind = flags.tailwind\n\t} else if (!flags.useDefaults && !usedStoredPreferences) {\n\t\teffective.tailwind = await prompts.confirm('Use Tailwind CSS?', true)\n\t}\n\n\tif (flags.sync !== undefined) {\n\t\teffective.sync = flags.sync\n\t} else if (!flags.useDefaults && !usedStoredPreferences) {\n\t\teffective.sync = await prompts.confirm('Enable multi-device sync?', true)\n\t}\n\n\tif (flags.db !== undefined) {\n\t\tif (!isDatabaseValue(flags.db)) {\n\t\t\tthrow new Error(`Invalid --db value \"${flags.db}\". Expected one of: none, sqlite, postgres.`)\n\t\t}\n\t\teffective.db = flags.db\n\t} else if (!effective.sync) {\n\t\teffective.db = 'none'\n\t} else if (!flags.useDefaults && !usedStoredPreferences) {\n\t\teffective.db = await prompts.select('Server-side database:', [\n\t\t\t{ label: 'SQLite (zero-config)', value: 'sqlite' },\n\t\t\t{ label: 'PostgreSQL (production-scale)', value: 'postgres' },\n\t\t])\n\t}\n\n\tif (effective.db !== 'postgres') {\n\t\teffective.dbProvider = 'none'\n\t} else if (flags.dbProvider !== undefined) {\n\t\tif (!isDatabaseProviderValue(flags.dbProvider)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid --db-provider value \"${flags.dbProvider}\". Expected one of: none, local, supabase, neon, railway, vercel-postgres, custom.`,\n\t\t\t)\n\t\t}\n\t\teffective.dbProvider = flags.dbProvider\n\t} else if (!flags.useDefaults && !usedStoredPreferences) {\n\t\teffective.dbProvider = await prompts.select('Database provider:', [\n\t\t\t{ label: 'Local Postgres', value: 'local' },\n\t\t\t{ label: 'Supabase', value: 'supabase' },\n\t\t\t{ label: 'Neon', value: 'neon' },\n\t\t\t{ label: 'Railway', value: 'railway' },\n\t\t\t{ label: 'Vercel Postgres', value: 'vercel-postgres' },\n\t\t\t{ label: 'Custom connection string', value: 'custom' },\n\t\t])\n\t}\n\n\tconst template = determineTemplateFromSelections({\n\t\ttailwind: effective.tailwind,\n\t\tsync: effective.sync,\n\t\tdb: effective.db,\n\t})\n\n\treturn {\n\t\tframework: effective.framework,\n\t\tauth: effective.auth,\n\t\tdb: effective.db,\n\t\tdbProvider: effective.dbProvider,\n\t\ttailwind: effective.tailwind,\n\t\tsync: effective.sync,\n\t\ttemplate,\n\t\tusedStoredPreferences,\n\t}\n}\n\nexport function shouldSavePreferences(flags: CreateFlags): boolean {\n\treturn !flags.useDefaults\n}\n\nexport function saveResolvedPreferences(\n\tstore: PreferenceStore,\n\tresolution: Omit<PreferenceResolutionResult, 'template' | 'usedStoredPreferences'> & {\n\t\tpackageManager: CreatePreferences['packageManager']\n\t},\n): void {\n\tstore.saveCreatePreferences({\n\t\tframework: resolution.framework,\n\t\ttailwind: resolution.tailwind,\n\t\tsync: resolution.sync,\n\t\tdb: resolution.db,\n\t\tdbProvider: resolution.dbProvider,\n\t\tauth: resolution.auth,\n\t\tpackageManager: resolution.packageManager,\n\t})\n}\n\nfunction hasExplicitPreferenceFlags(flags: CreateFlags): boolean {\n\treturn (\n\t\tflags.framework !== undefined ||\n\t\tflags.auth !== undefined ||\n\t\tflags.db !== undefined ||\n\t\tflags.dbProvider !== undefined ||\n\t\tflags.tailwind !== undefined ||\n\t\tflags.sync !== undefined\n\t)\n}\n\nfunction promptSupportsRichOptions(): boolean {\n\treturn typeof process !== 'undefined' && process.stdin.isTTY && process.stdout.isTTY\n}\n\nfunction formatStoredPreferenceLabel(preferences: CreatePreferences): string {\n\tconst syncLabel = preferences.sync ? `sync/${preferences.db}` : 'local-only'\n\tconst styleLabel = preferences.tailwind ? 'tailwind' : 'css'\n\treturn `Use previous settings (${preferences.framework} + ${styleLabel} + ${syncLabel} + ${preferences.packageManager})`\n}\n","import validateNpmPackageName from 'validate-npm-package-name'\n\nexport interface ProjectNameValidationResult {\n\tvalid: boolean\n\tissues: readonly string[]\n}\n\n/**\n * Validates a project name for scaffolded package creation.\n *\n * The create command uses this validation before writing files so users get a\n * clear, early error if the name cannot be used as an npm package name.\n */\nexport function validateProjectName(name: string): ProjectNameValidationResult {\n\tconst trimmedName = name.trim()\n\tif (trimmedName.length === 0) {\n\t\treturn {\n\t\t\tvalid: false,\n\t\t\tissues: ['Project name cannot be empty.'],\n\t\t}\n\t}\n\n\tconst validation = validateNpmPackageName(trimmedName)\n\tconst issues = [...(validation.errors ?? []), ...(validation.warnings ?? [])]\n\tif (!validation.validForNewPackages && issues.length === 0) {\n\t\treturn {\n\t\t\tvalid: false,\n\t\t\tissues: ['Project name is not a valid npm package name.'],\n\t\t}\n\t}\n\n\treturn {\n\t\tvalid: validation.validForNewPackages,\n\t\tissues,\n\t}\n}\n","import { readFile, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { TemplateName } from '../../types'\nimport type { DatabaseOption, DatabaseProviderOption } from './options'\n\ninterface SyncProviderPresetOptions {\n\ttargetDir: string\n\ttemplate: TemplateName\n\tdb: DatabaseOption\n\tdbProvider: DatabaseProviderOption\n}\n\n/**\n * Applies provider-specific sync scaffolding adjustments after template copy.\n *\n * This is a lightweight bridge until template-layer composition lands.\n * Today we only specialize the sync server template when Postgres is selected.\n */\nexport async function applySyncProviderPreset(options: SyncProviderPresetOptions): Promise<void> {\n\tif (!isSyncTemplate(options.template)) {\n\t\treturn\n\t}\n\tif (options.db !== 'postgres') {\n\t\treturn\n\t}\n\n\tconst providerName = getProviderDisplayName(options.dbProvider)\n\tconst providerConnectionString = getProviderConnectionStringExample(options.dbProvider)\n\tconst serverPath = join(options.targetDir, 'server.ts')\n\tconst envPath = join(options.targetDir, '.env.example')\n\tconst readmePath = join(options.targetDir, 'README.md')\n\n\tconst serverTemplate = [\n\t\t\"import { createPostgresServerStore, createProductionServer } from '@korajs/server'\",\n\t\t'',\n\t\t`// PostgreSQL provider preset: ${providerName}`,\n\t\t'// Ensure DATABASE_URL is set in your environment.',\n\t\t'',\n\t\t'async function start(): Promise<void> {',\n\t\t\"\\tconst connectionString = process.env.DATABASE_URL || ''\",\n\t\t'\\tif (connectionString.length === 0) {',\n\t\t\"\\t\\tthrow new Error('DATABASE_URL is required for PostgreSQL sync server store.')\",\n\t\t'\\t}',\n\t\t'',\n\t\t'\\tconst store = await createPostgresServerStore({ connectionString })',\n\t\t'\\tconst server = createProductionServer({',\n\t\t'\\t\\tstore,',\n\t\t\"\\t\\tport: Number(process.env.PORT) || 3001,\",\n\t\t\"\\t\\tstaticDir: './dist',\",\n\t\t\"\\t\\tsyncPath: '/kora-sync',\",\n\t\t'\\t})',\n\t\t'',\n\t\t'\\tconst url = await server.start()',\n\t\t'\\tconsole.log(`Kora app running at ${url}`)',\n\t\t'}',\n\t\t'',\n\t\t'void start()',\n\t\t'',\n\t].join('\\n')\n\n\tconst envTemplate = [\n\t\t'# Kora Sync Server',\n\t\t'# WebSocket URL for the sync server (used by the client)',\n\t\t'VITE_SYNC_URL=ws://localhost:3001',\n\t\t'',\n\t\t'# Sync server port',\n\t\t'PORT=3001',\n\t\t'',\n\t\t`# PostgreSQL connection string (${providerName})`,\n\t\t`# Example: ${providerConnectionString}`,\n\t\t'DATABASE_URL=',\n\t\t'',\n\t].join('\\n')\n\n\tconst existingReadme = await readFile(readmePath, 'utf-8')\n\tconst trimmedReadme = existingReadme.trimEnd()\n\tconst readmeSuffix = [\n\t\t'',\n\t\t'## PostgreSQL Provider Preset',\n\t\t'',\n\t\t`Selected DB provider: ${options.dbProvider}`,\n\t\t'',\n\t\t'This scaffold uses `createPostgresServerStore` in `server.ts` and reads `DATABASE_URL` from the environment. See `.env.example` for provider-specific examples.',\n\t\t'',\n\t].join('\\n')\n\tconst readmeTemplate = `${trimmedReadme}${readmeSuffix}`\n\n\tawait writeFile(serverPath, serverTemplate, 'utf-8')\n\tawait writeFile(envPath, envTemplate, 'utf-8')\n\tawait writeFile(readmePath, readmeTemplate, 'utf-8')\n}\n\nfunction isSyncTemplate(template: TemplateName): boolean {\n\treturn template === 'react-sync' || template === 'react-tailwind-sync'\n}\n\nfunction getProviderDisplayName(provider: DatabaseProviderOption): string {\n\tswitch (provider) {\n\t\tcase 'supabase':\n\t\t\treturn 'Supabase'\n\t\tcase 'neon':\n\t\t\treturn 'Neon'\n\t\tcase 'railway':\n\t\t\treturn 'Railway'\n\t\tcase 'vercel-postgres':\n\t\t\treturn 'Vercel Postgres'\n\t\tcase 'custom':\n\t\t\treturn 'Custom'\n\t\tcase 'local':\n\t\t\treturn 'Local Postgres'\n\t\tcase 'none':\n\t\t\treturn 'PostgreSQL'\n\t}\n}\n\nfunction getProviderConnectionStringExample(provider: DatabaseProviderOption): string {\n\tswitch (provider) {\n\t\tcase 'supabase':\n\t\t\treturn 'postgresql://postgres:<password>@db.<project-ref>.supabase.co:5432/postgres?sslmode=require'\n\t\tcase 'neon':\n\t\t\treturn 'postgresql://<user>:<password>@<branch>.<project>.neon.tech/neondb?sslmode=require'\n\t\tcase 'railway':\n\t\t\treturn 'postgresql://postgres:<password>@<host>.railway.app:<port>/railway?sslmode=require'\n\t\tcase 'vercel-postgres':\n\t\t\treturn 'postgresql://<user>:<password>@<host>.pooler.vercel-storage.com:5432/verceldb?sslmode=require'\n\t\tcase 'custom':\n\t\t\treturn 'postgresql://<user>:<password>@<host>:5432/<database>'\n\t\tcase 'local':\n\t\t\treturn 'postgresql://postgres:postgres@localhost:5432/kora'\n\t\tcase 'none':\n\t\t\treturn 'postgresql://postgres:postgres@localhost:5432/kora'\n\t}\n}\n","import { existsSync } from 'node:fs'\nimport { copyFile, mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises'\nimport { dirname, join, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport type { TemplateContext, TemplateName } from '../types'\n\nexport type TemplateLayerCategory = 'base' | 'ui' | 'style' | 'sync' | 'db' | 'auth'\n\nexport interface TemplateLayer {\n\tcategory: TemplateLayerCategory\n\tname: string\n\tsourceTemplate: TemplateName | null\n}\n\nexport interface TemplateLayerPlan {\n\tlayers: readonly TemplateLayer[]\n\tcompatibilityTarget: TemplateName\n}\n\n/**\n * Replaces {{variable}} placeholders in a template string with context values.\n *\n * @param template - The template string containing {{variable}} placeholders\n * @param context - Key-value pairs to substitute\n * @returns The template with all placeholders replaced\n */\nexport function substituteVariables(template: string, context: Record<string, string>): string {\n\treturn template.replace(/\\{\\{(\\w+)\\}\\}/g, (_match, key: string) => {\n\t\tconst value = context[key]\n\t\treturn value !== undefined ? value : `{{${key}}}`\n\t})\n}\n\n/**\n * Resolves the absolute path to a bundled template directory.\n *\n * After tsup bundling, import.meta.url points to dist/<file>.js (1 level from root).\n * In source, it's src/templates/composer.ts (2 levels from root).\n * We walk up from the current file to find the package root containing templates/.\n *\n * @param templateName - Name of the template (for example, 'react-basic')\n * @returns Absolute path to the template directory\n */\nexport function getTemplatePath(templateName: TemplateName): string {\n\tlet dir = dirname(fileURLToPath(import.meta.url))\n\tfor (let i = 0; i < 7; i++) {\n\t\tconst candidate = resolve(dir, 'templates', templateName)\n\t\tif (existsSync(candidate)) {\n\t\t\treturn candidate\n\t\t}\n\t\tdir = dirname(dir)\n\t}\n\t// Fallback: assume bundled output and step to package root.\n\tconst currentDir = dirname(fileURLToPath(import.meta.url))\n\treturn resolve(currentDir, '..', '..', '..', 'templates', templateName)\n}\n\n/**\n * Returns a v1 compatibility layer plan that composes to one of the existing\n * four concrete templates. This establishes the layer architecture while\n * preserving byte-for-byte output compatibility for current templates.\n */\nexport function createCompatibilityLayerPlan(templateName: TemplateName): TemplateLayerPlan {\n\tconst baseLayer: TemplateLayer = { category: 'base', name: 'base', sourceTemplate: 'react-basic' }\n\tconst uiLayer: TemplateLayer = { category: 'ui', name: 'react', sourceTemplate: null }\n\tconst authLayer: TemplateLayer = { category: 'auth', name: 'none', sourceTemplate: null }\n\n\tswitch (templateName) {\n\t\tcase 'react-basic':\n\t\t\treturn {\n\t\t\t\tcompatibilityTarget: templateName,\n\t\t\t\tlayers: [\n\t\t\t\t\tbaseLayer,\n\t\t\t\t\tuiLayer,\n\t\t\t\t\t{ category: 'style', name: 'plain', sourceTemplate: null },\n\t\t\t\t\t{ category: 'sync', name: 'disabled', sourceTemplate: null },\n\t\t\t\t\t{ category: 'db', name: 'none', sourceTemplate: null },\n\t\t\t\t\tauthLayer,\n\t\t\t\t],\n\t\t\t}\n\t\tcase 'react-tailwind':\n\t\t\treturn {\n\t\t\t\tcompatibilityTarget: templateName,\n\t\t\t\tlayers: [\n\t\t\t\t\tbaseLayer,\n\t\t\t\t\tuiLayer,\n\t\t\t\t\t{ category: 'style', name: 'tailwind', sourceTemplate: 'react-tailwind' },\n\t\t\t\t\t{ category: 'sync', name: 'disabled', sourceTemplate: null },\n\t\t\t\t\t{ category: 'db', name: 'none', sourceTemplate: null },\n\t\t\t\t\tauthLayer,\n\t\t\t\t],\n\t\t\t}\n\t\tcase 'react-sync':\n\t\t\treturn {\n\t\t\t\tcompatibilityTarget: templateName,\n\t\t\t\tlayers: [\n\t\t\t\t\tbaseLayer,\n\t\t\t\t\tuiLayer,\n\t\t\t\t\t{ category: 'style', name: 'plain', sourceTemplate: null },\n\t\t\t\t\t{ category: 'sync', name: 'enabled', sourceTemplate: 'react-sync' },\n\t\t\t\t\t{ category: 'db', name: 'sqlite', sourceTemplate: null },\n\t\t\t\t\tauthLayer,\n\t\t\t\t],\n\t\t\t}\n\t\tcase 'react-tailwind-sync':\n\t\t\treturn {\n\t\t\t\tcompatibilityTarget: templateName,\n\t\t\t\tlayers: [\n\t\t\t\t\tbaseLayer,\n\t\t\t\t\tuiLayer,\n\t\t\t\t\t{ category: 'style', name: 'tailwind', sourceTemplate: 'react-tailwind' },\n\t\t\t\t\t{ category: 'sync', name: 'enabled', sourceTemplate: 'react-tailwind-sync' },\n\t\t\t\t\t{ category: 'db', name: 'sqlite', sourceTemplate: null },\n\t\t\t\t\tauthLayer,\n\t\t\t\t],\n\t\t\t}\n\t}\n}\n\n/**\n * Composes a project by applying template layers in order. Later layers\n * overwrite earlier files, which allows progressive specialization.\n *\n * @param plan - Layer plan describing the composition\n * @param targetDir - Destination directory (must not exist yet)\n * @param context - Variables for template substitution\n */\nexport async function composeTemplateLayers(\n\tplan: TemplateLayerPlan,\n\ttargetDir: string,\n\tcontext: TemplateContext,\n): Promise<void> {\n\tconst vars: Record<string, string> = {\n\t\tprojectName: context.projectName,\n\t\tpackageManager: context.packageManager,\n\t\tkoraVersion: context.koraVersion,\n\t\tdbProvider: context.dbProvider ?? 'none',\n\t}\n\n\tfor (const layer of plan.layers) {\n\t\tif (layer.sourceTemplate === null) {\n\t\t\tcontinue\n\t\t}\n\t\tconst sourceDir = getTemplatePath(layer.sourceTemplate)\n\t\tawait copyDirectory(sourceDir, targetDir, vars)\n\t}\n}\n\nasync function copyDirectory(\n\tsrc: string,\n\tdest: string,\n\tvars: Record<string, string>,\n): Promise<void> {\n\tawait mkdir(dest, { recursive: true })\n\tconst entries = await readdir(src)\n\n\tfor (const entry of entries) {\n\t\tconst srcPath = join(src, entry)\n\t\tconst srcStat = await stat(srcPath)\n\n\t\tif (srcStat.isDirectory()) {\n\t\t\tawait copyDirectory(srcPath, join(dest, entry), vars)\n\t\t\tcontinue\n\t\t}\n\t\tif (entry.endsWith('.hbs')) {\n\t\t\tconst content = await readFile(srcPath, 'utf-8')\n\t\t\tconst outputName = entry.slice(0, -4)\n\t\t\tawait writeFile(join(dest, outputName), substituteVariables(content, vars), 'utf-8')\n\t\t\tcontinue\n\t\t}\n\t\tawait copyFile(srcPath, join(dest, entry))\n\t}\n}\n","import { composeTemplateLayers, createCompatibilityLayerPlan } from '../../templates/composer'\nimport type { TemplateContext, TemplateName } from '../../types'\n\n/**\n * Replaces {{variable}} placeholders in a template string with context values.\n *\n * @param template - The template string containing {{variable}} placeholders\n * @param context - Key-value pairs to substitute\n * @returns The template with all placeholders replaced\n */\nexport { substituteVariables, getTemplatePath } from '../../templates/composer'\n\n/**\n * Scaffolds a project from a bundled template.\n * Copies all files from the template directory to the target, applying\n * variable substitution to .hbs files and stripping the .hbs extension.\n *\n * @param templateName - Which template to use\n * @param targetDir - Destination directory (must not exist yet)\n * @param context - Variables for template substitution\n */\nexport async function scaffoldTemplate(\n\ttemplateName: TemplateName,\n\ttargetDir: string,\n\tcontext: TemplateContext,\n): Promise<void> {\n\tconst plan = createCompatibilityLayerPlan(templateName)\n\tawait composeTemplateLayers(plan, targetDir, context)\n}\n","import { basename, join } from 'node:path'\nimport { defineCommand } from 'citty'\nimport { InvalidProjectError } from '../../errors'\nimport { createPromptClient } from '../../prompts/prompt-client'\nimport { findProjectRoot } from '../../utils/fs-helpers'\nimport { createLogger } from '../../utils/logger'\nimport {\n\ttype ContextAwareDeployAdapter,\n\tDEPLOY_PLATFORMS,\n\ttype DeployAdapter,\n\ttype DeployPlatform,\n\ttype ProjectConfig,\n\tisDeployPlatform,\n} from './adapters/adapter'\nimport { createDeployAdapter } from './adapters/factory'\nimport {\n\twriteDockerIgnoreArtifact,\n\twriteDockerfileArtifact,\n} from './artifacts/dockerfile-generator'\nimport {\n\treadDeployState,\n\tresetDeployState,\n\tresolveDeployDirectory,\n\tupdateDeployState,\n\twriteDeployState,\n} from './state/deploy-state'\n\n/**\n * The `deploy` command for Phase 13.\n *\n * This command orchestrates:\n * - deploy state resolution and persistence\n * - artifact generation\n * - adapter-driven provision/build/deploy flows\n */\nexport const deployCommand = defineCommand({\n\tmeta: {\n\t\tname: 'deploy',\n\t\tdescription: 'Deploy a Kora project to your selected platform',\n\t},\n\targs: {\n\t\tplatform: {\n\t\t\ttype: 'string',\n\t\t\tdescription: `Deployment platform (${DEPLOY_PLATFORMS.join(', ')})`,\n\t\t},\n\t\tapp: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Application name used by the target platform',\n\t\t},\n\t\tregion: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Preferred deployment region (for example: iad, lhr, syd)',\n\t\t},\n\t\tprod: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Deploy to production environment',\n\t\t\tdefault: false,\n\t\t},\n\t\tconfirm: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Non-interactive mode (fail fast on missing required data)',\n\t\t\tdefault: false,\n\t\t},\n\t\treset: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Delete .kora/deploy state and generated artifacts',\n\t\t\tdefault: false,\n\t\t},\n\t},\n\tsubCommands: {\n\t\tstatus: defineCommand({\n\t\t\tmeta: {\n\t\t\t\tname: 'status',\n\t\t\t\tdescription: 'Show current deployment status',\n\t\t\t},\n\t\t\tasync run() {\n\t\t\t\tconst logger = createLogger()\n\t\t\t\tconst projectRoot = await requireProjectRoot()\n\t\t\t\tconst state = await readDeployState(projectRoot)\n\t\t\t\tif (!state) {\n\t\t\t\t\tlogger.warn('No deployment state found. Run `kora deploy` first.')\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tlogger.banner()\n\t\t\t\tlogger.info(`Platform: ${state.platform}`)\n\t\t\t\tlogger.step(`App: ${state.appName}`)\n\t\t\t\tlogger.step(`Region: ${state.region ?? 'n/a'}`)\n\t\t\t\tlogger.step(`Last deployment: ${state.lastDeploymentId ?? 'n/a'}`)\n\n\t\t\t\tconst adapter = createDeployAdapter(state.platform)\n\t\t\t\tconfigureAdapterContext(adapter, {\n\t\t\t\t\tprojectRoot,\n\t\t\t\t\tappName: state.appName,\n\t\t\t\t\tregion: state.region,\n\t\t\t\t})\n\t\t\t\tconst adapterStatus = await adapter.status()\n\t\t\t\tlogger.step(`Status: ${adapterStatus.state}`)\n\t\t\t\tlogger.step(`Message: ${adapterStatus.message}`)\n\t\t\t\tlogger.step(`Live URL: ${adapterStatus.liveUrl ?? state.liveUrl ?? 'n/a'}`)\n\t\t\t\tlogger.step(`Sync URL: ${state.syncUrl ?? 'n/a'}`)\n\t\t\t},\n\t\t}),\n\t\trollback: defineCommand({\n\t\t\tmeta: {\n\t\t\t\tname: 'rollback',\n\t\t\t\tdescription: 'Rollback the current deployment',\n\t\t\t},\n\t\t\targs: {\n\t\t\t\tid: {\n\t\t\t\t\ttype: 'positional',\n\t\t\t\t\tdescription: 'Optional deployment identifier',\n\t\t\t\t\trequired: false,\n\t\t\t\t},\n\t\t\t},\n\t\t\tasync run({ args }) {\n\t\t\t\tconst logger = createLogger()\n\t\t\t\tconst projectRoot = await requireProjectRoot()\n\t\t\t\tconst state = await readDeployState(projectRoot)\n\t\t\t\tif (!state) {\n\t\t\t\t\tlogger.warn('No deployment state found. Run `kora deploy` first.')\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tconst adapter = createDeployAdapter(state.platform)\n\t\t\t\tconfigureAdapterContext(adapter, {\n\t\t\t\t\tprojectRoot,\n\t\t\t\t\tappName: state.appName,\n\t\t\t\t\tregion: state.region,\n\t\t\t\t})\n\t\t\t\tconst deploymentId =\n\t\t\t\t\ttypeof args.id === 'string' && args.id.length > 0\n\t\t\t\t\t\t? args.id\n\t\t\t\t\t\t: (state.lastDeploymentId ?? 'latest')\n\t\t\t\tawait adapter.rollback(deploymentId)\n\t\t\t\tlogger.success(`Rolled back ${state.platform} deployment to ${deploymentId}.`)\n\t\t\t},\n\t\t}),\n\t\tlogs: defineCommand({\n\t\t\tmeta: {\n\t\t\t\tname: 'logs',\n\t\t\t\tdescription: 'Read deployment logs',\n\t\t\t},\n\t\t\tasync run() {\n\t\t\t\tconst logger = createLogger()\n\t\t\t\tconst projectRoot = await requireProjectRoot()\n\t\t\t\tconst state = await readDeployState(projectRoot)\n\t\t\t\tif (!state) {\n\t\t\t\t\tlogger.warn('No deployment state found. Run `kora deploy` first.')\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tconst adapter = createDeployAdapter(state.platform)\n\t\t\t\tconfigureAdapterContext(adapter, {\n\t\t\t\t\tprojectRoot,\n\t\t\t\t\tappName: state.appName,\n\t\t\t\t\tregion: state.region,\n\t\t\t\t})\n\t\t\t\tconst logLines = adapter.logs({ tail: 200 })\n\t\t\t\tlet hasLines = false\n\t\t\t\tfor await (const line of logLines) {\n\t\t\t\t\thasLines = true\n\t\t\t\t\tlogger.step(`[${line.level}] ${line.message}`)\n\t\t\t\t}\n\t\t\t\tif (!hasLines) {\n\t\t\t\t\tlogger.warn(`No logs returned from ${state.platform}.`)\n\t\t\t\t}\n\t\t\t},\n\t\t}),\n\t},\n\tasync run({ args, rawArgs }) {\n\t\t// Citty calls run() even after subcommand execution.\n\t\t// Guard against double-execution when a subcommand was invoked.\n\t\tconst subCommandNames = ['status', 'rollback', 'logs']\n\t\tif (rawArgs.some((arg) => subCommandNames.includes(arg))) {\n\t\t\treturn\n\t\t}\n\n\t\tconst logger = createLogger()\n\t\tconst prompts = createPromptClient()\n\t\tconst projectRoot = await requireProjectRoot()\n\n\t\tif (args.reset === true) {\n\t\t\tawait resetDeployState(projectRoot)\n\t\t\tlogger.success('Reset .kora/deploy state.')\n\t\t\treturn\n\t\t}\n\n\t\tconst existingState = await readDeployState(projectRoot)\n\t\tconst confirmMode = args.confirm === true\n\t\tconst platform = await resolvePlatform({\n\t\t\tpromptClient: prompts,\n\t\t\tplatformArg: args.platform,\n\t\t\tstoredPlatform: existingState?.platform,\n\t\t\tconfirm: confirmMode,\n\t\t})\n\t\tconst appName = resolveAppName(args.app, existingState?.appName, projectRoot, confirmMode)\n\t\tconst region = resolveRegion(args.region, existingState?.region, confirmMode)\n\t\tconst deployDirectory = resolveDeployDirectory(projectRoot)\n\t\tconst environment = args.prod === true ? 'production' : 'preview'\n\t\tconst config: ProjectConfig = {\n\t\t\tprojectRoot,\n\t\t\tappName,\n\t\t\tregion,\n\t\t\tenvironment,\n\t\t\tconfirm: confirmMode,\n\t\t}\n\t\tconst adapter = createDeployAdapter(platform)\n\t\tconfigureAdapterContext(adapter, {\n\t\t\tprojectRoot,\n\t\t\tappName,\n\t\t\tregion,\n\t\t})\n\n\t\tlogger.banner()\n\t\tlogger.info(\n\t\t\t`Deploying to ${platform} (${appName}${region ? `, ${region}` : ''}, ${environment})`,\n\t\t)\n\t\tif (confirmMode) {\n\t\t\tlogger.step('Running in --confirm mode (non-interactive, fail-fast).')\n\t\t}\n\n\t\tawait writeDockerfileArtifact(deployDirectory, {\n\t\t\tnativeDependencies: {\n\t\t\t\t'better-sqlite3': '^11.0.0',\n\t\t\t\t'drizzle-orm': '^0.45.2',\n\t\t\t},\n\t\t})\n\t\tawait writeDockerIgnoreArtifact(deployDirectory)\n\t\tconst detected = await adapter.detect()\n\t\tif (!detected) {\n\t\t\tawait adapter.install()\n\t\t}\n\t\tawait adapter.authenticate()\n\t\tconst provisionResult = await adapter.provision(config)\n\t\tconst artifacts = await adapter.build(config)\n\t\tconst deployResult = await adapter.deploy(artifacts)\n\n\t\tif (existingState) {\n\t\t\tawait updateDeployState(projectRoot, {\n\t\t\t\tplatform,\n\t\t\t\tappName,\n\t\t\t\tregion,\n\t\t\t\tprojectRoot,\n\t\t\t\tliveUrl: deployResult.liveUrl,\n\t\t\t\tsyncUrl: deployResult.syncUrl,\n\t\t\t\tdatabaseId: provisionResult.databaseId,\n\t\t\t\tlastDeploymentId: deployResult.deploymentId,\n\t\t\t})\n\t\t} else {\n\t\t\tawait writeDeployState(projectRoot, {\n\t\t\t\tplatform,\n\t\t\t\tappName,\n\t\t\t\tregion,\n\t\t\t\tprojectRoot,\n\t\t\t\tliveUrl: deployResult.liveUrl,\n\t\t\t\tsyncUrl: deployResult.syncUrl,\n\t\t\t\tdatabaseId: provisionResult.databaseId,\n\t\t\t\tlastDeploymentId: deployResult.deploymentId,\n\t\t\t})\n\t\t}\n\n\t\tlogger.success(`Deployment completed: ${deployResult.liveUrl}`)\n\t\tif (deployResult.syncUrl) {\n\t\t\tlogger.step(`Sync endpoint: ${deployResult.syncUrl}`)\n\t\t}\n\t},\n})\n\ninterface ResolvePlatformOptions {\n\tpromptClient: ReturnType<typeof createPromptClient>\n\tplatformArg: unknown\n\tstoredPlatform: DeployPlatform | undefined\n\tconfirm: boolean\n}\n\nasync function resolvePlatform(options: ResolvePlatformOptions): Promise<DeployPlatform> {\n\tif (typeof options.platformArg === 'string') {\n\t\tif (!isDeployPlatform(options.platformArg)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid --platform value \"${options.platformArg}\". Valid options: ${DEPLOY_PLATFORMS.join(', ')}`,\n\t\t\t)\n\t\t}\n\t\treturn options.platformArg\n\t}\n\n\tif (options.storedPlatform) {\n\t\treturn options.storedPlatform\n\t}\n\n\tif (options.confirm || !isInteractiveTerminal()) {\n\t\tthrow new Error(\n\t\t\t'Missing deploy platform in --confirm mode. Provide --platform or run an interactive deploy first.',\n\t\t)\n\t}\n\n\treturn await options.promptClient.select('Where do you want to deploy?', [\n\t\t{\n\t\t\tlabel: 'Fly.io (recommended for sync apps)',\n\t\t\tvalue: 'fly',\n\t\t},\n\t\t{\n\t\t\tlabel: 'Railway',\n\t\t\tvalue: 'railway',\n\t\t},\n\t\t{\n\t\t\tlabel: 'Render',\n\t\t\tvalue: 'render',\n\t\t},\n\t\t{\n\t\t\tlabel: 'Docker (self-hosted)',\n\t\t\tvalue: 'docker',\n\t\t},\n\t\t{\n\t\t\tlabel: 'Kora Cloud (coming soon)',\n\t\t\tvalue: 'kora-cloud',\n\t\t},\n\t])\n}\n\nfunction resolveAppName(\n\targValue: unknown,\n\tstoredValue: string | undefined,\n\tprojectRoot: string,\n\tconfirm: boolean,\n): string {\n\tif (typeof argValue === 'string' && argValue.length > 0) {\n\t\treturn sanitizeAppName(argValue)\n\t}\n\n\tif (storedValue && storedValue.length > 0) {\n\t\treturn storedValue\n\t}\n\n\tif (confirm) {\n\t\tthrow new Error(\n\t\t\t'Missing app name in --confirm mode. Provide --app or run an interactive deploy first.',\n\t\t)\n\t}\n\n\treturn sanitizeAppName(basename(projectRoot))\n}\n\nfunction resolveRegion(\n\targValue: unknown,\n\tstoredValue: string | null | undefined,\n\tconfirm: boolean,\n): string | null {\n\tif (typeof argValue === 'string' && argValue.length > 0) return argValue\n\tif (storedValue !== undefined) return storedValue\n\tif (confirm) {\n\t\tthrow new Error(\n\t\t\t'Missing region in --confirm mode. Provide --region or run an interactive deploy first.',\n\t\t)\n\t}\n\treturn 'iad'\n}\n\nfunction sanitizeAppName(value: string): string {\n\tconst normalized = value\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9-]+/g, '-')\n\t\t.replace(/-{2,}/g, '-')\n\t\t.replace(/^-|-$/g, '')\n\n\tif (normalized.length === 0) {\n\t\treturn 'kora-app'\n\t}\n\treturn normalized\n}\n\nasync function requireProjectRoot(): Promise<string> {\n\tconst projectRoot = await findProjectRoot()\n\tif (!projectRoot) {\n\t\tthrow new InvalidProjectError(process.cwd())\n\t}\n\treturn projectRoot\n}\n\nfunction isInteractiveTerminal(): boolean {\n\treturn process.stdin.isTTY === true && process.stdout.isTTY === true\n}\n\nfunction configureAdapterContext(\n\tadapter: DeployAdapter,\n\tcontext: { projectRoot: string; appName: string; region: string | null },\n): void {\n\tif (hasContextSetter(adapter)) {\n\t\tadapter.setContext(context)\n\t}\n}\n\nfunction hasContextSetter(adapter: DeployAdapter): adapter is ContextAwareDeployAdapter {\n\treturn typeof (adapter as ContextAwareDeployAdapter).setContext === 'function'\n}\n","export const DEPLOY_PLATFORMS = ['fly', 'railway', 'render', 'docker', 'kora-cloud'] as const\n\nexport type DeployPlatform = (typeof DEPLOY_PLATFORMS)[number]\n\nexport interface ProjectConfig {\n\tprojectRoot: string\n\tappName: string\n\tregion: string | null\n\tenvironment: 'preview' | 'production'\n\tconfirm: boolean\n}\n\nexport interface ProvisionResult {\n\tapplicationId: string\n\tdatabaseId: string | null\n\tsecretsSet: string[]\n}\n\nexport interface BuildArtifacts {\n\tclientDirectory: string | null\n\tserverBundlePath: string | null\n\tdeployDirectory: string\n}\n\nexport interface DeployResult {\n\tdeploymentId: string\n\tliveUrl: string\n\tsyncUrl: string | null\n}\n\nexport interface LogOptions {\n\tsince?: string\n\ttail?: number\n}\n\nexport interface LogLine {\n\ttimestamp: string\n\tlevel: 'debug' | 'info' | 'warn' | 'error'\n\tmessage: string\n}\n\nexport interface DeploymentStatus {\n\tstate: 'pending' | 'healthy' | 'failed' | 'unknown'\n\tmessage: string\n\tliveUrl?: string\n}\n\n/**\n * Contract implemented by each deployment platform integration.\n */\nexport interface DeployAdapter {\n\tname: DeployPlatform\n\tdetect(): Promise<boolean>\n\tinstall(): Promise<void>\n\tauthenticate(): Promise<void>\n\tprovision(config: ProjectConfig): Promise<ProvisionResult>\n\tbuild(config: ProjectConfig): Promise<BuildArtifacts>\n\tdeploy(artifacts: BuildArtifacts): Promise<DeployResult>\n\trollback(deploymentId: string): Promise<void>\n\tlogs(options: LogOptions): AsyncIterable<LogLine>\n\tstatus(): Promise<DeploymentStatus>\n}\n\n/**\n * Optional adapter extension for commands that require runtime context\n * (project root, app name, region) outside an initial provisioning run.\n */\nexport interface ContextAwareDeployAdapter extends DeployAdapter {\n\tsetContext(context: {\n\t\tprojectRoot: string\n\t\tappName: string\n\t\tregion: string | null\n\t}): void\n}\n\n/**\n * Checks whether the provided value is a known deploy platform.\n */\nexport function isDeployPlatform(value: string): value is DeployPlatform {\n\treturn (DEPLOY_PLATFORMS as readonly string[]).includes(value)\n}\n","import { spawn } from 'node:child_process'\nimport { join } from 'node:path'\nimport { createLogger } from '../../../utils/logger'\nimport { writeFlyTomlArtifact } from '../artifacts/fly-toml-generator'\nimport { buildClient } from '../builder/client-builder'\nimport { bundleServer } from '../builder/server-bundler'\nimport type {\n\tBuildArtifacts,\n\tContextAwareDeployAdapter,\n\tDeployResult,\n\tDeploymentStatus,\n\tLogLine,\n\tLogOptions,\n\tProjectConfig,\n\tProvisionResult,\n} from './adapter'\n\n/**\n * Execution abstraction for Fly CLI shell interactions.\n * This keeps FlyAdapter deterministic and fully mockable in tests.\n */\nexport interface FlyCommandRunner {\n\trun(command: string, args: string[], cwd: string): Promise<FlyCommandResult>\n}\n\nexport interface FlyCommandResult {\n\texitCode: number\n\tstdout: string\n\tstderr: string\n}\n\nexport interface FlyAdapterOptions {\n\trunner?: FlyCommandRunner\n\tcontext?: FlyAdapterContext\n\tcommandCandidates?: readonly string[]\n}\n\n/**\n * Fly.io deploy adapter implementation for Phase 13.\n */\nexport class FlyAdapter implements ContextAwareDeployAdapter {\n\tpublic readonly name = 'fly' as const\n\n\tprivate readonly logger = createLogger()\n\tprivate readonly runner: FlyCommandRunner\n\tprivate readonly commandCandidates: readonly string[]\n\tprivate flyCommand: string | null = null\n\tprivate currentContext: FlyAdapterContext | null\n\tprivate lastDeploymentId: string | null = null\n\n\tpublic constructor(options: FlyAdapterOptions = {}) {\n\t\tthis.runner = options.runner ?? new NodeFlyCommandRunner()\n\t\tthis.commandCandidates = options.commandCandidates ?? DEFAULT_FLY_COMMAND_CANDIDATES\n\t\tthis.currentContext = options.context ?? null\n\t}\n\n\t/**\n\t * Seeds runtime context for non-provisioning commands.\n\t */\n\tpublic setContext(context: FlyAdapterContext): void {\n\t\tthis.currentContext = context\n\t}\n\n\t/**\n\t * Checks whether a Fly CLI executable can be resolved.\n\t */\n\tpublic async detect(): Promise<boolean> {\n\t\tconst command = await this.tryResolveFlyCommand(process.cwd())\n\t\treturn command !== null\n\t}\n\n\t/**\n\t * Ensures Fly CLI is available before deployment.\n\t */\n\tpublic async install(): Promise<void> {\n\t\tconst available = await this.detect()\n\t\tif (!available) {\n\t\t\tthrow new Error(\n\t\t\t\t'Fly CLI is required but not installed. Install from https://fly.io/docs/hands-on/install-flyctl/.',\n\t\t\t)\n\t\t}\n\t}\n\n\t/**\n\t * Performs Fly authentication check/login.\n\t */\n\tpublic async authenticate(): Promise<void> {\n\t\tconst projectRoot = this.currentContext?.projectRoot ?? process.cwd()\n\t\tconst status = await this.runFlyCommand(['auth', 'whoami', '--json'], projectRoot, false)\n\t\tif (status.exitCode === 0) return\n\n\t\tconst login = await this.runFlyCommand(['auth', 'login'], projectRoot, true)\n\t\tif (login.exitCode !== 0) {\n\t\t\tthrow new Error(`Fly authentication failed: ${normalizeError(login.stderr, login.stdout)}`)\n\t\t}\n\t}\n\n\t/**\n\t * Provisions app and optionally region-bound resources in Fly.\n\t */\n\tpublic async provision(config: ProjectConfig): Promise<ProvisionResult> {\n\t\tthis.currentContext = {\n\t\t\tprojectRoot: config.projectRoot,\n\t\t\tappName: config.appName,\n\t\t\tregion: config.region ?? 'iad',\n\t\t}\n\n\t\tconst appCreateArgs = ['apps', 'create', config.appName]\n\n\t\tconst createApp = await this.runFlyCommand(appCreateArgs, config.projectRoot, false)\n\t\tif (createApp.exitCode !== 0 && !isAlreadyExistsResponse(createApp.stderr, createApp.stdout)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Fly app provisioning failed for \"${config.appName}\": ${normalizeError(createApp.stderr, createApp.stdout)}`,\n\t\t\t)\n\t\t}\n\n\t\tconst secrets: string[] = []\n\t\tconst portSecret = await this.runFlyCommand(\n\t\t\t['secrets', 'set', 'PORT=3000', '--app', config.appName],\n\t\t\tconfig.projectRoot,\n\t\t\tfalse,\n\t\t)\n\t\tif (portSecret.exitCode === 0) {\n\t\t\tsecrets.push('PORT')\n\t\t}\n\n\t\treturn {\n\t\t\tapplicationId: config.appName,\n\t\t\tdatabaseId: null,\n\t\t\tsecretsSet: secrets,\n\t\t}\n\t}\n\n\t/**\n\t * Builds local artifacts consumed by Fly deploy.\n\t */\n\tpublic async build(config: ProjectConfig): Promise<BuildArtifacts> {\n\t\tthis.currentContext = {\n\t\t\tprojectRoot: config.projectRoot,\n\t\t\tappName: config.appName,\n\t\t\tregion: config.region,\n\t\t}\n\t\tconst deployDirectory = join(config.projectRoot, '.kora', 'deploy')\n\t\tawait writeFlyTomlArtifact(deployDirectory, {\n\t\t\tappName: config.appName,\n\t\t\tregion: config.region ?? 'iad',\n\t\t})\n\n\t\tawait bundleServer({\n\t\t\tprojectRoot: config.projectRoot,\n\t\t\tdeployDirectory,\n\t\t})\n\t\tconst client = await buildClient({\n\t\t\tprojectRoot: config.projectRoot,\n\t\t\toutDir: join(deployDirectory, 'dist'),\n\t\t\tmode: 'production',\n\t\t})\n\n\t\treturn {\n\t\t\tclientDirectory: client.outDir,\n\t\t\tserverBundlePath: join(deployDirectory, 'server-bundled.js'),\n\t\t\tdeployDirectory,\n\t\t}\n\t}\n\n\t/**\n\t * Deploys generated artifacts to Fly and returns live endpoints.\n\t */\n\tpublic async deploy(artifacts: BuildArtifacts): Promise<DeployResult> {\n\t\tconst context = this.requireContext()\n\t\tconst deploy = await this.runFlyCommand(\n\t\t\t['deploy', '--config', 'fly.toml', '--app', context.appName],\n\t\t\tartifacts.deployDirectory,\n\t\t\ttrue,\n\t\t)\n\t\tif (deploy.exitCode !== 0) {\n\t\t\tthrow new Error(`Fly deployment failed: ${normalizeError(deploy.stderr, deploy.stdout)}`)\n\t\t}\n\n\t\tconst info = await this.runFlyCommand(\n\t\t\t['status', '--app', context.appName, '--json'],\n\t\t\tcontext.projectRoot,\n\t\t\tfalse,\n\t\t)\n\t\tconst hostname = parseFlyHostname(info.stdout) ?? `${context.appName}.fly.dev`\n\t\tconst deploymentId = parseFlyDeploymentId(info.stdout) ?? new Date().toISOString()\n\t\tthis.lastDeploymentId = deploymentId\n\n\t\treturn {\n\t\t\tdeploymentId,\n\t\t\tliveUrl: `https://${hostname}`,\n\t\t\tsyncUrl: `wss://${hostname}/kora-sync`,\n\t\t}\n\t}\n\n\t/**\n\t * Rolls back to a deployment version.\n\t */\n\tpublic async rollback(deploymentId: string): Promise<void> {\n\t\tconst context = this.requireContext()\n\t\tconst rollback = await this.runFlyCommand(\n\t\t\t['releases', 'revert', deploymentId, '--app', context.appName],\n\t\t\tcontext.projectRoot,\n\t\t\ttrue,\n\t\t)\n\t\tif (rollback.exitCode !== 0) {\n\t\t\tthrow new Error(`Fly rollback failed: ${normalizeError(rollback.stderr, rollback.stdout)}`)\n\t\t}\n\t}\n\n\t/**\n\t * Returns deployment logs as an async iterable.\n\t */\n\tpublic async *logs(options: LogOptions): AsyncIterable<LogLine> {\n\t\tconst context = this.requireContext()\n\t\tconst args = ['logs', '--app', context.appName, '--no-tail']\n\t\tif (typeof options.since === 'string' && options.since.length > 0) {\n\t\t\targs.push('--region', options.since)\n\t\t}\n\t\tconst result = await this.runFlyCommand(args, context.projectRoot, false)\n\t\tif (result.exitCode !== 0) {\n\t\t\tthrow new Error(`Fly logs failed: ${normalizeError(result.stderr, result.stdout)}`)\n\t\t}\n\n\t\tconst lines = result.stdout.split(/\\r?\\n/).filter((line) => line.length > 0)\n\t\tfor (const line of lines) {\n\t\t\tyield {\n\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\tlevel: inferLogLevel(line),\n\t\t\t\tmessage: line,\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Reads current deployment status from Fly.\n\t */\n\tpublic async status(): Promise<DeploymentStatus> {\n\t\tconst context = this.requireContext()\n\t\tconst status = await this.runFlyCommand(\n\t\t\t['status', '--app', context.appName, '--json'],\n\t\t\tcontext.projectRoot,\n\t\t\tfalse,\n\t\t)\n\t\tif (status.exitCode !== 0) {\n\t\t\treturn {\n\t\t\t\tstate: 'failed',\n\t\t\t\tmessage: normalizeError(status.stderr, status.stdout),\n\t\t\t}\n\t\t}\n\n\t\tconst hostname = parseFlyHostname(status.stdout)\n\t\treturn {\n\t\t\tstate: 'healthy',\n\t\t\tmessage: 'Fly deployment is healthy.',\n\t\t\tliveUrl: hostname ? `https://${hostname}` : undefined,\n\t\t}\n\t}\n\n\tprivate async runFlyCommand(\n\t\tflyArgs: string[],\n\t\tcwd: string,\n\t\tinheritOutput: boolean,\n\t): Promise<FlyCommandResult> {\n\t\tconst flyBinary = await this.resolveFlyCommand(cwd)\n\n\t\tif (inheritOutput) {\n\t\t\tthis.logger.step(`fly ${flyArgs.join(' ')}`)\n\t\t}\n\t\treturn await this.runner.run(flyBinary, flyArgs, cwd)\n\t}\n\n\tprivate requireContext(): FlyAdapterContext {\n\t\tif (!this.currentContext) {\n\t\t\tthrow new Error('Fly adapter context is not initialized. Run provision() first.')\n\t\t}\n\t\treturn this.currentContext\n\t}\n\n\tprivate async resolveFlyCommand(cwd: string): Promise<string> {\n\t\tif (this.flyCommand) {\n\t\t\treturn this.flyCommand\n\t\t}\n\n\t\tconst resolved = await this.tryResolveFlyCommand(cwd)\n\t\tif (!resolved) {\n\t\t\tthrow new Error('Could not resolve a usable Fly CLI command (tried flyctl, fly).')\n\t\t}\n\t\tthis.flyCommand = resolved\n\t\treturn resolved\n\t}\n\n\tprivate async tryResolveFlyCommand(cwd: string): Promise<string | null> {\n\t\tfor (const command of this.commandCandidates) {\n\t\t\tconst versionCheck = await this.runner.run(command, ['version'], cwd)\n\t\t\tif (versionCheck.exitCode === 0) {\n\t\t\t\treturn command\n\t\t\t}\n\t\t}\n\n\t\treturn null\n\t}\n}\n\n/**\n * Default subprocess-backed runner for Fly commands.\n */\nexport class NodeFlyCommandRunner implements FlyCommandRunner {\n\tpublic async run(command: string, args: string[], cwd: string): Promise<FlyCommandResult> {\n\t\treturn await new Promise<FlyCommandResult>((resolve) => {\n\t\t\tconst child = spawn(command, args, {\n\t\t\t\tcwd,\n\t\t\t\tenv: process.env,\n\t\t\t\tstdio: ['ignore', 'pipe', 'pipe'],\n\t\t\t})\n\n\t\t\tlet stdout = ''\n\t\t\tlet stderr = ''\n\t\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\t\tstdout += chunk.toString('utf-8')\n\t\t\t})\n\t\t\tchild.stderr?.on('data', (chunk: Buffer) => {\n\t\t\t\tstderr += chunk.toString('utf-8')\n\t\t\t})\n\t\t\tchild.on('error', (error) => {\n\t\t\t\tresolve({\n\t\t\t\t\texitCode: 1,\n\t\t\t\t\tstdout,\n\t\t\t\t\tstderr: `${stderr}\\n${error.message}`,\n\t\t\t\t})\n\t\t\t})\n\t\t\tchild.on('exit', (code) => {\n\t\t\t\tresolve({\n\t\t\t\t\texitCode: code ?? 1,\n\t\t\t\t\tstdout: stdout.trim(),\n\t\t\t\t\tstderr: stderr.trim(),\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t}\n}\n\nexport interface FlyAdapterContext {\n\tprojectRoot: string\n\tappName: string\n\tregion: string | null\n}\n\nconst DEFAULT_FLY_COMMAND_CANDIDATES = ['flyctl', 'fly'] as const\n\nfunction parseFlyHostname(rawJson: string): string | null {\n\tconst parsed = parseJsonRecord(rawJson)\n\tif (!parsed) return null\n\n\tconst hostname = parsed.Hostname\n\tif (typeof hostname === 'string' && hostname.length > 0) {\n\t\treturn hostname\n\t}\n\n\tconst hostnames = parsed.Hostnames\n\tif (Array.isArray(hostnames)) {\n\t\tconst first = hostnames.find((item) => typeof item === 'string')\n\t\tif (typeof first === 'string' && first.length > 0) {\n\t\t\treturn first\n\t\t}\n\t}\n\n\treturn null\n}\n\nfunction parseFlyDeploymentId(rawJson: string): string | null {\n\tconst parsed = parseJsonRecord(rawJson)\n\tif (!parsed) return null\n\n\tconst deploymentId = parsed.DeploymentID\n\tif (typeof deploymentId === 'string' && deploymentId.length > 0) {\n\t\treturn deploymentId\n\t}\n\n\tconst latestDeployment = parsed.LatestDeployment\n\tif (typeof latestDeployment === 'object' && latestDeployment !== null) {\n\t\tconst id = (latestDeployment as Record<string, unknown>).ID\n\t\tif (typeof id === 'string' && id.length > 0) {\n\t\t\treturn id\n\t\t}\n\t}\n\n\treturn null\n}\n\nfunction parseJsonRecord(value: string): Record<string, unknown> | null {\n\ttry {\n\t\tconst parsed = JSON.parse(value) as unknown\n\t\tif (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {\n\t\t\treturn parsed as Record<string, unknown>\n\t\t}\n\t\treturn null\n\t} catch {\n\t\treturn null\n\t}\n}\n\nfunction inferLogLevel(line: string): LogLine['level'] {\n\tconst normalized = line.toLowerCase()\n\tif (normalized.includes('error')) return 'error'\n\tif (normalized.includes('warn')) return 'warn'\n\tif (normalized.includes('debug')) return 'debug'\n\treturn 'info'\n}\n\nfunction normalizeError(stderr: string, stdout: string): string {\n\tif (stderr.length > 0) return stderr\n\tif (stdout.length > 0) return stdout\n\treturn 'unknown fly CLI error'\n}\n\nfunction isAlreadyExistsResponse(stderr: string, stdout: string): boolean {\n\tconst text = `${stderr}\\n${stdout}`.toLowerCase()\n\treturn text.includes('already exists') || text.includes('already been taken')\n}\n","import { mkdir, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nconst GENERATED_HEADER = '# Generated by kora deploy — do not edit manually'\n\n/**\n * Configuration options used to render `fly.toml`.\n */\nexport interface FlyTomlOptions {\n\tappName: string\n\tregion: string\n\tinternalPort?: number\n}\n\n/**\n * Generates a minimal Fly.io configuration file for Kora sync apps.\n */\nexport function generateFlyToml(options: FlyTomlOptions): string {\n\tconst internalPort = options.internalPort ?? 3000\n\n\treturn [\n\t\tGENERATED_HEADER,\n\t\t'',\n\t\t`app = \"${options.appName}\"`,\n\t\t`primary_region = \"${options.region}\"`,\n\t\t'',\n\t\t'[build]',\n\t\t` dockerfile = \"Dockerfile\"`,\n\t\t'',\n\t\t'[http_service]',\n\t\t` internal_port = ${String(internalPort)}`,\n\t\t' force_https = true',\n\t\t' auto_stop_machines = \"stop\"',\n\t\t' auto_start_machines = true',\n\t\t' min_machines_running = 0',\n\t\t'',\n\t\t' [[http_service.checks]]',\n\t\t' grace_period = \"10s\"',\n\t\t' interval = \"30s\"',\n\t\t' method = \"GET\"',\n\t\t' timeout = \"5s\"',\n\t\t' path = \"/\"',\n\t\t'',\n\t].join('\\n')\n}\n\n/**\n * Writes `fly.toml` into `.kora/deploy`.\n */\nexport async function writeFlyTomlArtifact(\n\tdeployDirectory: string,\n\toptions: FlyTomlOptions,\n): Promise<string> {\n\tawait mkdir(deployDirectory, { recursive: true })\n\tconst filePath = join(deployDirectory, 'fly.toml')\n\tawait writeFile(filePath, generateFlyToml(options), 'utf-8')\n\treturn filePath\n}\n","import { spawn } from 'node:child_process'\nimport { copyFile, readdir } from 'node:fs/promises'\nimport { existsSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { resolveProjectBinaryEntryPoint } from '../../../utils/fs-helpers'\n\n/**\n * Inputs used to execute a client build through Vite.\n */\nexport interface ClientBuildOptions {\n\tprojectRoot: string\n\toutDir: string\n\tmode?: 'development' | 'production'\n}\n\n/**\n * Result returned after a successful Vite build.\n */\nexport interface ClientBuildResult {\n\toutDir: string\n}\n\n/**\n * Builds the client bundle with the project's local Vite installation.\n *\n * After Vite completes, patches the output to ensure SQLite WASM assets\n * are present. The template's sqliteWasmHotfix Vite plugin writes to the\n * default `dist/` directory, but `kora deploy` redirects output to\n * `.kora/deploy/dist/`. This post-build step fills in any missing assets.\n */\nexport async function buildClient(options: ClientBuildOptions): Promise<ClientBuildResult> {\n\tconst viteEntryPoint = await resolveProjectBinaryEntryPoint(options.projectRoot, 'vite', 'vite')\n\tif (!viteEntryPoint) {\n\t\tthrow new Error(\n\t\t\t`Could not find local Vite binary in ${options.projectRoot}. Install dependencies before deploying.`,\n\t\t)\n\t}\n\n\tconst args = [\n\t\tviteEntryPoint,\n\t\t'build',\n\t\t'--outDir',\n\t\toptions.outDir,\n\t\t'--mode',\n\t\toptions.mode ?? 'production',\n\t]\n\n\tawait runProcess(process.execPath, args, options.projectRoot)\n\tawait patchSqliteWasmAssets(options.projectRoot, options.outDir)\n\treturn { outDir: options.outDir }\n}\n\n/**\n * Ensures the SQLite WASM assets required for OPFS are present in the build output.\n *\n * 1. Copies the content-hashed `sqlite3-XXXX.wasm` to `sqlite3.wasm` (Emscripten's\n * locateFile expects the unhashed name).\n * 2. Copies `sqlite3-opfs-async-proxy.js` from node_modules (dynamically loaded by\n * sqlite3, invisible to Vite's bundler).\n */\nasync function patchSqliteWasmAssets(projectRoot: string, outDir: string): Promise<void> {\n\tconst assetsDir = join(outDir, 'assets')\n\tif (!existsSync(assetsDir)) return\n\n\tconst files = await readdir(assetsDir)\n\n\t// Copy hashed sqlite3 WASM to unhashed name\n\tconst hashedWasm = files.find((f) => /^sqlite3-.+\\.wasm$/.test(f))\n\tif (hashedWasm && !files.includes('sqlite3.wasm')) {\n\t\tawait copyFile(join(assetsDir, hashedWasm), join(assetsDir, 'sqlite3.wasm'))\n\t}\n\n\t// Copy OPFS async proxy worker\n\tif (!files.includes('sqlite3-opfs-async-proxy.js')) {\n\t\tconst proxyFile = resolve(\n\t\t\tprojectRoot,\n\t\t\t'node_modules',\n\t\t\t'@sqlite.org',\n\t\t\t'sqlite-wasm',\n\t\t\t'sqlite-wasm',\n\t\t\t'jswasm',\n\t\t\t'sqlite3-opfs-async-proxy.js',\n\t\t)\n\t\tif (existsSync(proxyFile)) {\n\t\t\tawait copyFile(proxyFile, join(assetsDir, 'sqlite3-opfs-async-proxy.js'))\n\t\t}\n\t}\n}\n\nasync function runProcess(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: 'inherit',\n\t\t\tenv: process.env,\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\n\t\t\treject(new Error(`Client build failed with exit code ${String(code ?? 'unknown')}.`))\n\t\t})\n\t})\n}\n","import { mkdir } from 'node:fs/promises'\nimport { access } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { build } from 'esbuild'\n\n/**\n * Options used to produce a deployable server bundle artifact.\n */\nexport interface ServerBundleOptions {\n\tprojectRoot: string\n\tdeployDirectory: string\n\tentryFileCandidates?: readonly string[]\n}\n\n/**\n * Result details for the generated server bundle artifact.\n */\nexport interface ServerBundleResult {\n\tentryFilePath: string\n\toutputFilePath: string\n}\n\nconst DEFAULT_ENTRY_CANDIDATES = [\n\t'server.ts',\n\t'server.js',\n\t'src/server.ts',\n\t'src/server.js',\n] as const\n/**\n * Bundles the server entry into a single deployable JavaScript file.\n */\nexport async function bundleServer(options: ServerBundleOptions): Promise<ServerBundleResult> {\n\tconst candidates = options.entryFileCandidates ?? DEFAULT_ENTRY_CANDIDATES\n\tconst entryFilePath = await resolveServerEntry(options.projectRoot, candidates)\n\tif (!entryFilePath) {\n\t\tthrow new Error(\n\t\t\t`Could not find a server entry file in ${options.projectRoot}. Looked for: ${candidates.join(', ')}`,\n\t\t)\n\t}\n\n\tawait mkdir(options.deployDirectory, { recursive: true })\n\tconst outputFilePath = join(options.deployDirectory, 'server-bundled.js')\n\n\tawait build({\n\t\tentryPoints: [entryFilePath],\n\t\toutfile: outputFilePath,\n\t\tbundle: true,\n\t\tplatform: 'node',\n\t\tformat: 'esm',\n\t\ttarget: ['node20'],\n\t\tsourcemap: false,\n\t\tlogLevel: 'silent',\n\t\texternal: ['better-sqlite3'],\n\t\tbanner: {\n\t\t\tjs: \"import { createRequire as __createRequire } from 'module'; const require = __createRequire(import.meta.url);\",\n\t\t},\n\t})\n\n\treturn {\n\t\tentryFilePath,\n\t\toutputFilePath,\n\t}\n}\n\nasync function resolveServerEntry(\n\tprojectRoot: string,\n\tcandidates: readonly string[],\n): Promise<string | null> {\n\tfor (const candidate of candidates) {\n\t\tconst fullPath = join(projectRoot, candidate)\n\t\ttry {\n\t\t\tawait access(fullPath)\n\t\t\treturn fullPath\n\t\t} catch {\n\t\t\t// continue scanning candidates\n\t\t}\n\t}\n\n\treturn null\n}\n","import { spawn } from 'node:child_process'\nimport { join } from 'node:path'\nimport { createLogger } from '../../../utils/logger'\nimport { writeRailwayJsonArtifact } from '../artifacts/railway-json-generator'\nimport { buildClient } from '../builder/client-builder'\nimport { bundleServer } from '../builder/server-bundler'\nimport type {\n\tBuildArtifacts,\n\tContextAwareDeployAdapter,\n\tDeployResult,\n\tDeploymentStatus,\n\tLogLine,\n\tLogOptions,\n\tProjectConfig,\n\tProvisionResult,\n} from './adapter'\n\n/**\n * Execution abstraction for Railway CLI shell interactions.\n */\nexport interface RailwayCommandRunner {\n\trun(command: string, args: string[], cwd: string): Promise<RailwayCommandResult>\n}\n\nexport interface RailwayCommandResult {\n\texitCode: number\n\tstdout: string\n\tstderr: string\n}\n\nexport interface RailwayAdapterOptions {\n\trunner?: RailwayCommandRunner\n\tcontext?: RailwayAdapterContext\n\tcommandCandidates?: readonly string[]\n}\n\n/**\n * Railway deploy adapter implementation for Phase 13.\n */\nexport class RailwayAdapter implements ContextAwareDeployAdapter {\n\tpublic readonly name = 'railway' as const\n\n\tprivate readonly logger = createLogger()\n\tprivate readonly runner: RailwayCommandRunner\n\tprivate readonly commandCandidates: readonly string[]\n\tprivate railwayCommand: string | null = null\n\tprivate currentContext: RailwayAdapterContext | null\n\tprivate lastDeploymentId: string | null = null\n\n\tpublic constructor(options: RailwayAdapterOptions = {}) {\n\t\tthis.runner = options.runner ?? new NodeRailwayCommandRunner()\n\t\tthis.commandCandidates = options.commandCandidates ?? DEFAULT_RAILWAY_COMMAND_CANDIDATES\n\t\tthis.currentContext = options.context ?? null\n\t}\n\n\tpublic setContext(context: RailwayAdapterContext): void {\n\t\tthis.currentContext = context\n\t}\n\n\tpublic async detect(): Promise<boolean> {\n\t\tconst command = await this.tryResolveRailwayCommand(process.cwd())\n\t\treturn command !== null\n\t}\n\n\tpublic async install(): Promise<void> {\n\t\tconst available = await this.detect()\n\t\tif (!available) {\n\t\t\tthrow new Error(\n\t\t\t\t'Railway CLI is required but not installed. Install with `npm i -g @railway/cli` or see https://docs.railway.com/guides/cli.',\n\t\t\t)\n\t\t}\n\t}\n\n\tpublic async authenticate(): Promise<void> {\n\t\tconst projectRoot = this.currentContext?.projectRoot ?? process.cwd()\n\t\tconst whoami = await this.runRailwayCommand(['whoami'], projectRoot, false)\n\t\tif (whoami.exitCode === 0) return\n\n\t\tconst login = await this.runRailwayCommand(['login'], projectRoot, true)\n\t\tif (login.exitCode !== 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Railway authentication failed: ${normalizeError(login.stderr, login.stdout)}`,\n\t\t\t)\n\t\t}\n\t}\n\n\tpublic async provision(config: ProjectConfig): Promise<ProvisionResult> {\n\t\tthis.currentContext = {\n\t\t\tprojectRoot: config.projectRoot,\n\t\t\tappName: config.appName,\n\t\t\tregion: config.region,\n\t\t}\n\n\t\tconst init = await this.runRailwayCommand(\n\t\t\t['init', '--name', config.appName, '--confirm'],\n\t\t\tconfig.projectRoot,\n\t\t\tfalse,\n\t\t)\n\t\tif (init.exitCode !== 0 && !isAlreadyExistsResponse(init.stderr, init.stdout)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Railway project provisioning failed for \"${config.appName}\": ${normalizeError(init.stderr, init.stdout)}`,\n\t\t\t)\n\t\t}\n\n\t\tconst link = await this.runRailwayCommand(\n\t\t\t['link', '--project', config.appName, '--environment', config.environment, '--yes'],\n\t\t\tconfig.projectRoot,\n\t\t\tfalse,\n\t\t)\n\t\tif (link.exitCode !== 0 && !isAlreadyExistsResponse(link.stderr, link.stdout)) {\n\t\t\tthrow new Error(`Railway link failed: ${normalizeError(link.stderr, link.stdout)}`)\n\t\t}\n\n\t\tconst vars: string[] = []\n\t\tconst setPort = await this.runRailwayCommand(\n\t\t\t['variables', 'set', 'PORT=3000', '--yes'],\n\t\t\tconfig.projectRoot,\n\t\t\tfalse,\n\t\t)\n\t\tif (setPort.exitCode === 0) {\n\t\t\tvars.push('PORT')\n\t\t}\n\n\t\treturn {\n\t\t\tapplicationId: config.appName,\n\t\t\tdatabaseId: null,\n\t\t\tsecretsSet: vars,\n\t\t}\n\t}\n\n\tpublic async build(config: ProjectConfig): Promise<BuildArtifacts> {\n\t\tthis.currentContext = {\n\t\t\tprojectRoot: config.projectRoot,\n\t\t\tappName: config.appName,\n\t\t\tregion: config.region,\n\t\t}\n\t\tconst deployDirectory = join(config.projectRoot, '.kora', 'deploy')\n\t\tawait writeRailwayJsonArtifact(deployDirectory, {\n\t\t\tappName: config.appName,\n\t\t\tenvironment: config.environment,\n\t\t})\n\n\t\tawait bundleServer({\n\t\t\tprojectRoot: config.projectRoot,\n\t\t\tdeployDirectory,\n\t\t})\n\t\tconst client = await buildClient({\n\t\t\tprojectRoot: config.projectRoot,\n\t\t\toutDir: join(deployDirectory, 'dist'),\n\t\t\tmode: 'production',\n\t\t})\n\n\t\treturn {\n\t\t\tclientDirectory: client.outDir,\n\t\t\tserverBundlePath: join(deployDirectory, 'server-bundled.js'),\n\t\t\tdeployDirectory,\n\t\t}\n\t}\n\n\tpublic async deploy(artifacts: BuildArtifacts): Promise<DeployResult> {\n\t\tconst context = this.requireContext()\n\t\tconst up = await this.runRailwayCommand(['up', '--yes'], artifacts.deployDirectory, true)\n\t\tif (up.exitCode !== 0) {\n\t\t\tthrow new Error(`Railway deployment failed: ${normalizeError(up.stderr, up.stdout)}`)\n\t\t}\n\n\t\tconst status = await this.runRailwayCommand(['status', '--json'], context.projectRoot, false)\n\t\tconst deploymentId = parseRailwayDeploymentId(status.stdout) ?? new Date().toISOString()\n\t\tconst liveUrl = parseRailwayUrl(status.stdout) ?? `https://${context.appName}.up.railway.app`\n\t\tthis.lastDeploymentId = deploymentId\n\n\t\treturn {\n\t\t\tdeploymentId,\n\t\t\tliveUrl,\n\t\t\tsyncUrl: toSyncUrl(liveUrl),\n\t\t}\n\t}\n\n\tpublic async rollback(deploymentId: string): Promise<void> {\n\t\tconst context = this.requireContext()\n\t\tconst rollback = await this.runRailwayCommand(\n\t\t\t['redeploy', '--deployment', deploymentId, '--yes'],\n\t\t\tcontext.projectRoot,\n\t\t\ttrue,\n\t\t)\n\t\tif (rollback.exitCode !== 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Railway rollback failed: ${normalizeError(rollback.stderr, rollback.stdout)}`,\n\t\t\t)\n\t\t}\n\t}\n\n\tpublic async *logs(options: LogOptions): AsyncIterable<LogLine> {\n\t\tconst context = this.requireContext()\n\t\tconst args = ['logs']\n\t\tif (typeof options.tail === 'number' && options.tail > 0) {\n\t\t\targs.push('--lines', String(options.tail))\n\t\t}\n\n\t\tconst result = await this.runRailwayCommand(args, context.projectRoot, false)\n\t\tif (result.exitCode !== 0) {\n\t\t\tthrow new Error(`Railway logs failed: ${normalizeError(result.stderr, result.stdout)}`)\n\t\t}\n\n\t\tconst lines = result.stdout.split(/\\r?\\n/).filter((line) => line.length > 0)\n\t\tfor (const line of lines) {\n\t\t\tyield {\n\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\tlevel: inferLogLevel(line),\n\t\t\t\tmessage: line,\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async status(): Promise<DeploymentStatus> {\n\t\tconst context = this.requireContext()\n\t\tconst status = await this.runRailwayCommand(['status', '--json'], context.projectRoot, false)\n\t\tif (status.exitCode !== 0) {\n\t\t\treturn {\n\t\t\t\tstate: 'failed',\n\t\t\t\tmessage: normalizeError(status.stderr, status.stdout),\n\t\t\t}\n\t\t}\n\n\t\tconst liveUrl = parseRailwayUrl(status.stdout)\n\t\treturn {\n\t\t\tstate: 'healthy',\n\t\t\tmessage: 'Railway deployment is healthy.',\n\t\t\tliveUrl: liveUrl ?? undefined,\n\t\t}\n\t}\n\n\tprivate async runRailwayCommand(\n\t\trailwayArgs: string[],\n\t\tcwd: string,\n\t\tinheritOutput: boolean,\n\t): Promise<RailwayCommandResult> {\n\t\tconst command = await this.resolveRailwayCommand(cwd)\n\t\tif (inheritOutput) {\n\t\t\tthis.logger.step(`railway ${railwayArgs.join(' ')}`)\n\t\t}\n\t\treturn await this.runner.run(command, railwayArgs, cwd)\n\t}\n\n\tprivate requireContext(): RailwayAdapterContext {\n\t\tif (!this.currentContext) {\n\t\t\tthrow new Error('Railway adapter context is not initialized. Run provision() first.')\n\t\t}\n\t\treturn this.currentContext\n\t}\n\n\tprivate async resolveRailwayCommand(cwd: string): Promise<string> {\n\t\tif (this.railwayCommand) {\n\t\t\treturn this.railwayCommand\n\t\t}\n\t\tconst resolved = await this.tryResolveRailwayCommand(cwd)\n\t\tif (!resolved) {\n\t\t\tthrow new Error('Could not resolve a usable Railway CLI command (tried railway).')\n\t\t}\n\t\tthis.railwayCommand = resolved\n\t\treturn resolved\n\t}\n\n\tprivate async tryResolveRailwayCommand(cwd: string): Promise<string | null> {\n\t\tfor (const command of this.commandCandidates) {\n\t\t\tconst version = await this.runner.run(command, ['--version'], cwd)\n\t\t\tif (version.exitCode === 0) {\n\t\t\t\treturn command\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\n/**\n * Default subprocess-backed runner for Railway commands.\n */\nexport class NodeRailwayCommandRunner implements RailwayCommandRunner {\n\tpublic async run(command: string, args: string[], cwd: string): Promise<RailwayCommandResult> {\n\t\treturn await new Promise<RailwayCommandResult>((resolve) => {\n\t\t\tconst child = spawn(command, args, {\n\t\t\t\tcwd,\n\t\t\t\tenv: process.env,\n\t\t\t\tstdio: ['ignore', 'pipe', 'pipe'],\n\t\t\t})\n\n\t\t\tlet stdout = ''\n\t\t\tlet stderr = ''\n\t\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\t\tstdout += chunk.toString('utf-8')\n\t\t\t})\n\t\t\tchild.stderr?.on('data', (chunk: Buffer) => {\n\t\t\t\tstderr += chunk.toString('utf-8')\n\t\t\t})\n\t\t\tchild.on('error', (error) => {\n\t\t\t\tresolve({\n\t\t\t\t\texitCode: 1,\n\t\t\t\t\tstdout,\n\t\t\t\t\tstderr: `${stderr}\\n${error.message}`,\n\t\t\t\t})\n\t\t\t})\n\t\t\tchild.on('exit', (code) => {\n\t\t\t\tresolve({\n\t\t\t\t\texitCode: code ?? 1,\n\t\t\t\t\tstdout: stdout.trim(),\n\t\t\t\t\tstderr: stderr.trim(),\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t}\n}\n\nexport interface RailwayAdapterContext {\n\tprojectRoot: string\n\tappName: string\n\tregion: string | null\n}\n\nconst DEFAULT_RAILWAY_COMMAND_CANDIDATES = ['railway'] as const\n\nfunction parseRailwayUrl(rawJson: string): string | null {\n\tconst record = parseJsonRecord(rawJson)\n\tif (!record) return null\n\n\tconst url = record.url\n\tif (typeof url === 'string' && url.length > 0) {\n\t\treturn ensureHttpsUrl(url)\n\t}\n\n\tconst service = record.service\n\tif (typeof service === 'object' && service !== null) {\n\t\tconst domain = (service as Record<string, unknown>).domain\n\t\tif (typeof domain === 'string' && domain.length > 0) {\n\t\t\treturn ensureHttpsUrl(domain)\n\t\t}\n\t}\n\n\treturn null\n}\n\nfunction parseRailwayDeploymentId(rawJson: string): string | null {\n\tconst record = parseJsonRecord(rawJson)\n\tif (!record) return null\n\n\tconst deploymentId = record.deploymentId\n\tif (typeof deploymentId === 'string' && deploymentId.length > 0) {\n\t\treturn deploymentId\n\t}\n\n\tconst deployment = record.deployment\n\tif (typeof deployment === 'object' && deployment !== null) {\n\t\tconst id = (deployment as Record<string, unknown>).id\n\t\tif (typeof id === 'string' && id.length > 0) {\n\t\t\treturn id\n\t\t}\n\t}\n\n\treturn null\n}\n\nfunction parseJsonRecord(value: string): Record<string, unknown> | null {\n\ttry {\n\t\tconst parsed = JSON.parse(value) as unknown\n\t\tif (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {\n\t\t\treturn parsed as Record<string, unknown>\n\t\t}\n\t\treturn null\n\t} catch {\n\t\treturn null\n\t}\n}\n\nfunction toSyncUrl(liveUrl: string): string | null {\n\ttry {\n\t\tconst url = new URL(liveUrl)\n\t\turl.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'\n\t\turl.pathname = '/kora-sync'\n\t\treturn url.toString().replace(/\\/$/, '')\n\t} catch {\n\t\treturn null\n\t}\n}\n\nfunction ensureHttpsUrl(value: string): string {\n\tif (value.startsWith('http://') || value.startsWith('https://')) {\n\t\treturn value\n\t}\n\treturn `https://${value}`\n}\n\nfunction inferLogLevel(line: string): LogLine['level'] {\n\tconst normalized = line.toLowerCase()\n\tif (normalized.includes('error')) return 'error'\n\tif (normalized.includes('warn')) return 'warn'\n\tif (normalized.includes('debug')) return 'debug'\n\treturn 'info'\n}\n\nfunction normalizeError(stderr: string, stdout: string): string {\n\tif (stderr.length > 0) return stderr\n\tif (stdout.length > 0) return stdout\n\treturn 'unknown railway CLI error'\n}\n\nfunction isAlreadyExistsResponse(stderr: string, stdout: string): boolean {\n\tconst text = `${stderr}\\n${stdout}`.toLowerCase()\n\treturn text.includes('already exists')\n}\n","import { mkdir, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nconst GENERATED_HEADER = 'Generated by kora deploy - do not edit manually.'\n\n/**\n * Configuration used to render `railway.json`.\n */\nexport interface RailwayJsonOptions {\n\tappName: string\n\tregion?: string\n\tenvironment?: string\n\tstartCommand?: string\n\thealthcheckPath?: string\n}\n\ninterface RailwayJsonFile {\n\t$schema: string\n\tbuild: {\n\t\tbuilder: string\n\t\tdockerfilePath: string\n\t}\n\tdeploy: {\n\t\tstartCommand: string\n\t\thealthcheckPath: string\n\t\trestartPolicyType: 'on_failure'\n\t\trestartPolicyMaxRetries: number\n\t}\n\tmetadata: {\n\t\tgeneratedBy: string\n\t\tappName: string\n\t\tregion: string | undefined\n\t}\n}\n\n/**\n * Generates Railway deployment configuration in JSON format.\n */\nexport function generateRailwayJson(options: RailwayJsonOptions): string {\n\tconst file: RailwayJsonFile = {\n\t\t$schema: 'https://railway.app/railway.schema.json',\n\t\tbuild: {\n\t\t\tbuilder: 'DOCKERFILE',\n\t\t\tdockerfilePath: 'Dockerfile',\n\t\t},\n\t\tdeploy: {\n\t\t\tstartCommand: options.startCommand ?? 'node ./server-bundled.js',\n\t\t\thealthcheckPath: options.healthcheckPath ?? '/health',\n\t\t\trestartPolicyType: 'on_failure',\n\t\t\trestartPolicyMaxRetries: 3,\n\t\t},\n\t\tmetadata: {\n\t\t\tgeneratedBy: GENERATED_HEADER,\n\t\t\tappName: options.appName,\n\t\t\tregion: options.region,\n\t\t},\n\t}\n\n\treturn `${JSON.stringify(file, null, 2)}\\n`\n}\n\n/**\n * Writes `railway.json` into `.kora/deploy`.\n */\nexport async function writeRailwayJsonArtifact(\n\tdeployDirectory: string,\n\toptions: RailwayJsonOptions,\n): Promise<string> {\n\tawait mkdir(deployDirectory, { recursive: true })\n\tconst filePath = join(deployDirectory, 'railway.json')\n\tawait writeFile(filePath, generateRailwayJson(options), 'utf-8')\n\treturn filePath\n}\n","import type {\n\tBuildArtifacts,\n\tContextAwareDeployAdapter,\n\tDeployPlatform,\n\tDeployResult,\n\tDeploymentStatus,\n\tLogLine,\n\tLogOptions,\n\tProjectConfig,\n\tProvisionResult,\n} from './adapter'\n\n/**\n * Lightweight scaffold adapter used for platforms not yet implemented.\n * It provides explicit, deterministic errors while preserving the shared\n * adapter contract and command wiring across all platforms.\n */\nexport class StubDeployAdapter implements ContextAwareDeployAdapter {\n\tpublic readonly name: DeployPlatform\n\tprivate readonly contextLabel: string\n\n\tpublic constructor(platform: DeployPlatform) {\n\t\tthis.name = platform\n\t\tthis.contextLabel = `Deploy adapter \"${platform}\" is not implemented yet.`\n\t}\n\n\tpublic setContext(_context: {\n\t\tprojectRoot: string\n\t\tappName: string\n\t\tregion: string | null\n\t}): void {\n\t\t// Context is intentionally ignored for stub implementations.\n\t}\n\n\tpublic async detect(): Promise<boolean> {\n\t\treturn false\n\t}\n\n\tpublic async install(): Promise<void> {\n\t\tthrow this.notImplementedError()\n\t}\n\n\tpublic async authenticate(): Promise<void> {\n\t\tthrow this.notImplementedError()\n\t}\n\n\tpublic async provision(_config: ProjectConfig): Promise<ProvisionResult> {\n\t\tthrow this.notImplementedError()\n\t}\n\n\tpublic async build(_config: ProjectConfig): Promise<BuildArtifacts> {\n\t\tthrow this.notImplementedError()\n\t}\n\n\tpublic async deploy(_artifacts: BuildArtifacts): Promise<DeployResult> {\n\t\tthrow this.notImplementedError()\n\t}\n\n\tpublic async rollback(_deploymentId: string): Promise<void> {\n\t\tthrow this.notImplementedError()\n\t}\n\n\tpublic logs(_options: LogOptions): AsyncIterable<LogLine> {\n\t\tthrow this.notImplementedError()\n\t}\n\n\tpublic async status(): Promise<DeploymentStatus> {\n\t\treturn {\n\t\t\tstate: 'unknown',\n\t\t\tmessage: this.notImplementedMessage(),\n\t\t}\n\t}\n\n\tprivate notImplementedError(): Error {\n\t\treturn new Error(this.notImplementedMessage())\n\t}\n\n\tprivate notImplementedMessage(): string {\n\t\treturn `${this.contextLabel} Start with --platform fly for now.`\n\t}\n}\n","import type { DeployAdapter, DeployPlatform } from './adapter'\nimport { FlyAdapter } from './fly-adapter'\nimport { RailwayAdapter } from './railway-adapter'\nimport { StubDeployAdapter } from './stub-adapter'\n\n/**\n * Creates a deploy adapter instance for the selected platform.\n */\nexport function createDeployAdapter(platform: DeployPlatform): DeployAdapter {\n\tswitch (platform) {\n\t\tcase 'fly':\n\t\t\treturn new FlyAdapter()\n\t\tcase 'railway':\n\t\t\treturn new RailwayAdapter()\n\t\tcase 'render':\n\t\tcase 'docker':\n\t\tcase 'kora-cloud':\n\t\t\treturn new StubDeployAdapter(platform)\n\t\tdefault: {\n\t\t\tconst exhaustiveCheck: never = platform\n\t\t\treturn exhaustiveCheck\n\t\t}\n\t}\n}\n","import { mkdir, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nconst GENERATED_HEADER = '# Generated by kora deploy — do not edit manually'\n\n/**\n * Configuration for generating a production Dockerfile.\n */\nexport interface DockerfileOptions {\n\tnodeVersion?: string\n\tport?: number\n\tclientDirectory?: string\n\tserverBundleFile?: string\n\t/** Native modules that must be installed at runtime (externalized from bundle). */\n\tnativeDependencies?: Record<string, string>\n}\n\n/**\n * Generates a multi-stage Dockerfile for Kora deployments.\n *\n * The generated image expects artifacts produced under `.kora/deploy`:\n * - `dist/` for client assets\n * - `server-bundled.js` for server runtime entry\n * - `package.json` (if native dependencies are needed)\n */\nexport function generateDockerfile(options: DockerfileOptions = {}): string {\n\tconst nodeVersion = options.nodeVersion ?? '20-alpine'\n\tconst port = options.port ?? 3000\n\tconst clientDirectory = options.clientDirectory ?? 'dist'\n\tconst serverBundleFile = options.serverBundleFile ?? 'server-bundled.js'\n\tconst hasNativeDeps =\n\t\toptions.nativeDependencies && Object.keys(options.nativeDependencies).length > 0\n\n\tconst lines: string[] = [\n\t\tGENERATED_HEADER,\n\t\t'',\n\t\t`FROM node:${nodeVersion} AS runtime`,\n\t\t'WORKDIR /app',\n\t\t'ENV NODE_ENV=production',\n\t\t`ENV PORT=${String(port)}`,\n\t\t'',\n\t]\n\n\tif (hasNativeDeps) {\n\t\t// Alpine needs build tools for native modules like better-sqlite3\n\t\tlines.push('# Install build tools for native modules')\n\t\tlines.push('RUN apk add --no-cache python3 make g++')\n\t\tlines.push('')\n\t\tlines.push('COPY package.json ./package.json')\n\t\tlines.push('RUN npm install --omit=dev')\n\t\tlines.push('')\n\t}\n\n\tlines.push(`COPY ${clientDirectory} ./dist`)\n\tlines.push(`COPY ${serverBundleFile} ./server-bundled.js`)\n\tlines.push('')\n\tlines.push(`EXPOSE ${String(port)}`)\n\tlines.push('CMD [\"node\", \"./server-bundled.js\"]')\n\tlines.push('')\n\n\treturn lines.join('\\n')\n}\n\n/**\n * Generates a minimal package.json for native dependencies in the deploy container.\n */\nexport function generateDeployPackageJson(\n\tnativeDependencies: Record<string, string>,\n): string {\n\tconst pkg = {\n\t\tname: 'kora-deploy',\n\t\tversion: '1.0.0',\n\t\tprivate: true,\n\t\ttype: 'module',\n\t\tdependencies: nativeDependencies,\n\t}\n\treturn JSON.stringify(pkg, null, 2) + '\\n'\n}\n\n/**\n * Generates a `.dockerignore` tuned for Kora deploy output.\n */\nexport function generateDockerIgnore(): string {\n\treturn [\n\t\tGENERATED_HEADER,\n\t\t'',\n\t\t'node_modules',\n\t\t'npm-debug.log*',\n\t\t'pnpm-debug.log*',\n\t\t'yarn-error.log*',\n\t\t'.env',\n\t\t'.env.*',\n\t\t'.git',\n\t\t'.gitignore',\n\t\t'coverage',\n\t\t'.turbo',\n\t\t'*.test.ts',\n\t\t'*.spec.ts',\n\t\t'',\n\t].join('\\n')\n}\n\n/**\n * Writes the generated Dockerfile (and package.json if needed) to `.kora/deploy/`.\n */\nexport async function writeDockerfileArtifact(\n\tdeployDirectory: string,\n\toptions: DockerfileOptions = {},\n): Promise<string> {\n\tawait mkdir(deployDirectory, { recursive: true })\n\tconst dockerfilePath = join(deployDirectory, 'Dockerfile')\n\tawait writeFile(dockerfilePath, generateDockerfile(options), 'utf-8')\n\n\tif (options.nativeDependencies && Object.keys(options.nativeDependencies).length > 0) {\n\t\tconst pkgJsonPath = join(deployDirectory, 'package.json')\n\t\tawait writeFile(pkgJsonPath, generateDeployPackageJson(options.nativeDependencies), 'utf-8')\n\t}\n\n\treturn dockerfilePath\n}\n\n/**\n * Writes the generated `.dockerignore` to `.kora/deploy/.dockerignore`.\n */\nexport async function writeDockerIgnoreArtifact(deployDirectory: string): Promise<string> {\n\tawait mkdir(deployDirectory, { recursive: true })\n\tconst dockerIgnorePath = join(deployDirectory, '.dockerignore')\n\tawait writeFile(dockerIgnorePath, generateDockerIgnore(), 'utf-8')\n\treturn dockerIgnorePath\n}\n","import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { DeployPlatform } from '../adapters/adapter'\nimport { isDeployPlatform } from '../adapters/adapter'\n\nconst KORA_DEPLOY_DIRECTORY = join('.kora', 'deploy')\nconst DEPLOY_STATE_FILENAME = 'deploy.json'\n\n/**\n * Durable deployment settings stored for subsequent `kora deploy` runs.\n */\nexport interface DeployState {\n\tplatform: DeployPlatform\n\tappName: string\n\tregion: string | null\n\tprojectRoot: string\n\tliveUrl: string | null\n\tsyncUrl: string | null\n\tdatabaseId: string | null\n\tlastDeploymentId: string | null\n\tcreatedAt: string\n\tupdatedAt: string\n}\n\n/**\n * Input required to create a new deployment state record.\n */\nexport interface DeployStateCreateInput {\n\tplatform: DeployPlatform\n\tappName: string\n\tregion: string | null\n\tprojectRoot: string\n\tliveUrl?: string | null\n\tsyncUrl?: string | null\n\tdatabaseId?: string | null\n\tlastDeploymentId?: string | null\n}\n\n/**\n * Partial update fields for an existing deployment state record.\n */\nexport interface DeployStatePatch {\n\tplatform?: DeployPlatform\n\tappName?: string\n\tregion?: string | null\n\tprojectRoot?: string\n\tliveUrl?: string | null\n\tsyncUrl?: string | null\n\tdatabaseId?: string | null\n\tlastDeploymentId?: string | null\n}\n\n/**\n * Returns the absolute path to `.kora/deploy`.\n */\nexport function resolveDeployDirectory(projectRoot: string): string {\n\treturn join(projectRoot, KORA_DEPLOY_DIRECTORY)\n}\n\n/**\n * Returns the absolute path to `.kora/deploy/deploy.json`.\n */\nexport function resolveDeployStatePath(projectRoot: string): string {\n\treturn join(resolveDeployDirectory(projectRoot), DEPLOY_STATE_FILENAME)\n}\n\n/**\n * Loads deployment state from `.kora/deploy/deploy.json`.\n * Returns null when the file does not exist.\n */\nexport async function readDeployState(projectRoot: string): Promise<DeployState | null> {\n\tconst statePath = resolveDeployStatePath(projectRoot)\n\n\ttry {\n\t\tconst source = await readFile(statePath, 'utf-8')\n\t\tconst parsed = JSON.parse(source) as unknown\n\t\treturn parseDeployState(parsed)\n\t} catch (error) {\n\t\tconst code = (error as NodeJS.ErrnoException).code\n\t\tif (code === 'ENOENT') return null\n\t\tthrow error\n\t}\n}\n\n/**\n * Writes a brand-new deployment state record, replacing any existing file.\n */\nexport async function writeDeployState(\n\tprojectRoot: string,\n\tinput: DeployStateCreateInput,\n\tnow = new Date(),\n): Promise<DeployState> {\n\tconst timestamp = now.toISOString()\n\tconst state: DeployState = {\n\t\tplatform: input.platform,\n\t\tappName: input.appName,\n\t\tregion: input.region,\n\t\tprojectRoot: input.projectRoot,\n\t\tliveUrl: input.liveUrl ?? null,\n\t\tsyncUrl: input.syncUrl ?? null,\n\t\tdatabaseId: input.databaseId ?? null,\n\t\tlastDeploymentId: input.lastDeploymentId ?? null,\n\t\tcreatedAt: timestamp,\n\t\tupdatedAt: timestamp,\n\t}\n\n\tawait persistDeployState(projectRoot, state)\n\treturn state\n}\n\n/**\n * Applies a partial update to deployment state.\n * Throws when state does not exist.\n */\nexport async function updateDeployState(\n\tprojectRoot: string,\n\tpatch: DeployStatePatch,\n\tnow = new Date(),\n): Promise<DeployState> {\n\tconst existing = await readDeployState(projectRoot)\n\tif (!existing) {\n\t\tthrow new Error('Cannot update deploy state because deploy.json does not exist yet.')\n\t}\n\n\tconst nextState: DeployState = {\n\t\tplatform: patch.platform ?? existing.platform,\n\t\tappName: patch.appName ?? existing.appName,\n\t\tregion: patch.region === undefined ? existing.region : patch.region,\n\t\tprojectRoot: patch.projectRoot ?? existing.projectRoot,\n\t\tliveUrl: patch.liveUrl === undefined ? existing.liveUrl : patch.liveUrl,\n\t\tsyncUrl: patch.syncUrl === undefined ? existing.syncUrl : patch.syncUrl,\n\t\tdatabaseId: patch.databaseId === undefined ? existing.databaseId : patch.databaseId,\n\t\tlastDeploymentId:\n\t\t\tpatch.lastDeploymentId === undefined ? existing.lastDeploymentId : patch.lastDeploymentId,\n\t\tcreatedAt: existing.createdAt,\n\t\tupdatedAt: now.toISOString(),\n\t}\n\n\tawait persistDeployState(projectRoot, nextState)\n\treturn nextState\n}\n\n/**\n * Removes the entire `.kora/deploy` directory tree.\n */\nexport async function resetDeployState(projectRoot: string): Promise<void> {\n\tawait rm(resolveDeployDirectory(projectRoot), { recursive: true, force: true })\n}\n\nasync function persistDeployState(projectRoot: string, state: DeployState): Promise<void> {\n\tconst deployDir = resolveDeployDirectory(projectRoot)\n\tconst statePath = resolveDeployStatePath(projectRoot)\n\tawait mkdir(deployDir, { recursive: true })\n\tawait writeFile(statePath, `${JSON.stringify(state, null, 2)}\\n`, 'utf-8')\n}\n\nfunction parseDeployState(value: unknown): DeployState {\n\tif (typeof value !== 'object' || value === null || Array.isArray(value)) {\n\t\tthrow new Error('Invalid deploy state: expected an object.')\n\t}\n\n\tconst record = value as Record<string, unknown>\n\n\tconst platform = readPlatform(record.platform)\n\tconst appName = readString(record.appName, 'appName')\n\tconst region = readOptionalString(record.region, 'region')\n\tconst projectRoot = readString(record.projectRoot, 'projectRoot')\n\tconst liveUrl = readOptionalString(record.liveUrl, 'liveUrl')\n\tconst syncUrl = readOptionalString(record.syncUrl, 'syncUrl')\n\tconst databaseId = readOptionalString(record.databaseId, 'databaseId')\n\tconst lastDeploymentId = readOptionalString(record.lastDeploymentId, 'lastDeploymentId')\n\tconst createdAt = readString(record.createdAt, 'createdAt')\n\tconst updatedAt = readString(record.updatedAt, 'updatedAt')\n\n\treturn {\n\t\tplatform,\n\t\tappName,\n\t\tregion,\n\t\tprojectRoot,\n\t\tliveUrl,\n\t\tsyncUrl,\n\t\tdatabaseId,\n\t\tlastDeploymentId,\n\t\tcreatedAt,\n\t\tupdatedAt,\n\t}\n}\n\nfunction readPlatform(value: unknown): DeployPlatform {\n\tif (typeof value !== 'string' || !isDeployPlatform(value)) {\n\t\tthrow new Error('Invalid deploy state: \"platform\" must be a supported platform.')\n\t}\n\treturn value\n}\n\nfunction readString(value: unknown, field: string): string {\n\tif (typeof value !== 'string' || value.length === 0) {\n\t\tthrow new Error(`Invalid deploy state: \"${field}\" must be a non-empty string.`)\n\t}\n\treturn value\n}\n\nfunction readOptionalString(value: unknown, field: string): string | null {\n\tif (value === null) return null\n\tif (typeof value === 'string') return value\n\tthrow new Error(`Invalid deploy state: \"${field}\" must be a string or null.`)\n}\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 type { FieldDescriptor, FieldKind, SchemaDefinition } from '@korajs/core'\n\n/**\n * Generates TypeScript interfaces from a SchemaDefinition.\n * For each collection, produces three interfaces:\n * - {Name}Record: full record type (all fields + id)\n * - {Name}InsertInput: insert input (omit auto fields, optional for fields with defaults)\n * - {Name}UpdateInput: update input (all non-auto fields optional)\n *\n * @param schema - A validated SchemaDefinition from defineSchema()\n * @returns A complete TypeScript file as a string\n */\nexport function generateTypes(schema: SchemaDefinition): string {\n\tconst lines: string[] = [\n\t\t'// Auto-generated by @korajs/cli — do not edit manually',\n\t\t`// Generated from schema version ${String(schema.version)}`,\n\t\t'',\n\t]\n\n\tconst collectionNames = Object.keys(schema.collections)\n\tif (collectionNames.length === 0) {\n\t\treturn lines.join('\\n')\n\t}\n\n\tfor (const [name, collection] of Object.entries(schema.collections)) {\n\t\tconst pascal = toPascalCase(name)\n\t\tconst fields = collection.fields\n\n\t\t// Record type: all fields + id\n\t\tlines.push(`export interface ${pascal}Record {`)\n\t\tlines.push('\\treadonly id: string')\n\t\tfor (const [fieldName, descriptor] of Object.entries(fields)) {\n\t\t\tconst tsType = fieldKindToTypeScript(descriptor)\n\t\t\tconst optional = !descriptor.required && !descriptor.auto ? '?' : ''\n\t\t\tlines.push(`\\treadonly ${fieldName}${optional}: ${tsType}`)\n\t\t}\n\t\tlines.push('}')\n\t\tlines.push('')\n\n\t\t// Insert input: omit auto fields, optional for fields with defaults\n\t\tlines.push(`export interface ${pascal}InsertInput {`)\n\t\tfor (const [fieldName, descriptor] of Object.entries(fields)) {\n\t\t\tif (descriptor.auto) continue\n\t\t\tconst tsType = fieldKindToTypeScript(descriptor)\n\t\t\tconst optional = !descriptor.required || descriptor.defaultValue !== undefined ? '?' : ''\n\t\t\tlines.push(`\\t${fieldName}${optional}: ${tsType}`)\n\t\t}\n\t\tlines.push('}')\n\t\tlines.push('')\n\n\t\t// Update input: all non-auto fields optional\n\t\tlines.push(`export interface ${pascal}UpdateInput {`)\n\t\tfor (const [fieldName, descriptor] of Object.entries(fields)) {\n\t\t\tif (descriptor.auto) continue\n\t\t\tconst tsType = fieldKindToTypeScript(descriptor)\n\t\t\tlines.push(`\\t${fieldName}?: ${tsType}`)\n\t\t}\n\t\tlines.push('}')\n\t\tlines.push('')\n\t}\n\n\treturn lines.join('\\n')\n}\n\n/** Maps a FieldDescriptor to its TypeScript type string */\nfunction fieldKindToTypeScript(descriptor: FieldDescriptor): string {\n\tswitch (descriptor.kind) {\n\t\tcase 'string':\n\t\t\treturn 'string'\n\t\tcase 'number':\n\t\t\treturn 'number'\n\t\tcase 'boolean':\n\t\t\treturn 'boolean'\n\t\tcase 'timestamp':\n\t\t\treturn 'number'\n\t\tcase 'richtext':\n\t\t\treturn 'string'\n\t\tcase 'enum': {\n\t\t\tif (descriptor.enumValues && descriptor.enumValues.length > 0) {\n\t\t\t\treturn descriptor.enumValues.map((v) => `'${v}'`).join(' | ')\n\t\t\t}\n\t\t\treturn 'string'\n\t\t}\n\t\tcase 'array': {\n\t\t\tconst itemType = itemKindToTypeScript(descriptor.itemKind)\n\t\t\treturn `Array<${itemType}>`\n\t\t}\n\t\tdefault:\n\t\t\treturn 'unknown'\n\t}\n}\n\n/** Maps an item FieldKind to its TypeScript type string */\nfunction itemKindToTypeScript(kind: FieldKind | null): string {\n\tswitch (kind) {\n\t\tcase 'string':\n\t\t\treturn 'string'\n\t\tcase 'number':\n\t\t\treturn 'number'\n\t\tcase 'boolean':\n\t\t\treturn 'boolean'\n\t\tcase 'timestamp':\n\t\t\treturn 'number'\n\t\tcase 'richtext':\n\t\t\treturn 'string'\n\t\tcase 'enum':\n\t\t\treturn 'string'\n\t\tcase 'array':\n\t\t\treturn 'unknown[]'\n\t\tdefault:\n\t\t\treturn 'unknown'\n\t}\n}\n\n/** Converts a snake_case or kebab-case name to PascalCase */\nfunction toPascalCase(name: string): string {\n\treturn name\n\t\t.split(/[_-]/)\n\t\t.map((part) => {\n\t\t\tif (part.length === 0) return ''\n\t\t\tconst first = part[0]\n\t\t\treturn first ? first.toUpperCase() + part.slice(1) : ''\n\t\t})\n\t\t.join('')\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,IAAAA,gBAAuC;;;ACAvC,IAAAC,6BAAyB;AACzB,IAAAC,kBAAyC;AACzC,IAAAC,oBAAiC;AACjC,IAAAC,mBAA8B;AAC9B,mBAA8B;;;ACJ9B,kBAA0B;AAenB,IAAM,qBAAN,cAAiC,sBAAU;AAAA,EACjD,YAA4B,WAAmB;AAC9C;AAAA,MACC,cAAc,SAAS;AAAA,MACvB;AAAA,MACA,EAAE,UAAU;AAAA,IACb;AAL2B;AAM3B,SAAK,OAAO;AAAA,EACb;AAAA,EAP4B;AAQ7B;AAKO,IAAM,sBAAN,cAAkC,sBAAU;AAAA,EAClD,YAA4B,eAAyB;AACpD;AAAA,MACC,2CAA2C,cAAc,KAAK,IAAI,CAAC;AAAA,MACnE;AAAA,MACA,EAAE,cAAc;AAAA,IACjB;AAL2B;AAM3B,SAAK,OAAO;AAAA,EACb;AAAA,EAP4B;AAQ7B;AAKO,IAAM,sBAAN,cAAkC,sBAAU;AAAA,EAClD,YAA4B,WAAmB;AAC9C;AAAA,MACC,IAAI,SAAS;AAAA,MACb;AAAA,MACA,EAAE,UAAU;AAAA,IACb;AAL2B;AAM3B,SAAK,OAAO;AAAA,EACb;AAAA,EAP4B;AAQ7B;AAKO,IAAM,iBAAN,cAA6B,sBAAU;AAAA,EAC7C,YACiB,QACA,YACf;AACD;AAAA,MACC,mCAAmC,MAAM,QAAQ,UAAU;AAAA,MAC3D;AAAA,MACA,EAAE,QAAQ,WAAW;AAAA,IACtB;AAPgB;AACA;AAOhB,SAAK,OAAO;AAAA,EACb;AAAA,EATiB;AAAA,EACA;AASlB;;;ACrEA,kBAAiB;AAcjB,IAAM,sB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,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,SAAS;AAAA,EACV;AACD,CAAC;AAAA,IAED,uBAAQ,IAAI;","names":["import_citty","import_node_child_process","import_node_fs","import_node_path","import_node_url","Conf","resolve","clackText","clackIsCancel","clackCancel","clackSelect","clackConfirm","clackIntro","clackOutro","import_promises","import_node_path","validateNpmPackageName","import_promises","import_node_path","import_promises","import_node_path","import_meta","isSyncTemplate","import_node_path","import_citty","import_node_child_process","import_node_path","import_promises","import_node_path","import_node_child_process","import_promises","import_node_fs","import_node_path","resolve","import_promises","import_node_path","resolve","import_node_child_process","import_node_path","import_promises","import_node_path","GENERATED_HEADER","normalizeError","isAlreadyExistsResponse","inferLogLevel","resolve","parseJsonRecord","import_promises","import_node_path","GENERATED_HEADER","import_promises","import_node_path","import_promises","import_node_path","import_citty","import_node_child_process","import_promises","import_node_path","import_node_url","loaded","resolve","import_node_child_process","spawnChild","resolve","import_node_child_process","import_node_fs","import_node_path","resolve","fileExists","resolve","import_promises","import_node_path","import_citty","import_promises","import_node_path","import_citty","import_core","import_meta","sqlLiteral","import_node_child_process","import_node_path","import_node_url","extractSchema","isSchemaDefinition","runCommand","resolve","isInteractiveTerminal"]}
|