@korajs/cli 0.3.0 → 0.3.1

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/types.ts","../src/errors.ts","../src/commands/generate/type-generator.ts","../src/commands/deploy/deploy-command.ts","../src/prompts/prompt-client.ts","../src/utils/prompt.ts","../src/utils/fs-helpers.ts","../src/utils/logger.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/create/project-name.ts","../src/commands/create/options.ts","../src/prompts/preferences.ts","../src/commands/create/preferences-flow.ts","../src/commands/create/sync-provider-preset.ts"],"sourcesContent":["// @korajs/cli — public API\n// Every export here is a public API commitment. Be explicit.\n\n// === Types ===\nexport type { PackageManager, TemplateName, TemplateContext, TemplateInfo } from './types'\nexport { PACKAGE_MANAGERS, TEMPLATES, TEMPLATE_INFO } from './types'\n\n// === Errors ===\nexport {\n\tCliError,\n\tDevServerError,\n\tInvalidProjectError,\n\tProjectExistsError,\n\tSchemaNotFoundError,\n} from './errors'\n\n// === Type Generation (programmatic use) ===\nexport { generateTypes } from './commands/generate/type-generator'\nexport { deployCommand } from './commands/deploy/deploy-command'\nexport {\n\tDEPLOY_PLATFORMS,\n\tisDeployPlatform,\n\ttype ContextAwareDeployAdapter,\n\ttype BuildArtifacts,\n\ttype DeployAdapter,\n\ttype DeployPlatform,\n\ttype DeploymentStatus,\n\ttype DeployResult,\n\ttype LogLine,\n\ttype LogOptions,\n\ttype ProjectConfig,\n\ttype ProvisionResult,\n} from './commands/deploy/adapters/adapter'\nexport {\n\tFlyAdapter,\n\tNodeFlyCommandRunner,\n\ttype FlyAdapterContext,\n\ttype FlyAdapterOptions,\n\ttype FlyCommandResult,\n\ttype FlyCommandRunner,\n} from './commands/deploy/adapters/fly-adapter'\nexport { createDeployAdapter } from './commands/deploy/adapters/factory'\nexport {\n\tNodeRailwayCommandRunner,\n\tRailwayAdapter,\n\ttype RailwayAdapterContext,\n\ttype RailwayAdapterOptions,\n\ttype RailwayCommandResult,\n\ttype RailwayCommandRunner,\n} from './commands/deploy/adapters/railway-adapter'\nexport { StubDeployAdapter } from './commands/deploy/adapters/stub-adapter'\nexport {\n\treadDeployState,\n\tresetDeployState,\n\tresolveDeployDirectory,\n\tresolveDeployStatePath,\n\tupdateDeployState,\n\twriteDeployState,\n\ttype DeployState,\n\ttype DeployStateCreateInput,\n\ttype DeployStatePatch,\n} from './commands/deploy/state/deploy-state'\nexport {\n\tgenerateDockerIgnore,\n\tgenerateDeployPackageJson,\n\tgenerateDockerfile,\n\twriteDockerIgnoreArtifact,\n\twriteDockerfileArtifact,\n\ttype DockerfileOptions,\n} from './commands/deploy/artifacts/dockerfile-generator'\nexport {\n\tgenerateFlyToml,\n\twriteFlyTomlArtifact,\n\ttype FlyTomlOptions,\n} from './commands/deploy/artifacts/fly-toml-generator'\nexport {\n\tgenerateRailwayJson,\n\twriteRailwayJsonArtifact,\n\ttype RailwayJsonOptions,\n} from './commands/deploy/artifacts/railway-json-generator'\nexport {\n\tbuildClient,\n\ttype ClientBuildOptions,\n\ttype ClientBuildResult,\n} from './commands/deploy/builder/client-builder'\nexport {\n\tbundleServer,\n\ttype ServerBundleOptions,\n\ttype ServerBundleResult,\n} from './commands/deploy/builder/server-bundler'\nexport {\n\tvalidateProjectName,\n\ttype ProjectNameValidationResult,\n} from './commands/create/project-name'\nexport {\n\tdetermineTemplateFromSelections,\n\tisAuthValue,\n\tisDatabaseProviderValue,\n\tisDatabaseValue,\n\tisFrameworkValue,\n\ttype AuthOption,\n\ttype DatabaseOption,\n\ttype DatabaseProviderOption,\n\ttype FrameworkOption,\n\ttype TemplateSelectionInput,\n} from './commands/create/options'\nexport {\n\tresolveCreatePreferencesFlow,\n\tsaveResolvedPreferences,\n\tshouldSavePreferences,\n\ttype CreateFlags,\n\ttype PreferenceResolutionResult,\n} from './commands/create/preferences-flow'\nexport { applySyncProviderPreset } from './commands/create/sync-provider-preset'\n\n// === Prompt Abstractions ===\nexport {\n\tcreatePromptClient,\n\tClackPromptClient,\n\tReadlinePromptClient,\n\tPromptCancelledError,\n\ttype PromptClient,\n\ttype SelectOption,\n} from './prompts/prompt-client'\nexport {\n\tgetDefaultCreatePreferences,\n\tgetCreatePreferencesOrDefault,\n\tPreferenceStore,\n\ttype CreatePreferences,\n} from './prompts/preferences'\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 { 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 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 { 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","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","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","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 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 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 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 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 { 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCO,IAAM,mBAAmB,CAAC,QAAQ,OAAO,QAAQ,KAAK;AAItD,IAAM,YAAY;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD;AAWO,IAAM,gBAAyC;AAAA,EACrD;AAAA,IACC,MAAM;AAAA,IACN,OAAO;AAAA,IACP,aAAa;AAAA,EACd;AAAA,EACA;AAAA,IACC,MAAM;AAAA,IACN,OAAO;AAAA,IACP,aAAa;AAAA,EACd;AAAA,EACA;AAAA,IACC,MAAM;AAAA,IACN,OAAO;AAAA,IACP,aAAa;AAAA,EACd;AAAA,EACA;AAAA,IACC,MAA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AAK,IAAI;AACX,QAAM,iBAAiB,GAAG,aAAa,GAAG,YAAY;AAEtD,YAAM,4BAAU,YAAY,gBAAgB,OAAO;AACnD,YAAM,4BAAU,SAAS,aAAa,OAAO;AAC7C,YAAM,4BAAU,YAAY,gBAAgB,OAAO;AACpD;AAEA,SAAS,eAAe,UAAiC;AACxD,SAAO,aAAa,gBAAgB,aAAa;AAClD;AAEA,SAAS,uBAAuB,UAA0C;AACzE,UAAQ,UAAU;AAAA,IACjB,KAAK;AACJ,aAAO;AAAA,IACR,KAAK;AACJ,aAAO;AAAA,IACR,KAAK;AACJ,aAAO;AAAA,IACR,KAAK;AACJ,aAAO;AAAA,IACR,KAAK;AACJ,aAAO;AAAA,IACR,KAAK;AACJ,aAAO;AAAA,IACR,KAAK;AACJ,aAAO;AAAA,EACT;AACD;AAEA,SAAS,mCAAmC,UAA0C;AACrF,UAAQ,UAAU;AAAA,IACjB,KAAK;AACJ,aAAO;AAAA,IACR,KAAK;AACJ,aAAO;AAAA,IACR,KAAK;AACJ,aAAO;AAAA,IACR,KAAK;AACJ,aAAO;AAAA,IACR,KAAK;AACJ,aAAO;AAAA,IACR,KAAK;AACJ,aAAO;AAAA,IACR,KAAK;AACJ,aAAO;AAAA,EACT;AACD;","names":["import_node_path","resolve","clackText","clackIsCancel","clackCancel","clackSelect","clackConfirm","clackIntro","clackOutro","import_node_child_process","import_node_path","import_promises","import_node_path","import_promises","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","validateNpmPackageName","Conf","import_promises","import_node_path"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/types.ts","../src/errors.ts","../src/commands/generate/type-generator.ts","../src/commands/deploy/deploy-command.ts","../src/prompts/prompt-client.ts","../src/utils/prompt.ts","../src/utils/fs-helpers.ts","../src/utils/logger.ts","../src/commands/deploy/adapters/adapter.ts","../src/commands/deploy/adapters/aws-ecs-adapter.ts","../src/commands/deploy/builder/client-builder.ts","../src/commands/deploy/builder/server-bundler.ts","../src/commands/deploy/adapters/aws-lightsail-adapter.ts","../src/commands/deploy/adapters/fly-adapter.ts","../src/commands/deploy/artifacts/fly-toml-generator.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/create/project-name.ts","../src/commands/create/options.ts","../src/prompts/preferences.ts","../src/commands/create/preferences-flow.ts","../src/commands/create/sync-provider-preset.ts"],"sourcesContent":["// @korajs/cli — public API\n// Every export here is a public API commitment. Be explicit.\n\n// === Types ===\nexport type { PackageManager, TemplateName, TemplateContext, TemplateInfo } from './types'\nexport { PACKAGE_MANAGERS, TEMPLATES, TEMPLATE_INFO } from './types'\n\n// === Errors ===\nexport {\n\tCliError,\n\tDevServerError,\n\tInvalidProjectError,\n\tProjectExistsError,\n\tSchemaNotFoundError,\n} from './errors'\n\n// === Type Generation (programmatic use) ===\nexport { generateTypes } from './commands/generate/type-generator'\nexport { deployCommand } from './commands/deploy/deploy-command'\nexport {\n\tDEPLOY_PLATFORMS,\n\tisDeployPlatform,\n\ttype ContextAwareDeployAdapter,\n\ttype BuildArtifacts,\n\ttype DeployAdapter,\n\ttype DeployPlatform,\n\ttype DeploymentStatus,\n\ttype DeployResult,\n\ttype LogLine,\n\ttype LogOptions,\n\ttype ProjectConfig,\n\ttype ProvisionResult,\n} from './commands/deploy/adapters/adapter'\nexport {\n\tFlyAdapter,\n\tNodeFlyCommandRunner,\n\ttype FlyAdapterContext,\n\ttype FlyAdapterOptions,\n\ttype FlyCommandResult,\n\ttype FlyCommandRunner,\n} from './commands/deploy/adapters/fly-adapter'\nexport { createDeployAdapter } from './commands/deploy/adapters/factory'\nexport {\n\tNodeRailwayCommandRunner,\n\tRailwayAdapter,\n\ttype RailwayAdapterContext,\n\ttype RailwayAdapterOptions,\n\ttype RailwayCommandResult,\n\ttype RailwayCommandRunner,\n} from './commands/deploy/adapters/railway-adapter'\nexport { StubDeployAdapter } from './commands/deploy/adapters/stub-adapter'\nexport {\n\treadDeployState,\n\tresetDeployState,\n\tresolveDeployDirectory,\n\tresolveDeployStatePath,\n\tupdateDeployState,\n\twriteDeployState,\n\ttype DeployState,\n\ttype DeployStateCreateInput,\n\ttype DeployStatePatch,\n} from './commands/deploy/state/deploy-state'\nexport {\n\tgenerateDockerIgnore,\n\tgenerateDeployPackageJson,\n\tgenerateDockerfile,\n\twriteDockerIgnoreArtifact,\n\twriteDockerfileArtifact,\n\ttype DockerfileOptions,\n} from './commands/deploy/artifacts/dockerfile-generator'\nexport {\n\tgenerateFlyToml,\n\twriteFlyTomlArtifact,\n\ttype FlyTomlOptions,\n} from './commands/deploy/artifacts/fly-toml-generator'\nexport {\n\tgenerateRailwayJson,\n\twriteRailwayJsonArtifact,\n\ttype RailwayJsonOptions,\n} from './commands/deploy/artifacts/railway-json-generator'\nexport {\n\tbuildClient,\n\ttype ClientBuildOptions,\n\ttype ClientBuildResult,\n} from './commands/deploy/builder/client-builder'\nexport {\n\tbundleServer,\n\ttype ServerBundleOptions,\n\ttype ServerBundleResult,\n} from './commands/deploy/builder/server-bundler'\nexport {\n\tvalidateProjectName,\n\ttype ProjectNameValidationResult,\n} from './commands/create/project-name'\nexport {\n\tdetermineTemplateFromSelections,\n\tisAuthValue,\n\tisDatabaseProviderValue,\n\tisDatabaseValue,\n\tisFrameworkValue,\n\ttype AuthOption,\n\ttype DatabaseOption,\n\ttype DatabaseProviderOption,\n\ttype FrameworkOption,\n\ttype TemplateSelectionInput,\n} from './commands/create/options'\nexport {\n\tresolveCreatePreferencesFlow,\n\tsaveResolvedPreferences,\n\tshouldSavePreferences,\n\ttype CreateFlags,\n\ttype PreferenceResolutionResult,\n} from './commands/create/preferences-flow'\nexport { applySyncProviderPreset } from './commands/create/sync-provider-preset'\n\n// === Prompt Abstractions ===\nexport {\n\tcreatePromptClient,\n\tClackPromptClient,\n\tReadlinePromptClient,\n\tPromptCancelledError,\n\ttype PromptClient,\n\ttype SelectOption,\n} from './prompts/prompt-client'\nexport {\n\tgetDefaultCreatePreferences,\n\tgetCreatePreferencesOrDefault,\n\tPreferenceStore,\n\ttype CreatePreferences,\n} from './prompts/preferences'\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 { 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 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 { 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\t'postgres': '^3.4.0',\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: 'AWS ECS Fargate (production multi-instance)',\n\t\t\tvalue: 'aws-ecs',\n\t\t},\n\t\t{\n\t\t\tlabel: 'AWS Lightsail Containers (simple, cost-effective)',\n\t\t\tvalue: 'aws-lightsail',\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","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","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","export const DEPLOY_PLATFORMS = ['fly', 'railway', 'aws-ecs', 'aws-lightsail', '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 { 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 AWS CLI interactions.\n */\nexport interface AwsCommandRunner {\n\trun(command: string, args: string[], cwd: string): Promise<AwsCommandResult>\n}\n\nexport interface AwsCommandResult {\n\texitCode: number\n\tstdout: string\n\tstderr: string\n}\n\nexport interface AwsEcsAdapterOptions {\n\trunner?: AwsCommandRunner\n\tcontext?: AwsEcsAdapterContext\n}\n\nexport interface AwsEcsAdapterContext {\n\tprojectRoot: string\n\tappName: string\n\tregion: string | null\n}\n\n/**\n * AWS ECS Fargate deploy adapter.\n *\n * Uses the AWS CLI to:\n * 1. Create an ECR repository for the Docker image\n * 2. Build and push the image to ECR\n * 3. Create/update an ECS Fargate service with an ALB\n *\n * Requires: `aws` CLI installed and configured with valid credentials.\n * Optionally uses `DATABASE_URL` env var for PostgreSQL (no EFS needed).\n *\n * Recommended for production multi-instance deployments.\n */\nexport class AwsEcsAdapter implements ContextAwareDeployAdapter {\n\tpublic readonly name = 'aws-ecs' as const\n\n\tprivate readonly logger = createLogger()\n\tprivate readonly runner: AwsCommandRunner\n\tprivate currentContext: AwsEcsAdapterContext | null\n\n\tpublic constructor(options: AwsEcsAdapterOptions = {}) {\n\t\tthis.runner = options.runner ?? new NodeAwsCommandRunner()\n\t\tthis.currentContext = options.context ?? null\n\t}\n\n\tpublic setContext(context: AwsEcsAdapterContext): void {\n\t\tthis.currentContext = context\n\t}\n\n\tpublic async detect(): Promise<boolean> {\n\t\tconst result = await this.runner.run('aws', ['--version'], process.cwd())\n\t\treturn result.exitCode === 0\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'AWS CLI is required but not installed. Install from https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html',\n\t\t\t)\n\t\t}\n\t}\n\n\tpublic async authenticate(): Promise<void> {\n\t\tconst cwd = this.currentContext?.projectRoot ?? process.cwd()\n\t\tconst result = await this.runner.run('aws', ['sts', 'get-caller-identity'], cwd)\n\t\tif (result.exitCode !== 0) {\n\t\t\tthrow new Error(\n\t\t\t\t'AWS CLI is not authenticated. Run `aws configure` or set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables.',\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 ?? 'us-east-1',\n\t\t}\n\n\t\tconst region = config.region ?? 'us-east-1'\n\t\tconst repoName = `kora/${config.appName}`\n\n\t\t// Create ECR repository (idempotent)\n\t\tconst createRepo = await this.runner.run('aws', [\n\t\t\t'ecr', 'create-repository',\n\t\t\t'--repository-name', repoName,\n\t\t\t'--region', region,\n\t\t\t'--image-scanning-configuration', 'scanOnPush=true',\n\t\t], config.projectRoot)\n\n\t\tif (createRepo.exitCode !== 0 && !createRepo.stderr.includes('RepositoryAlreadyExistsException')) {\n\t\t\tthrow new Error(`Failed to create ECR repository: ${createRepo.stderr}`)\n\t\t}\n\n\t\t// Get AWS account ID for ECR URI\n\t\tconst identity = await this.runner.run('aws', ['sts', 'get-caller-identity', '--query', 'Account', '--output', 'text'], config.projectRoot)\n\t\tconst accountId = identity.stdout.trim()\n\n\t\t// Create ECS cluster (idempotent)\n\t\tawait this.runner.run('aws', [\n\t\t\t'ecs', 'create-cluster',\n\t\t\t'--cluster-name', config.appName,\n\t\t\t'--region', region,\n\t\t], config.projectRoot)\n\n\t\t// Create CloudWatch log group\n\t\tawait this.runner.run('aws', [\n\t\t\t'logs', 'create-log-group',\n\t\t\t'--log-group-name', `/ecs/${config.appName}`,\n\t\t\t'--region', region,\n\t\t], config.projectRoot)\n\n\t\treturn {\n\t\t\tapplicationId: `${accountId}.dkr.ecr.${region}.amazonaws.com/${repoName}`,\n\t\t\tdatabaseId: null,\n\t\t\tsecretsSet: ['PORT'],\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\n\t\tconst deployDirectory = join(config.projectRoot, '.kora', 'deploy')\n\n\t\tawait bundleServer({\n\t\t\tprojectRoot: config.projectRoot,\n\t\t\tdeployDirectory,\n\t\t})\n\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 region = context.region ?? 'us-east-1'\n\t\tconst repoName = `kora/${context.appName}`\n\n\t\t// Get ECR login token\n\t\tconst loginPassword = await this.runner.run('aws', [\n\t\t\t'ecr', 'get-login-password', '--region', region,\n\t\t], context.projectRoot)\n\n\t\tif (loginPassword.exitCode !== 0) {\n\t\t\tthrow new Error(`ECR login failed: ${loginPassword.stderr}`)\n\t\t}\n\n\t\t// Get account ID\n\t\tconst identity = await this.runner.run('aws', [\n\t\t\t'sts', 'get-caller-identity', '--query', 'Account', '--output', 'text',\n\t\t], context.projectRoot)\n\t\tconst accountId = identity.stdout.trim()\n\t\tconst ecrUri = `${accountId}.dkr.ecr.${region}.amazonaws.com`\n\t\tconst imageUri = `${ecrUri}/${repoName}:latest`\n\n\t\t// Docker login to ECR\n\t\tconst dockerLogin = await this.runner.run('docker', [\n\t\t\t'login', '--username', 'AWS', '--password-stdin', ecrUri,\n\t\t], artifacts.deployDirectory)\n\t\t// Note: password is piped via stdin in real usage; for the adapter we use the password result\n\n\t\t// Build Docker image\n\t\tthis.logger.step('Building Docker image...')\n\t\tconst dockerBuild = await this.runner.run('docker', [\n\t\t\t'build', '--platform', 'linux/amd64', '-t', imageUri, '.',\n\t\t], artifacts.deployDirectory)\n\n\t\tif (dockerBuild.exitCode !== 0) {\n\t\t\tthrow new Error(`Docker build failed: ${dockerBuild.stderr}`)\n\t\t}\n\n\t\t// Push to ECR\n\t\tthis.logger.step('Pushing image to ECR...')\n\t\tconst dockerPush = await this.runner.run('docker', [\n\t\t\t'push', imageUri,\n\t\t], artifacts.deployDirectory)\n\n\t\tif (dockerPush.exitCode !== 0) {\n\t\t\tthrow new Error(`Docker push failed: ${dockerPush.stderr}`)\n\t\t}\n\n\t\t// Register task definition\n\t\tconst taskDef = JSON.stringify({\n\t\t\tfamily: context.appName,\n\t\t\tnetworkMode: 'awsvpc',\n\t\t\trequiresCompatibilities: ['FARGATE'],\n\t\t\tcpu: '256',\n\t\t\tmemory: '512',\n\t\t\texecutionRoleArn: `arn:aws:iam::${accountId}:role/ecsTaskExecutionRole`,\n\t\t\tcontainerDefinitions: [{\n\t\t\t\tname: context.appName,\n\t\t\t\timage: imageUri,\n\t\t\t\tessential: true,\n\t\t\t\tportMappings: [{ containerPort: 3001, protocol: 'tcp' }],\n\t\t\t\tlogConfiguration: {\n\t\t\t\t\tlogDriver: 'awslogs',\n\t\t\t\t\toptions: {\n\t\t\t\t\t\t'awslogs-group': `/ecs/${context.appName}`,\n\t\t\t\t\t\t'awslogs-region': region,\n\t\t\t\t\t\t'awslogs-stream-prefix': 'ecs',\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\thealthCheck: {\n\t\t\t\t\tcommand: ['CMD-SHELL', 'curl -f http://localhost:3001/health || exit 1'],\n\t\t\t\t\tinterval: 30,\n\t\t\t\t\ttimeout: 5,\n\t\t\t\t\tretries: 3,\n\t\t\t\t\tstartPeriod: 60,\n\t\t\t\t},\n\t\t\t}],\n\t\t})\n\n\t\tconst registerTask = await this.runner.run('aws', [\n\t\t\t'ecs', 'register-task-definition',\n\t\t\t'--cli-input-json', taskDef,\n\t\t\t'--region', region,\n\t\t], context.projectRoot)\n\n\t\tif (registerTask.exitCode !== 0) {\n\t\t\tthrow new Error(`Task definition registration failed: ${registerTask.stderr}`)\n\t\t}\n\n\t\t// Update or create ECS service\n\t\tconst updateService = await this.runner.run('aws', [\n\t\t\t'ecs', 'update-service',\n\t\t\t'--cluster', context.appName,\n\t\t\t'--service', context.appName,\n\t\t\t'--task-definition', context.appName,\n\t\t\t'--force-new-deployment',\n\t\t\t'--region', region,\n\t\t], context.projectRoot)\n\n\t\tconst deploymentId = new Date().toISOString()\n\n\t\tif (updateService.exitCode !== 0) {\n\t\t\tthis.logger.step('Service not found, creating new service...')\n\t\t\t// Service doesn't exist — developer needs to create it with proper VPC/subnet/ALB config.\n\t\t\t// We can't auto-create the full networking stack, so provide guidance.\n\t\t\tthis.logger.step(\n\t\t\t\t'Task definition registered. Create the ECS service with:\\n' +\n\t\t\t\t` aws ecs create-service \\\\\\n` +\n\t\t\t\t` --cluster ${context.appName} \\\\\\n` +\n\t\t\t\t` --service-name ${context.appName} \\\\\\n` +\n\t\t\t\t` --task-definition ${context.appName} \\\\\\n` +\n\t\t\t\t` --desired-count 1 \\\\\\n` +\n\t\t\t\t` --launch-type FARGATE \\\\\\n` +\n\t\t\t\t` --network-configuration \"awsvpcConfiguration={subnets=[<subnet-id>],securityGroups=[<sg-id>],assignPublicIp=ENABLED}\" \\\\\\n` +\n\t\t\t\t` --region ${region}`,\n\t\t\t)\n\t\t}\n\n\t\treturn {\n\t\t\tdeploymentId,\n\t\t\tliveUrl: `https://${context.appName}.${region}.amazonaws.com`,\n\t\t\tsyncUrl: `wss://${context.appName}.${region}.amazonaws.com/kora-sync`,\n\t\t}\n\t}\n\n\tpublic async rollback(deploymentId: string): Promise<void> {\n\t\tconst context = this.requireContext()\n\t\tconst region = context.region ?? 'us-east-1'\n\n\t\t// List task definition revisions and deploy the previous one\n\t\tconst result = await this.runner.run('aws', [\n\t\t\t'ecs', 'update-service',\n\t\t\t'--cluster', context.appName,\n\t\t\t'--service', context.appName,\n\t\t\t'--task-definition', `${context.appName}:${deploymentId}`,\n\t\t\t'--force-new-deployment',\n\t\t\t'--region', region,\n\t\t], context.projectRoot)\n\n\t\tif (result.exitCode !== 0) {\n\t\t\tthrow new Error(`ECS rollback failed: ${result.stderr}`)\n\t\t}\n\t}\n\n\tpublic async *logs(options: LogOptions): AsyncIterable<LogLine> {\n\t\tconst context = this.requireContext()\n\t\tconst region = context.region ?? 'us-east-1'\n\n\t\tconst args = [\n\t\t\t'logs', 'get-log-events',\n\t\t\t'--log-group-name', `/ecs/${context.appName}`,\n\t\t\t'--log-stream-name', 'ecs/latest',\n\t\t\t'--region', region,\n\t\t]\n\n\t\tif (options.tail) {\n\t\t\targs.push('--limit', String(options.tail))\n\t\t}\n\n\t\tconst result = await this.runner.run('aws', args, context.projectRoot)\n\t\tif (result.exitCode !== 0) {\n\t\t\treturn\n\t\t}\n\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(result.stdout) as { events?: Array<{ timestamp: number; message: string }> }\n\t\t\tfor (const event of parsed.events ?? []) {\n\t\t\t\tyield {\n\t\t\t\t\ttimestamp: new Date(event.timestamp).toISOString(),\n\t\t\t\t\tlevel: inferLogLevel(event.message),\n\t\t\t\t\tmessage: event.message,\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Non-JSON output, yield raw lines\n\t\t\tfor (const line of result.stdout.split('\\n').filter(Boolean)) {\n\t\t\t\tyield { timestamp: new Date().toISOString(), level: 'info', message: 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 region = context.region ?? 'us-east-1'\n\n\t\tconst result = await this.runner.run('aws', [\n\t\t\t'ecs', 'describe-services',\n\t\t\t'--cluster', context.appName,\n\t\t\t'--services', context.appName,\n\t\t\t'--region', region,\n\t\t], context.projectRoot)\n\n\t\tif (result.exitCode !== 0) {\n\t\t\treturn { state: 'failed', message: result.stderr }\n\t\t}\n\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(result.stdout) as {\n\t\t\t\tservices?: Array<{ status: string; runningCount: number; desiredCount: number }>\n\t\t\t}\n\t\t\tconst service = parsed.services?.[0]\n\t\t\tif (!service) {\n\t\t\t\treturn { state: 'unknown', message: 'Service not found' }\n\t\t\t}\n\n\t\t\tif (service.status === 'ACTIVE' && service.runningCount > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tstate: 'healthy',\n\t\t\t\t\tmessage: `Running ${service.runningCount}/${service.desiredCount} tasks`,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tstate: service.runningCount === 0 ? 'pending' : 'healthy',\n\t\t\t\tmessage: `Status: ${service.status}, running: ${service.runningCount}/${service.desiredCount}`,\n\t\t\t}\n\t\t} catch {\n\t\t\treturn { state: 'unknown', message: 'Could not parse service status' }\n\t\t}\n\t}\n\n\tprivate requireContext(): AwsEcsAdapterContext {\n\t\tif (!this.currentContext) {\n\t\t\tthrow new Error('AWS ECS adapter context is not initialized. Run provision() first.')\n\t\t}\n\t\treturn this.currentContext\n\t}\n}\n\n/**\n * Default subprocess-backed runner for AWS CLI commands.\n */\nexport class NodeAwsCommandRunner implements AwsCommandRunner {\n\tpublic async run(command: string, args: string[], cwd: string): Promise<AwsCommandResult> {\n\t\treturn new Promise<AwsCommandResult>((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) => { stdout += chunk.toString('utf-8') })\n\t\t\tchild.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf-8') })\n\t\t\tchild.on('error', (error) => {\n\t\t\t\tresolve({ exitCode: 1, stdout, stderr: `${stderr}\\n${error.message}` })\n\t\t\t})\n\t\t\tchild.on('exit', (code) => {\n\t\t\t\tresolve({ exitCode: code ?? 1, stdout: stdout.trim(), stderr: stderr.trim() })\n\t\t\t})\n\t\t})\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","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 { 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 AWS CLI interactions.\n */\nexport interface AwsLightsailCommandRunner {\n\trun(command: string, args: string[], cwd: string): Promise<AwsLightsailCommandResult>\n}\n\nexport interface AwsLightsailCommandResult {\n\texitCode: number\n\tstdout: string\n\tstderr: string\n}\n\nexport interface AwsLightsailAdapterOptions {\n\trunner?: AwsLightsailCommandRunner\n\tcontext?: AwsLightsailAdapterContext\n}\n\nexport interface AwsLightsailAdapterContext {\n\tprojectRoot: string\n\tappName: string\n\tregion: string | null\n}\n\n/**\n * AWS Lightsail Container Service deploy adapter.\n *\n * Uses the AWS CLI to:\n * 1. Create a Lightsail container service\n * 2. Build and push the Docker image\n * 3. Create a deployment with the container image\n *\n * Requires: `aws` CLI installed and configured with valid credentials,\n * plus the `lightsailctl` plugin for container image pushes.\n *\n * Recommended for simple, cost-effective container deployments.\n */\nexport class AwsLightsailAdapter implements ContextAwareDeployAdapter {\n\tpublic readonly name = 'aws-lightsail' as const\n\n\tprivate readonly logger = createLogger()\n\tprivate readonly runner: AwsLightsailCommandRunner\n\tprivate currentContext: AwsLightsailAdapterContext | null\n\n\tpublic constructor(options: AwsLightsailAdapterOptions = {}) {\n\t\tthis.runner = options.runner ?? new NodeAwsLightsailCommandRunner()\n\t\tthis.currentContext = options.context ?? null\n\t}\n\n\tpublic setContext(context: AwsLightsailAdapterContext): void {\n\t\tthis.currentContext = context\n\t}\n\n\tpublic async detect(): Promise<boolean> {\n\t\tconst result = await this.runner.run('aws', ['--version'], process.cwd())\n\t\treturn result.exitCode === 0\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'AWS CLI is required but not installed. Install from https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html',\n\t\t\t)\n\t\t}\n\t}\n\n\tpublic async authenticate(): Promise<void> {\n\t\tconst cwd = this.currentContext?.projectRoot ?? process.cwd()\n\t\tconst result = await this.runner.run('aws', ['sts', 'get-caller-identity'], cwd)\n\t\tif (result.exitCode !== 0) {\n\t\t\tthrow new Error(\n\t\t\t\t'AWS CLI is not authenticated. Run `aws configure` or set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables.',\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 ?? 'us-east-1',\n\t\t}\n\n\t\tconst region = config.region ?? 'us-east-1'\n\t\tconst serviceName = sanitizeLightsailName(config.appName)\n\n\t\t// Create Lightsail container service (idempotent — errors if already exists)\n\t\tconst createService = await this.runner.run('aws', [\n\t\t\t'lightsail', 'create-container-service',\n\t\t\t'--service-name', serviceName,\n\t\t\t'--power', 'nano',\n\t\t\t'--scale', '1',\n\t\t\t'--region', region,\n\t\t], config.projectRoot)\n\n\t\tif (createService.exitCode !== 0 && !createService.stderr.includes('already exists')) {\n\t\t\tthrow new Error(`Failed to create Lightsail container service: ${createService.stderr}`)\n\t\t}\n\n\t\treturn {\n\t\t\tapplicationId: serviceName,\n\t\t\tdatabaseId: null,\n\t\t\tsecretsSet: ['PORT'],\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\n\t\tconst deployDirectory = join(config.projectRoot, '.kora', 'deploy')\n\n\t\tawait bundleServer({\n\t\t\tprojectRoot: config.projectRoot,\n\t\t\tdeployDirectory,\n\t\t})\n\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 region = context.region ?? 'us-east-1'\n\t\tconst serviceName = sanitizeLightsailName(context.appName)\n\t\tconst imageTag = `${serviceName}:latest`\n\n\t\t// Build Docker image locally\n\t\tthis.logger.step('Building Docker image...')\n\t\tconst dockerBuild = await this.runner.run('docker', [\n\t\t\t'build', '--platform', 'linux/amd64', '-t', imageTag, '.',\n\t\t], artifacts.deployDirectory)\n\n\t\tif (dockerBuild.exitCode !== 0) {\n\t\t\tthrow new Error(`Docker build failed: ${dockerBuild.stderr}`)\n\t\t}\n\n\t\t// Push image to Lightsail using lightsailctl plugin\n\t\tthis.logger.step('Pushing image to Lightsail...')\n\t\tconst pushImage = await this.runner.run('aws', [\n\t\t\t'lightsail', 'push-container-image',\n\t\t\t'--service-name', serviceName,\n\t\t\t'--label', 'latest',\n\t\t\t'--image', imageTag,\n\t\t\t'--region', region,\n\t\t], artifacts.deployDirectory)\n\n\t\tif (pushImage.exitCode !== 0) {\n\t\t\tthrow new Error(`Lightsail image push failed: ${pushImage.stderr}`)\n\t\t}\n\n\t\t// Parse the image reference from the push output\n\t\tconst lightsailImage = parseLightsailImageRef(pushImage.stdout) ?? `:${serviceName}.latest.1`\n\n\t\t// Create deployment\n\t\tthis.logger.step('Creating Lightsail deployment...')\n\t\tconst environment: Record<string, string> = { PORT: '3001' }\n\t\t// Pass through deployment-relevant env vars\n\t\tfor (const key of PASSTHROUGH_ENV_VARS) {\n\t\t\tconst value = process.env[key]\n\t\t\tif (value) {\n\t\t\t\tenvironment[key] = value\n\t\t\t}\n\t\t}\n\t\tconst containers = JSON.stringify({\n\t\t\t[serviceName]: {\n\t\t\t\timage: lightsailImage,\n\t\t\t\tports: { '3001': 'HTTP' },\n\t\t\t\tenvironment,\n\t\t\t},\n\t\t})\n\t\tconst publicEndpoint = JSON.stringify({\n\t\t\tcontainerName: serviceName,\n\t\t\tcontainerPort: 3001,\n\t\t\thealthCheck: {\n\t\t\t\tpath: '/health',\n\t\t\t\tintervalSeconds: 30,\n\t\t\t\ttimeoutSeconds: 5,\n\t\t\t\thealthyThreshold: 2,\n\t\t\t\tunhealthyThreshold: 3,\n\t\t\t},\n\t\t})\n\n\t\tconst createDeploy = await this.runner.run('aws', [\n\t\t\t'lightsail', 'create-container-service-deployment',\n\t\t\t'--service-name', serviceName,\n\t\t\t'--containers', containers,\n\t\t\t'--public-endpoint', publicEndpoint,\n\t\t\t'--region', region,\n\t\t], context.projectRoot)\n\n\t\tif (createDeploy.exitCode !== 0) {\n\t\t\tthrow new Error(`Lightsail deployment failed: ${createDeploy.stderr}`)\n\t\t}\n\n\t\t// Get the service URL\n\t\tconst serviceInfo = await this.runner.run('aws', [\n\t\t\t'lightsail', 'get-container-services',\n\t\t\t'--service-name', serviceName,\n\t\t\t'--region', region,\n\t\t], context.projectRoot)\n\n\t\tconst rawUrl = parseLightsailUrl(serviceInfo.stdout) ?? `https://${serviceName}.${region}.cs.amazonlightsail.com`\n\t\tconst serviceUrl = rawUrl.replace(/\\/+$/, '')\n\t\tconst deploymentId = new Date().toISOString()\n\n\t\treturn {\n\t\t\tdeploymentId,\n\t\t\tliveUrl: serviceUrl,\n\t\t\tsyncUrl: `${serviceUrl.replace('https://', 'wss://')}/kora-sync`,\n\t\t}\n\t}\n\n\tpublic async rollback(_deploymentId: string): Promise<void> {\n\t\tconst context = this.requireContext()\n\t\tconst region = context.region ?? 'us-east-1'\n\t\tconst serviceName = sanitizeLightsailName(context.appName)\n\n\t\t// Lightsail doesn't have a native rollback — get previous deployment version\n\t\t// and redeploy. For now, we list deployments and use the previous container image.\n\t\tconst deployments = await this.runner.run('aws', [\n\t\t\t'lightsail', 'get-container-service-deployments',\n\t\t\t'--service-name', serviceName,\n\t\t\t'--region', region,\n\t\t], context.projectRoot)\n\n\t\tif (deployments.exitCode !== 0) {\n\t\t\tthrow new Error(`Lightsail rollback failed: ${deployments.stderr}`)\n\t\t}\n\n\t\t// Parse previous deployment and re-create it\n\t\tconst previousDeployment = parsePreviousDeployment(deployments.stdout, serviceName)\n\t\tif (!previousDeployment) {\n\t\t\tthrow new Error('No previous deployment found to rollback to.')\n\t\t}\n\n\t\tconst redeploy = await this.runner.run('aws', [\n\t\t\t'lightsail', 'create-container-service-deployment',\n\t\t\t'--service-name', serviceName,\n\t\t\t'--containers', JSON.stringify(previousDeployment.containers),\n\t\t\t'--public-endpoint', JSON.stringify(previousDeployment.publicEndpoint),\n\t\t\t'--region', region,\n\t\t], context.projectRoot)\n\n\t\tif (redeploy.exitCode !== 0) {\n\t\t\tthrow new Error(`Lightsail rollback deployment failed: ${redeploy.stderr}`)\n\t\t}\n\t}\n\n\tpublic async *logs(options: LogOptions): AsyncIterable<LogLine> {\n\t\tconst context = this.requireContext()\n\t\tconst region = context.region ?? 'us-east-1'\n\t\tconst serviceName = sanitizeLightsailName(context.appName)\n\n\t\tconst args = [\n\t\t\t'lightsail', 'get-container-log',\n\t\t\t'--service-name', serviceName,\n\t\t\t'--container-name', serviceName,\n\t\t\t'--region', region,\n\t\t]\n\n\t\tif (options.since) {\n\t\t\targs.push('--start-time', options.since)\n\t\t}\n\n\t\tconst result = await this.runner.run('aws', args, context.projectRoot)\n\t\tif (result.exitCode !== 0) {\n\t\t\treturn\n\t\t}\n\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(result.stdout) as { logEvents?: Array<{ createdAt: string; message: string }> }\n\t\t\tconst events = parsed.logEvents ?? []\n\t\t\tconst limited = options.tail ? events.slice(-options.tail) : events\n\t\t\tfor (const event of limited) {\n\t\t\t\tyield {\n\t\t\t\t\ttimestamp: event.createdAt,\n\t\t\t\t\tlevel: inferLogLevel(event.message),\n\t\t\t\t\tmessage: event.message,\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\tfor (const line of result.stdout.split('\\n').filter(Boolean)) {\n\t\t\t\tyield { timestamp: new Date().toISOString(), level: 'info', message: 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 region = context.region ?? 'us-east-1'\n\t\tconst serviceName = sanitizeLightsailName(context.appName)\n\n\t\tconst result = await this.runner.run('aws', [\n\t\t\t'lightsail', 'get-container-services',\n\t\t\t'--service-name', serviceName,\n\t\t\t'--region', region,\n\t\t], context.projectRoot)\n\n\t\tif (result.exitCode !== 0) {\n\t\t\treturn { state: 'failed', message: result.stderr }\n\t\t}\n\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(result.stdout) as {\n\t\t\t\tcontainerServices?: Array<{\n\t\t\t\t\tstate: string\n\t\t\t\t\turl: string\n\t\t\t\t\tcurrentDeployment?: { state: string }\n\t\t\t\t}>\n\t\t\t}\n\t\t\tconst service = parsed.containerServices?.[0]\n\t\t\tif (!service) {\n\t\t\t\treturn { state: 'unknown', message: 'Container service not found' }\n\t\t\t}\n\n\t\t\tconst deployState = service.currentDeployment?.state ?? 'UNKNOWN'\n\t\t\tif (service.state === 'RUNNING' && deployState === 'ACTIVE') {\n\t\t\t\treturn {\n\t\t\t\t\tstate: 'healthy',\n\t\t\t\t\tmessage: 'Lightsail container service is running',\n\t\t\t\t\tliveUrl: service.url,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (service.state === 'DEPLOYING' || deployState === 'ACTIVATING') {\n\t\t\t\treturn {\n\t\t\t\t\tstate: 'pending',\n\t\t\t\t\tmessage: `Service: ${service.state}, Deployment: ${deployState}`,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tstate: service.state === 'DISABLED' ? 'failed' : 'unknown',\n\t\t\t\tmessage: `Service: ${service.state}, Deployment: ${deployState}`,\n\t\t\t}\n\t\t} catch {\n\t\t\treturn { state: 'unknown', message: 'Could not parse service status' }\n\t\t}\n\t}\n\n\tprivate requireContext(): AwsLightsailAdapterContext {\n\t\tif (!this.currentContext) {\n\t\t\tthrow new Error('AWS Lightsail adapter context is not initialized. Run provision() first.')\n\t\t}\n\t\treturn this.currentContext\n\t}\n}\n\n/**\n * Default subprocess-backed runner for AWS CLI commands.\n */\nexport class NodeAwsLightsailCommandRunner implements AwsLightsailCommandRunner {\n\tpublic async run(command: string, args: string[], cwd: string): Promise<AwsLightsailCommandResult> {\n\t\treturn new Promise<AwsLightsailCommandResult>((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) => { stdout += chunk.toString('utf-8') })\n\t\t\tchild.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf-8') })\n\t\t\tchild.on('error', (error) => {\n\t\t\t\tresolve({ exitCode: 1, stdout, stderr: `${stderr}\\n${error.message}` })\n\t\t\t})\n\t\t\tchild.on('exit', (code) => {\n\t\t\t\tresolve({ exitCode: code ?? 1, stdout: stdout.trim(), stderr: stderr.trim() })\n\t\t\t})\n\t\t})\n\t}\n}\n\n/**\n * Environment variables automatically forwarded from the host to the Lightsail container.\n */\nconst PASSTHROUGH_ENV_VARS = [\n\t'DATABASE_URL',\n\t'AUTH_SECRET',\n\t'PUBLIC_URL',\n\t'NODE_ENV',\n] as const\n\n/**\n * Lightsail service names must be 2-255 chars, lowercase alphanumeric and hyphens only.\n */\nfunction sanitizeLightsailName(name: string): string {\n\treturn name\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9-]/g, '-')\n\t\t.replace(/-{2,}/g, '-')\n\t\t.replace(/^-|-$/g, '')\n\t\t.slice(0, 255) || 'kora-app'\n}\n\nfunction parseLightsailImageRef(output: string): string | null {\n\t// The push output contains a line like: \"Refer to this image as `:service.label.N` ...\"\n\tconst match = output.match(/Refer to this image as\\s+\"?(:[^\"\\s]+)\"?/i)\n\tif (match?.[1]) {\n\t\treturn match[1]\n\t}\n\t// Fallback: look for the image reference pattern\n\tconst refMatch = output.match(/(:\\S+\\.\\S+\\.\\d+)/)\n\treturn refMatch?.[1] ?? null\n}\n\nfunction parseLightsailUrl(rawJson: string): string | null {\n\ttry {\n\t\tconst parsed = JSON.parse(rawJson) as {\n\t\t\tcontainerServices?: Array<{ url?: string }>\n\t\t}\n\t\tconst url = parsed.containerServices?.[0]?.url\n\t\tif (typeof url === 'string' && url.length > 0) {\n\t\t\treturn url.startsWith('https://') ? url : `https://${url}`\n\t\t}\n\t\treturn null\n\t} catch {\n\t\treturn null\n\t}\n}\n\ninterface DeploymentConfig {\n\tcontainers: Record<string, unknown>\n\tpublicEndpoint: Record<string, unknown>\n}\n\nfunction parsePreviousDeployment(rawJson: string, serviceName: string): DeploymentConfig | null {\n\ttry {\n\t\tconst parsed = JSON.parse(rawJson) as {\n\t\t\tdeployments?: Array<{\n\t\t\t\tstate: string\n\t\t\t\tcontainers: Record<string, unknown>\n\t\t\t\tpublicEndpoint: Record<string, unknown>\n\t\t\t}>\n\t\t}\n\t\tconst deployments = parsed.deployments ?? []\n\t\t// Find the second deployment (index 1) — first is current, second is previous\n\t\tconst previous = deployments.length > 1 ? deployments[1] : null\n\t\tif (!previous) return null\n\n\t\treturn {\n\t\t\tcontainers: previous.containers,\n\t\t\tpublicEndpoint: previous.publicEndpoint,\n\t\t}\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","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 { 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 { AwsEcsAdapter } from './aws-ecs-adapter'\nimport { AwsLightsailAdapter } from './aws-lightsail-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 'aws-ecs':\n\t\t\treturn new AwsEcsAdapter()\n\t\tcase 'aws-lightsail':\n\t\t\treturn new AwsLightsailAdapter()\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 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 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 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 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 { 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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ACT;AACD;","names":["import_node_path","resolve","clackText","clackIsCancel","clackCancel","clackSelect","clackConfirm","clackIntro","clackOutro","import_node_child_process","import_node_path","import_promises","import_node_path","resolve","import_promises","import_node_path","resolve","import_node_child_process","import_node_path","inferLogLevel","resolve","import_node_child_process","import_node_path","import_promises","import_node_path","inferLogLevel","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","validateNpmPackageName","Conf","import_promises","import_node_path"]}