symmetria-kit 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":["inspect","inspect"],"sources":["../src/cli/context.ts","../src/cli/screens/schema-browser.ts","../src/cli/screens/dashboard.ts","../src/cli/screens/rollback-prompt.ts","../src/cli/commands/database.ts","../src/cli/commands/files.ts","../src/cli/commands/graph.ts","../src/cli/scaffold.ts","../src/cli/commands/init.ts","../src/cli/screens/profiler.ts","../src/cli/commands/profile.ts","../src/cli/commands/pull.ts","../src/cli/screens/rename-prompt.ts","../src/cli/commands/schema.ts","../src/cli/commands/index.ts","../src/cli/options.ts","../src/cli/index.ts"],"sourcesContent":["/** Everything a command needs: terminal mode, output, the project configuration and a database driver. */\nimport { access } from \"node:fs/promises\";\nimport * as nodeModule from \"node:module\";\nimport { dirname, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { postgres, type PostgresDriver } from \"symmetria/driver\";\nimport type { SchemaSnapshot } from \"symmetria\";\nimport type { MigrationConfig } from \"../migrations/config\";\nimport type { MigratorOptions } from \"../migrations/runner\";\nimport { supportsColor, theme } from \"./ui/style\";\nimport { choose, withSpinner } from \"./ui/terminal\";\nimport type { CliValues } from \"./options\";\n\nexport type Output = (message: string) => void;\n\nexport type CliContext = {\n readonly values: CliValues;\n readonly output: Output;\n /** A terminal that can show formatted output and animations. */\n readonly pretty: boolean;\n /** A terminal that can also ask questions and open screens. */\n readonly interactive: boolean;\n readonly color: boolean;\n readonly style: ReturnType<typeof theme>[\"style\"];\n readonly progress: <Result>(\n label: string,\n operation: () => Promise<Result>,\n ) => Promise<Result>;\n readonly select: (\n question: string,\n choices: readonly string[],\n ) => Promise<number | undefined>;\n /** Prints one of three renderings: JSON when --json, the pretty form on a terminal, else plain text. */\n readonly emit: (rendering: Rendering) => void;\n /** Runs another command in this process, collecting its output (used by the dashboard). */\n readonly rerun: (argumentsList: string[], output: Output) => Promise<void>;\n};\n\ntype Rendering = {\n readonly json: unknown;\n readonly indent?: number;\n readonly replacer?: (name: string, value: unknown) => unknown;\n readonly pretty?: () => string;\n readonly plain: () => string;\n};\n\nexport const createContext = (\n values: CliValues,\n output: Output,\n rerun: CliContext[\"rerun\"],\n): CliContext => {\n const pretty = !!process.stdout.isTTY && process.env.TERM !== \"dumb\";\n const interactive =\n !!process.stdin.isTTY &&\n pretty &&\n !values[\"no-interactive\"] &&\n !values.json &&\n !values.sql;\n const color =\n supportsColor() && !values[\"no-color\"] && !values.json && !values.sql;\n const { style } = theme(color);\n\n return {\n values,\n output,\n pretty,\n interactive,\n color,\n style,\n progress: (label, operation) =>\n withSpinner(label, operation, {\n enabled: pretty && !values.json && !values.sql,\n color,\n animation: !values[\"no-animation\"],\n }),\n select: (question, choices) => choose(question, choices, { color }),\n emit: (rendering) => {\n output(\n values.json\n ? JSON.stringify(rendering.json, rendering.replacer, rendering.indent)\n : pretty && rendering.pretty\n ? rendering.pretty()\n : rendering.plain(),\n );\n },\n rerun,\n };\n};\n\n/** The migration project a command works on: config module, directories and connection settings. */\nexport type Project = {\n readonly configPath: string;\n readonly present: boolean;\n readonly config: MigrationConfig;\n readonly directory: string;\n readonly databaseUrl: string | undefined;\n readonly runnerOptions: Omit<MigratorOptions, \"driver\" | \"signal\">;\n /** The declared schema as a snapshot, when the config has one. */\n readonly snapshot: () => SchemaSnapshot | undefined;\n};\n\nconst TIMEOUT_FLAGS = [\n [\"advisoryLockTimeoutMs\", \"advisory-lock-timeout\"],\n [\"lockTimeoutMs\", \"lock-timeout\"],\n [\"statementTimeoutMs\", \"statement-timeout\"],\n] as const;\n\nconst RESOLVE_EXTENSIONS = [\n \".ts\",\n \".mts\",\n \".js\",\n \".mjs\",\n \"/index.ts\",\n \"/index.js\",\n];\nconst RELATIVE_SPECIFIER = /^(\\.\\.?\\/|\\/|file:)/;\nconst KNOWN_EXTENSION = /\\.[cm]?[jt]sx?$|\\.json$/;\nlet hooksRegistered = false;\n\n/**\n * Node resolves `./src/schema` only with an extension, so the config and the\n * modules it imports get extension fallbacks. Bun resolves them natively and\n * has no registerHooks.\n */\nconst registerExtensionHooks = (): void => {\n // Bun has no registerHooks and resolves extensionless specifiers itself.\n const registerHooks = (\n nodeModule as { registerHooks?: typeof nodeModule.registerHooks }\n ).registerHooks;\n\n if (hooksRegistered || typeof registerHooks !== \"function\") {\n return;\n }\n\n hooksRegistered = true;\n registerHooks({\n resolve(specifier, context, nextResolve) {\n try {\n return nextResolve(specifier, context);\n } catch (error) {\n const code = (error as { code?: unknown } | null)?.code;\n\n if (\n (code !== \"ERR_MODULE_NOT_FOUND\" &&\n code !== \"ERR_UNSUPPORTED_DIR_IMPORT\") ||\n !RELATIVE_SPECIFIER.test(specifier) ||\n KNOWN_EXTENSION.test(specifier)\n ) {\n throw error;\n }\n\n for (const extension of RESOLVE_EXTENSIONS) {\n try {\n return nextResolve(`${specifier}${extension}`, context);\n } catch {\n // try the next candidate\n }\n }\n\n throw error;\n }\n },\n });\n};\n\nexport const loadProject = async (context: CliContext): Promise<Project> => {\n const { values } = context;\n const configPath = resolve(values.config ?? \"symmetria.config.ts\");\n const present = await access(configPath).then(\n () => true,\n (error: unknown) => {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"ENOENT\" &&\n !values.config\n ) {\n return false;\n }\n\n throw error;\n },\n );\n let config: MigrationConfig = {};\n\n if (present) {\n registerExtensionHooks();\n const module = await context.progress(\n \"Loading schema\",\n () => import(pathToFileURL(configPath).href),\n );\n\n if (!module.default || typeof module.default !== \"object\") {\n throw new Error(\n \"symmetria: config must default-export a migration configuration\",\n );\n }\n\n config = module.default;\n }\n\n const directory = values.dir\n ? resolve(values.dir)\n : resolve(\n present ? dirname(configPath) : process.cwd(),\n config.directory ?? \"migrations\",\n );\n const databaseUrl =\n values[\"database-url\"] ?? config.databaseUrl ?? process.env.DATABASE_URL;\n const timeouts = Object.fromEntries(\n TIMEOUT_FLAGS.flatMap(([key, flag]) => {\n const value =\n values[flag] === undefined ? config[key] : Number(values[flag]);\n\n if (value === undefined) {\n return [];\n }\n\n if (!Number.isSafeInteger(value) || value < 0 || value > 2147483647) {\n throw new Error(`symmetria: invalid --${flag}`);\n }\n\n return [[key, value]];\n }),\n );\n const verificationDatabaseUrl =\n values[\"verify-url\"] ?? config.verificationDatabaseUrl;\n // Prisma's history table is never part of an application schema, and adopt\n // must work while it still exists; declared tables are compared regardless.\n const ignoreTables = [\n ...new Set([\n \"_prisma_migrations\",\n ...(config.ignoreTables ?? []),\n ...(values[\"ignore-table\"] ?? []),\n ]),\n ];\n\n return {\n configPath,\n present,\n config,\n directory,\n databaseUrl,\n runnerOptions: {\n directory,\n ...(config.metadataSchema\n ? { metadataSchema: config.metadataSchema }\n : {}),\n ...(config.metadataTable ? { metadataTable: config.metadataTable } : {}),\n ...(verificationDatabaseUrl ? { verificationDatabaseUrl } : {}),\n ignoreTables,\n ...timeouts,\n ...(config.onEvent ? { onEvent: config.onEvent } : {}),\n },\n snapshot: () => {\n const source = config.schema;\n\n return source\n ? \"$snapshot\" in source\n ? source.$snapshot()\n : source\n : undefined;\n },\n };\n};\n\n/**\n * Opens a driver for the configured database, turns SIGINT/SIGTERM into a\n * cancellation signal with the conventional exit codes, and always closes it.\n */\nexport const withDatabase = async <Result>(\n project: Pick<Project, \"databaseUrl\">,\n operation: (driver: PostgresDriver, signal: AbortSignal) => Promise<Result>,\n): Promise<Result> => {\n if (!project.databaseUrl) {\n throw new Error(\n \"symmetria: no database: set databaseUrl in the config, DATABASE_URL or --database-url\",\n );\n }\n\n const driver = postgres(project.databaseUrl);\n\n try {\n return await withCancellation((signal) => operation(driver, signal));\n } finally {\n await driver.close();\n }\n};\n\nexport const withCancellation = async <Result>(\n operation: (signal: AbortSignal) => Promise<Result>,\n): Promise<Result> => {\n const cancellation = new AbortController();\n\n const interrupt = () => {\n process.exitCode = 130;\n cancellation.abort(new Error(\"symmetria: interrupted\"));\n };\n\n const terminate = () => {\n process.exitCode = 143;\n cancellation.abort(new Error(\"symmetria: terminated\"));\n };\n\n process.once(\"SIGINT\", interrupt);\n process.once(\"SIGTERM\", terminate);\n\n try {\n return await operation(cancellation.signal);\n } finally {\n process.removeListener(\"SIGINT\", interrupt);\n process.removeListener(\"SIGTERM\", terminate);\n }\n};\n","/**\n * Interactive schema browser: navigates tables, columns, relations, indexes and generated DDL.\n */\nimport stringWidth from \"string-width\";\nimport { emitKeypressEvents } from \"node:readline\";\nimport { stripVTControlCharacters } from \"node:util\";\nimport type { SchemaSnapshot, TableSnapshot } from \"symmetria\";\nimport { fitLine, numberedLines, theme, wrapLines } from \"../ui/style\";\nimport {\n highlightSQL,\n inspectEntries,\n inspectTableSQL,\n inspectTabs,\n matchesEntry,\n matchesTableName,\n matchingTables,\n type InspectTab,\n} from \"./schema-browser-data\";\n\ntype InspectOptions = { color: boolean; table?: string; tab?: InspectTab };\ntype Position = {\n table: TableSnapshot | undefined;\n tab: InspectTab;\n row: number;\n search: string;\n focus: \"tables\" | \"details\";\n};\n\n/** Runs inside the caller's alternate screen, both standalone and in the dashboard. */\nexport const inspectSchema = (\n snapshot: SchemaSnapshot,\n options: InspectOptions,\n): Promise<void> => {\n const initial = options.table\n ? snapshot.tables.find(\n (table) =>\n table.name === options.table || table.sqlName === options.table,\n )\n : snapshot.tables[0];\n\n if (options.table && !initial) {\n throw new Error(`symmetria: unknown table \"${options.table}\"`);\n }\n\n if (!process.stdin.isTTY || !process.stdout.isTTY) {\n throw new Error(\"symmetria: schema browser requires a terminal\");\n }\n\n return new Promise((resolve, reject) => {\n const { style, brand } = theme(options.color);\n const position: Position = {\n table: initial,\n tab: options.tab ?? \"Columns\",\n row: 0,\n search: \"\",\n focus: options.table ? \"details\" : \"tables\",\n };\n const history: Position[] = [];\n const sqlCache = new Map<TableSnapshot, string>();\n let searchStart: Position | undefined;\n let finished = false;\n let previousLines: string[] = [];\n let pageSize = 1;\n let tablePageSize = 1;\n let rowCount = 0;\n const wasRaw = process.stdin.isRaw;\n\n const tables = () => matchingTables(snapshot, position.search);\n\n const entries = () =>\n position.table\n ? inspectEntries(position.table, position.tab).filter(\n (entry) =>\n !position.search ||\n matchesTableName(position.table!, position.search) ||\n matchesEntry(entry, position.search),\n )\n : [];\n\n const align = (text: string, width: number) => {\n const clipped = fitLine(text, width);\n\n return clipped + \" \".repeat(Math.max(0, width - stringWidth(clipped)));\n };\n\n const frame = (\n title: string,\n body: string[],\n width: number,\n focused: boolean,\n ) => {\n const tone = focused ? \"violet\" : \"border\";\n const top = `─ ${title} `;\n\n return [\n style(\n `╭${fitLine(top, width - 2)}${\"─\".repeat(Math.max(0, width - 2 - stringWidth(top)))}╮`,\n tone,\n ),\n ...body.map(\n (line) =>\n `${style(\"│\", tone)} ${align(line, width - 4)} ${style(\"│\", tone)}`,\n ),\n style(`╰${\"─\".repeat(width - 2)}╯`, tone),\n ];\n };\n\n const rowStyle = (\n line: string,\n selected: boolean,\n focused: boolean,\n width: number,\n ) =>\n selected\n ? style(\n align(stripVTControlCharacters(line), width),\n focused ? \"selected\" : \"accent\",\n )\n : align(line, width);\n\n const normalize = () => {\n const visible = tables();\n\n if (!position.table || !visible.includes(position.table)) {\n position.table = visible[0];\n position.row = 0;\n }\n };\n\n const render = () => {\n normalize();\n const width = Math.max(\n 1,\n Math.min(process.stdout.columns || 88, 160) - 4,\n );\n const height = process.stdout.rows || 24;\n\n if (width < 28 || height < 12) {\n return [\n fitLine(\" symmetria / inspect\", width),\n fitLine(\" Enlarge terminal to browse\", width),\n fitLine(\" Esc to return\", width),\n ];\n }\n\n const visible = tables();\n const selectedTableIndex = Math.max(0, visible.indexOf(position.table!));\n const split = width >= 72;\n const sidebarWidth = split\n ? Math.min(28, Math.max(19, Math.floor(width * 0.23)))\n : width;\n const detailWidth = split ? width - sidebarWidth - 2 : width;\n const innerWidth = detailWidth - 4;\n const innerHeight = height - 7;\n tablePageSize = innerHeight;\n const tableOffset = Math.max(\n 0,\n Math.min(\n selectedTableIndex - innerHeight + 1,\n visible.length - innerHeight,\n ),\n );\n const sidebar = visible\n .slice(tableOffset, tableOffset + innerHeight)\n .map((table) => {\n const selected = table === position.table;\n\n return rowStyle(\n `${selected ? \"›\" : \" \"} ${table.name}`,\n selected,\n position.focus === \"tables\",\n sidebarWidth - 4,\n );\n });\n\n if (!sidebar.length) {\n sidebar.push(style(\"No matching tables\", \"muted\"));\n }\n\n while (sidebar.length < innerHeight) {\n sidebar.push(\"\");\n }\n\n const selectedEntries = entries();\n const labels =\n innerWidth >= 66\n ? inspectTabs\n : [\"Cols\", \"Rels\", \"Idx\", \"Checks\", \"SQL\"];\n const tabs = inspectTabs\n .map((tab, index) => {\n const count =\n position.table && tab !== \"SQL\"\n ? ` ${inspectEntries(position.table, tab).length}`\n : \"\";\n const label = `${labels[index]}${count}`;\n\n return style(\n position.tab === tab ? `[${label}]` : label,\n position.tab === tab ? \"pink\" : \"muted\",\n );\n })\n .join(\" \");\n const tabLine =\n stringWidth(tabs) <= innerWidth\n ? tabs\n : `${style(`‹ ${position.tab} ›`, \"pink\")} ${style(`${inspectTabs.indexOf(position.tab) + 1}/5 · ← → tabs`, \"muted\")}`;\n const detail: string[] = [\n tabLine,\n style(\"─\".repeat(innerWidth), \"border\"),\n ];\n let pageLabel = \"\";\n\n if (position.tab === \"SQL\" && position.table) {\n if (!sqlCache.has(position.table)) {\n sqlCache.set(\n position.table,\n highlightSQL(\n inspectTableSQL(snapshot, position.table),\n options.color,\n ),\n );\n }\n\n const sqlLines = numberedLines(\n sqlCache.get(position.table)!,\n innerWidth - 5,\n (label) => style(label, \"muted\"),\n );\n pageSize = innerHeight - detail.length;\n rowCount = sqlLines.length;\n position.row = Math.max(0, Math.min(position.row, rowCount - pageSize));\n detail.push(...sqlLines.slice(position.row, position.row + pageSize));\n pageLabel = `SQL ${position.row + 1}–${Math.min(rowCount, position.row + pageSize)}/${rowCount}`;\n } else {\n const nameWidth = Math.min(\n Math.max(\n 10,\n ...selectedEntries.map((entry) => stringWidth(entry.name)),\n ),\n Math.floor(innerWidth * 0.43),\n );\n const typeWidth = Math.min(\n Math.max(\n 7,\n ...selectedEntries.map((entry) => stringWidth(entry.kind)),\n ),\n Math.floor(innerWidth * 0.25),\n );\n\n const entryLine = (name: string, kind: string, flags: string) =>\n `${align(name, nameWidth)} ${align(kind, typeWidth)} ${flags}`;\n\n const detailBudget = Math.min(\n 4,\n Math.max(2, Math.floor(innerHeight / 4)),\n );\n pageSize = Math.max(\n 1,\n innerHeight - detail.length - 1 - detailBudget - 1,\n );\n rowCount = selectedEntries.length;\n position.row = Math.max(0, Math.min(position.row, rowCount - 1));\n const offset = Math.max(\n 0,\n Math.min(position.row - pageSize + 1, rowCount - pageSize),\n );\n detail.push(style(` ${entryLine(\"NAME\", \"TYPE\", \"FLAGS\")}`, \"muted\"));\n const rows = selectedEntries\n .slice(offset, offset + pageSize)\n .map((entry, index) => {\n const selected = position.row === offset + index;\n\n return rowStyle(\n `${selected ? \"›\" : \" \"} ${entryLine(style(entry.name, \"accent\"), style(entry.kind, \"violet\"), entry.badges.map((badge) => style(badge, \"pink\")).join(\" · \"))}`,\n selected,\n position.focus === \"details\",\n innerWidth,\n );\n });\n\n if (!rows.length) {\n rows.push(\n style(\n position.search\n ? \"No matches in this tab\"\n : `No ${position.tab.toLowerCase()}`,\n \"muted\",\n ),\n );\n }\n\n while (rows.length < pageSize) {\n rows.push(\"\");\n }\n\n detail.push(...rows, style(\"─\".repeat(innerWidth), \"border\"));\n const selected = selectedEntries[position.row];\n const description = selected\n ? wrapLines(style(selected.description, \"muted\"), innerWidth).slice(\n 0,\n detailBudget,\n )\n : [\n style(\n position.table\n ? \"← → switch tabs · / search\"\n : \"No tables to inspect\",\n \"muted\",\n ),\n ];\n detail.push(...description);\n pageLabel = rowCount\n ? `${position.tab} ${position.row + 1}/${rowCount}`\n : position.tab;\n }\n\n while (detail.length < innerHeight) {\n detail.push(\"\");\n }\n\n const sidebarPanel = frame(\n `Tables · ${visible.length}/${snapshot.tables.length}`,\n sidebar,\n sidebarWidth,\n position.focus === \"tables\",\n );\n const detailPanel = frame(\n position.table?.name ?? \"Schema\",\n detail.slice(0, innerHeight),\n detailWidth,\n position.focus === \"details\",\n );\n const panels = split\n ? sidebarPanel.map((line, index) => `${line} ${detailPanel[index]}`)\n : position.focus === \"tables\"\n ? sidebarPanel\n : detailPanel;\n const breadcrumb = `${history.length ? `${history.at(-1)!.table?.name} → ` : \"\"}${position.table?.name ?? \"schema\"}`;\n const search = searchStart\n ? `${style(\"/\", \"pink\")} ${position.search}${style(\"▏\", \"pink\")} ${style(\"enter apply · esc cancel\", \"muted\")}`\n : position.search\n ? `${style(\"/\", \"pink\")} ${position.search} ${style(\"esc clear\", \"muted\")}`\n : style(\"/ search tables and fields\", \"muted\");\n const hint =\n width >= 90\n ? \"↑↓ select · Tab pane · ←→ tabs · Enter follow · / search · ⌫ back · Esc/q exit\"\n : width >= 64\n ? \"↑↓ select · Tab pane · ←→ tabs · Enter follow · / find · Esc back\"\n : \"Tab pane · ←→ tabs · / find · Esc back\";\n\n return [\n ` ${fitLine(`${brand()} ${style(`/ inspect / ${breadcrumb}`, \"muted\")}`, width)}`,\n ` ${fitLine(search, width)}`,\n ...panels.map((line) => ` ${line}`),\n ` ${fitLine(`${style(position.focus === \"tables\" ? \"TABLES\" : \"DETAILS\", \"violet\")} ${style(pageLabel, \"muted\")}${history.length ? style(\" · ⌫ previous table\", \"pink\") : \"\"}`, width)}`,\n ` ${style(fitLine(hint, width), \"muted\")}`,\n ];\n };\n\n const draw = () => {\n try {\n const lines = render();\n const changes = lines.flatMap((line, index) =>\n line === previousLines[index]\n ? []\n : [`\\u001b[${index + 1};1H\\u001b[2K${line}`],\n );\n\n for (let index = lines.length; index < previousLines.length; index++) {\n changes.push(`\\u001b[${index + 1};1H\\u001b[2K`);\n }\n\n process.stdout.write(changes.join(\"\"));\n previousLines = lines;\n } catch (error) {\n finish(error);\n }\n };\n\n const resize = () => {\n previousLines = [];\n process.stdout.write(\"\\u001b[H\\u001b[2J\");\n draw();\n };\n\n const finish = (error?: unknown) => {\n if (finished) {\n return;\n }\n\n finished = true;\n process.stdin.off(\"keypress\", keypress);\n process.stdin.off(\"end\", end);\n process.stdout.off(\"resize\", resize);\n process.stdin.setRawMode(wasRaw);\n process.stdin.pause();\n process.stdout.write(\"\\u001b[?25h\");\n\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n };\n\n const end = () => finish();\n\n const keypress = (\n input: string,\n key: { name?: string; ctrl?: boolean; meta?: boolean },\n ) => {\n if (key.ctrl && [\"c\", \"d\"].includes(key.name ?? \"\")) {\n return finish();\n }\n\n if (searchStart) {\n if (key.name === \"escape\") {\n Object.assign(position, searchStart);\n searchStart = undefined;\n } else if (key.name === \"return\") {\n searchStart = undefined;\n } else if (key.name === \"backspace\") {\n position.search = [...position.search].slice(0, -1).join(\"\");\n position.row = 0;\n } else if (key.ctrl && key.name === \"u\") {\n position.search = \"\";\n position.row = 0;\n } else if (!key.ctrl && !key.meta && input && !/[\\p{C}]/u.test(input)) {\n position.search += input;\n position.row = 0;\n }\n\n draw();\n\n return;\n }\n\n if (input === \"/\") {\n searchStart = { ...position };\n draw();\n\n return;\n }\n\n // q closes the browser as it does the query inspector and the profiler.\n if (input === \"q\" && !key.ctrl && !key.meta) {\n return finish();\n }\n\n if (key.name === \"escape\") {\n if (position.search) {\n position.search = \"\";\n position.row = 0;\n draw();\n\n return;\n }\n\n return finish();\n }\n\n if (key.name === \"tab\") {\n position.focus = position.focus === \"tables\" ? \"details\" : \"tables\";\n } else if (key.name === \"backspace\") {\n const previous = history.pop();\n\n if (previous) {\n Object.assign(position, previous);\n } else {\n position.focus = \"tables\";\n }\n } else if (\n key.name === \"left\" ||\n key.name === \"right\" ||\n /^[1-5]$/.test(input)\n ) {\n const index = inspectTabs.indexOf(position.tab);\n position.tab =\n inspectTabs[\n /^[1-5]$/.test(input)\n ? Number(input) - 1\n : (index + (key.name === \"left\" ? -1 : 1) + inspectTabs.length) %\n inspectTabs.length\n ]!;\n position.row = 0;\n position.focus = \"details\";\n } else if (key.name === \"return\") {\n if (position.focus === \"tables\") {\n position.focus = \"details\";\n } else {\n const target = entries()[position.row]?.target;\n const table =\n target &&\n snapshot.tables.find(\n (table) =>\n table.name === target.table || table.sqlName === target.table,\n );\n\n if (table) {\n history.push({ ...position });\n Object.assign(position, {\n table,\n tab: \"Columns\",\n search: \"\",\n row: Math.max(\n 0,\n table.columns.findIndex(\n (column) =>\n column.name === target.column ||\n column.sqlName === target.column,\n ),\n ),\n });\n }\n }\n } else if (\n [\"up\", \"down\", \"pageup\", \"pagedown\", \"home\", \"end\"].includes(\n key.name ?? \"\",\n )\n ) {\n const visible = tables();\n const maximum =\n position.focus === \"tables\"\n ? visible.length - 1\n : position.tab === \"SQL\"\n ? rowCount - pageSize\n : rowCount - 1;\n const current =\n position.focus === \"tables\"\n ? visible.indexOf(position.table!)\n : position.row;\n const step = position.focus === \"tables\" ? tablePageSize : pageSize;\n const amount =\n key.name === \"up\"\n ? -1\n : key.name === \"down\"\n ? 1\n : key.name === \"pageup\"\n ? -step\n : step;\n const next = Math.max(\n 0,\n Math.min(\n maximum,\n key.name === \"home\"\n ? 0\n : key.name === \"end\"\n ? maximum\n : current + amount,\n ),\n );\n\n if (position.focus === \"tables\") {\n position.table = visible[next];\n position.row = 0;\n } else {\n position.row = next;\n }\n } else {\n return;\n }\n\n draw();\n };\n\n emitKeypressEvents(process.stdin);\n process.stdin.setRawMode(true);\n process.stdin.resume();\n process.stdin.on(\"keypress\", keypress);\n process.stdin.once(\"end\", end);\n process.stdout.on(\"resize\", resize);\n process.stdout.write(\"\\u001b[?25l\");\n resize();\n });\n};\n","/**\n * Interactive dashboard: header with chain, connectivity and schema state, plus a menu for generate,\n * migrate, inspect, status and rollback.\n */\nimport { relative } from \"node:path\";\nimport { postgres } from \"symmetria/driver\";\nimport { diffSchemas, loadMigrationState, migrator } from \"../../index\";\nimport { formatDashboard } from \"../ui/format\";\nimport { inspectSchema } from \"./schema-browser\";\nimport { formatError } from \"../ui/style\";\nimport { choose, view, withScreen } from \"../ui/terminal\";\nimport type { CliContext, Project } from \"../context\";\n\nconst ACTIONS = [\n [\n \"View schema changes\",\n \"diff\",\n \"Compare your schema with the latest local snapshot.\",\n ],\n [\n \"Generate migration\",\n \"generate\",\n \"Turn schema changes into a versioned SQL migration.\",\n ],\n [\"Apply migrations\", \"migrate\", \"Run pending migrations against PostgreSQL.\"],\n [\n \"Inspect schema\",\n \"inspect\",\n \"Explore tables, columns, relationships and constraints.\",\n ],\n [\n \"Migration history\",\n \"status\",\n \"See applied and pending migrations at a glance.\",\n ],\n [\n \"Rollback latest migration\",\n \"rollback\",\n \"Execute down.sql for the latest applied migration.\",\n ],\n [\"Exit\", \"\", \"Back to your terminal.\"],\n] as const;\n\nconst clear = () => process.stdout.write(\"\\u001b[H\\u001b[2J\");\n\n/** What the dashboard header shows: local chain, database connectivity and schema changes. */\nconst overview = async (context: CliContext, project: Project) => {\n const { migrations, snapshot: before } = await loadMigrationState(\n project.directory,\n );\n const snapshot = project.snapshot();\n const summary = {\n migrations: `${migrations.length} local · database not configured`,\n address: \"Offline · set DATABASE_URL to connect\",\n connection: \"offline\" as \"connected\" | \"offline\" | \"unavailable\",\n pending: 0,\n applied: 0,\n };\n\n if (project.databaseUrl) {\n const url = new URL(project.databaseUrl);\n summary.address = `PostgreSQL · ${url.hostname}:${url.port || \"5432\"}${url.pathname}`;\n const driver = postgres(project.databaseUrl);\n\n try {\n const statuses = await context.progress(\"Checking PostgreSQL\", () =>\n migrator({ driver, ...project.runnerOptions }).status(),\n );\n summary.applied = statuses.filter(\n (entry) => entry.status === \"applied\",\n ).length;\n summary.pending = statuses.filter(\n (entry) => entry.status === \"pending\",\n ).length;\n summary.connection = \"connected\";\n summary.migrations = `${summary.applied} applied · ${summary.pending} pending`;\n const incomplete = statuses.length - summary.applied - summary.pending;\n\n if (incomplete) {\n summary.migrations += ` · ${incomplete} incomplete (repair required)`;\n }\n } catch (error) {\n summary.connection = \"unavailable\";\n summary.migrations = `Unavailable: ${error instanceof Error ? error.message : String(error)}`;\n } finally {\n await driver.close();\n }\n }\n\n return {\n ...summary,\n snapshot,\n local: migrations.length,\n changes: snapshot\n ? diffSchemas(before, snapshot).up.filter(\n (statement) => !statement.startsWith(\"--\"),\n ).length\n : undefined,\n config: project.present\n ? relative(process.cwd(), project.configPath) || project.configPath\n : \"No config · symmetria init to get started\",\n };\n};\n\n/** `dashboard` (the bare `symmetria` command): a menu that runs the other commands in place. */\nexport const dashboard = async (\n context: CliContext,\n project: Project,\n): Promise<void> => {\n const { values, color } = context;\n\n if (!context.interactive) {\n throw new Error(\"symmetria: dashboard requires an interactive terminal\");\n }\n\n const forwarded = [\n ...(values.config ? [\"--config\", values.config] : []),\n ...(values.dir ? [\"--dir\", values.dir] : []),\n ...(values[\"database-url\"]\n ? [\"--database-url\", values[\"database-url\"]]\n : []),\n ...(values[\"no-color\"] ? [\"--no-color\"] : []),\n ...(values[\"no-animation\"] ? [\"--no-animation\"] : []),\n ];\n\n return withScreen(async () => {\n while (true) {\n const state = await overview(context, project);\n const selected = await choose(\n \"Choose an action\",\n ACTIONS.map(([label]) => label),\n {\n color,\n animation: !values[\"no-animation\"],\n header: (frame) => formatDashboard(state, color, frame),\n descriptions: ACTIONS.map(([, , description]) => description),\n },\n );\n const action = selected === undefined ? \"\" : ACTIONS[selected]![1];\n\n if (!action) {\n return;\n }\n\n clear();\n\n if (action === \"inspect\" && state.snapshot) {\n try {\n await inspectSchema(state.snapshot, { color });\n } catch (error) {\n await view(\n \"inspect\",\n formatError(\n error instanceof Error ? error.message : String(error),\n color,\n ),\n color,\n );\n }\n\n clear();\n continue;\n }\n\n const messages: string[] = [];\n\n try {\n await context.rerun([action, ...forwarded], (message) => {\n messages.push(message);\n });\n } catch (error) {\n messages.push(\n formatError(\n error instanceof Error ? error.message : String(error),\n color,\n ),\n );\n }\n\n await view(action, messages.join(\"\\n\"), color);\n clear();\n }\n });\n};\n","/**\n * Confirmation before a rollback: shows what down.sql removes and asks before\n * anything runs. Dropping or emptying whole tables needs the database name\n * typed out.\n */\nimport { parseMigrationSQL } from \"../../migrations/sql\";\nimport { lintMigrationSQL } from \"../../migrations/sql-lint\";\nimport type { Choose } from \"../ui/terminal\";\n\nexport type RollbackSummary = {\n readonly migrations: readonly string[];\n readonly statements: number;\n readonly destructive: readonly string[];\n readonly droppedTables: number;\n readonly emptiedTables: number;\n};\n\n/** The statement's leading keywords, read past comments. */\nconst opening = (sql: string): string =>\n (parseMigrationSQL(`${sql};`)[0]?.words ?? []).slice(0, 2).join(\" \");\n\nconst EMPTIES_TABLES = /^(?:TRUNCATE\\b|DROP (?:SCHEMA|OWNED)$)/;\n\nconst oneLine = (sql: string): string => {\n const text = sql.replace(/\\s+/g, \" \").trim();\n\n return text.length > 96 ? `${text.slice(0, 95)}…` : text;\n};\n\nexport const rollbackSummary = (\n steps: readonly {\n readonly id: string;\n readonly statements: readonly string[];\n }[],\n): RollbackSummary => {\n const destructive = steps.flatMap((step) =>\n lintMigrationSQL(\n step.statements.map((sql) => `${sql};`).join(\"\\n\"),\n step.id,\n )\n .filter((finding) => finding.level === \"destructive\")\n .map((finding) => step.statements[finding.statement - 1]!),\n );\n const unique = [...new Set(destructive)];\n\n return {\n migrations: steps.map((step) => step.id),\n statements: steps.reduce((sum, step) => sum + step.statements.length, 0),\n destructive: unique.map(oneLine),\n droppedTables: unique.filter((sql) => opening(sql) === \"DROP TABLE\").length,\n emptiedTables: unique.filter((sql) => EMPTIES_TABLES.test(opening(sql)))\n .length,\n };\n};\n\n/** The database a URL points at, for the question and the typed confirmation. */\nexport const databaseName = (url: string | undefined): string => {\n try {\n return (\n decodeURIComponent(new URL(url ?? \"\").pathname.slice(1)) || \"postgres\"\n );\n } catch {\n return \"database\";\n }\n};\n\nexport const rollbackPreview = (\n summary: RollbackSummary,\n database: string,\n): string =>\n [\n \"\",\n ` Rollback on \"${database}\": ${summary.migrations.join(\", \")}`,\n ` ${summary.statements} SQL statement${summary.statements === 1 ? \"\" : \"s\"} from down.sql`,\n ...(summary.destructive.length\n ? [\n \"\",\n ` Removes data or database objects (${summary.destructive.length}):`,\n ...summary.destructive.slice(0, 12).map((sql) => ` ${sql}`),\n ...(summary.destructive.length > 12\n ? [` … and ${summary.destructive.length - 12} more (see --plan)`]\n : []),\n ]\n : []),\n \"\",\n ].join(\"\\n\");\n\n/** True only after an explicit yes; closing the question or a wrong name cancels. */\nexport const confirmRollback = async (\n summary: RollbackSummary,\n database: string,\n prompts: {\n readonly write: (text: string) => void;\n readonly select: Choose;\n readonly ask: (question: string) => Promise<string>;\n },\n): Promise<boolean> => {\n prompts.write(`${rollbackPreview(summary, database)}\\n`);\n\n if (summary.droppedTables || summary.emptiedTables) {\n const answer = await prompts.ask(\n `${\n summary.emptiedTables\n ? \"This drops or empties whole tables\"\n : `This drops ${summary.droppedTables} table${summary.droppedTables === 1 ? \"\" : \"s\"}`\n }. Type the database name \"${database}\" to continue:`,\n );\n\n return answer === database;\n }\n\n const count = summary.migrations.length;\n\n return (\n (await prompts.select(\n `Roll back ${count} migration${count === 1 ? \"\" : \"s\"} on \"${database}\"?`,\n [\"Cancel\", \"Roll back\"],\n )) === 1\n );\n};\n","/**\n * Database-backed CLI commands: verify, drift, repair, adopt, status, migrate and rollback.\n * Each one opens a connection through the shared context and prints or emits JSON.\n */\nimport { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport {\n detectDrift,\n formatDriftFindings,\n loadMigrationState,\n migrator,\n parseMigrationSnapshot,\n snapshotHash,\n verifyMigrations,\n} from \"../../index\";\nimport { boundaryDifferences } from \"../../migrations/verify\";\nimport { formatExecution, formatStatus } from \"../ui/format\";\nimport { ask } from \"../ui/terminal\";\nimport {\n confirmRollback,\n databaseName,\n rollbackSummary,\n} from \"../screens/rollback-prompt\";\nimport {\n withCancellation,\n withDatabase,\n type CliContext,\n type Project,\n} from \"../context\";\n\n/** `verify`: replay the chain in disposable databases on the verification server. */\nexport const verify = async (\n context: CliContext,\n project: Project,\n): Promise<void> => {\n const url = project.runnerOptions.verificationDatabaseUrl;\n\n if (!url) {\n throw new Error(\n \"symmetria: verify requires --verify-url or verificationDatabaseUrl: an administrative PostgreSQL URL with CREATEDB permission, separate from the application database\",\n );\n }\n\n const result = await withCancellation((signal) =>\n verifyMigrations({\n ...project.runnerOptions,\n ...project.config.verify,\n url,\n signal,\n }),\n );\n context.emit({\n json: result,\n plain: () =>\n `Verified ${result.migrations.length} migrations: installation, upgrade, rollback and reapplication.`,\n });\n};\n\n/**\n * `drift`: compare the live catalog with the latest snapshot or the declared\n * schema. A database that is some migrations behind the local chain, after a\n * rollback or before a deploy, is not compared with the latest snapshot: every\n * pending change would read as drift. There are no older snapshots, so its own\n * boundary is checked by replaying the chain on the verification server, when\n * one is configured.\n */\nexport const drift = async (\n context: CliContext,\n project: Project,\n): Promise<void> =>\n withDatabase(project, async (driver, signal) => {\n const state = await loadMigrationState(project.directory);\n const { migrations, snapshot } = state;\n const expected =\n (migrations.length ? snapshot : undefined) ?? project.snapshot();\n\n if (!expected) {\n throw new Error(\n \"symmetria: drift needs a migration chain or a schema in the config\",\n );\n }\n\n const { metadataSchema, metadataTable } = project.config;\n const { ignoreTables, verificationDatabaseUrl } = project.runnerOptions;\n const history = migrations.length\n ? await migrator({ ...project.runnerOptions, driver, signal }).status()\n : [];\n const applied = history.findLastIndex(\n (entry) => entry.status === \"applied\",\n );\n\n // A database with no applied migration is compared with the latest\n // snapshot, as before `adopt`; so is one whose pending migrations leave\n // the schema as it is.\n if (\n applied >= 0 &&\n applied < migrations.length - 1 &&\n migrations[applied]!.manifest.after !== snapshotHash(snapshot)\n ) {\n const lastApplied = migrations[applied]!.id;\n const pending = migrations.slice(applied + 1).map(({ id }) => id);\n const differences = verificationDatabaseUrl\n ? await context.progress(\"Replaying the applied migrations\", () =>\n boundaryDifferences({\n ...project.runnerOptions,\n execute: driver.execute,\n state,\n target: applied,\n url: verificationDatabaseUrl,\n signal,\n }),\n )\n : undefined;\n const summary = `The database is ${pending.length} ${pending.length === 1 ? \"migration\" : \"migrations\"} behind the local chain (last applied: ${lastApplied}); drift is checked against the latest snapshot only.`;\n\n context.emit({\n json: {\n findings: [],\n behind: {\n migrations: pending.length,\n lastApplied,\n pending,\n verified: differences ? differences.length === 0 : null,\n ...(differences?.length ? { differences } : {}),\n },\n },\n indent: 2,\n plain: () =>\n [\n summary,\n ...(differences === undefined\n ? [\n `Run migrate, or verify the database against ${lastApplied} with --verify-url.`,\n ]\n : differences.length\n ? [\n `Replaying the chain up to ${lastApplied} on the verification server gives a different schema:`,\n ...differences.map((line) => ` ${line}`),\n ]\n : [\n `Replaying the chain up to ${lastApplied} on the verification server gives the same schema: no schema drift detected.`,\n ]),\n ].join(\"\\n\"),\n });\n\n // Being behind is not drift; a boundary that does not match is.\n if (context.values.strict && differences?.length) {\n process.exitCode = 1;\n }\n\n return;\n }\n\n const findings = await context.progress(\"Inspecting the database\", () =>\n detectDrift({\n execute: driver.execute,\n snapshot: expected,\n ...(metadataSchema ? { metadataSchema } : {}),\n ...(metadataTable ? { metadataTable } : {}),\n ...(ignoreTables ? { ignoreTables } : {}),\n }),\n );\n context.emit({\n json: { findings },\n indent: 2,\n plain: () => formatDriftFindings(findings),\n });\n\n if (context.values.strict && findings.length) {\n process.exitCode = 1;\n }\n });\n\ntype Runner = ReturnType<typeof migrator>;\n\n/** `migrate`, `rollback`, `status`, `adopt` and `repair` share one migrator bound to the database. */\nconst withRunner = (\n project: Project,\n operation: (runner: Runner) => Promise<void>,\n): Promise<void> =>\n withDatabase(project, (driver, signal) =>\n operation(migrator({ ...project.runnerOptions, driver, signal })),\n );\n\nconst plan = async (\n context: CliContext,\n runner: Runner,\n direction: \"up\" | \"down\",\n): Promise<void> => {\n const { values } = context;\n const steps = await runner.plan({\n ...(values.to ? { to: values.to } : {}),\n ...(values.steps ? { steps: Number(values.steps) } : {}),\n direction,\n });\n context.emit({\n json: { steps },\n indent: 2,\n plain: () =>\n steps\n .map(\n (step) =>\n `-- group ${step.group}: ${step.transaction} · ${step.id}\\n${step.statements.map((sql) => `${sql};`).join(\"\\n\\n\")}`,\n )\n .join(\"\\n\\n\"),\n });\n};\n\nexport const repair = (\n context: CliContext,\n project: Project,\n id: string,\n): Promise<void> =>\n withRunner(project, async (runner) => {\n const action = context.values.action as \"retry\" | \"complete\";\n // The snapshot file of the boundary, such as meta/snapshot.json as it was\n // before the migration was generated; the runner checks its hash.\n const file = context.values.snapshot;\n const snapshot =\n file === undefined\n ? undefined\n : parseMigrationSnapshot(\n JSON.parse(await readFile(resolve(file), \"utf8\")),\n );\n await runner.repair({ id, action, ...(snapshot ? { snapshot } : {}) });\n context.emit({\n json: { repaired: id, action },\n plain: () => `Repaired ${id}: ${action}`,\n });\n });\n\nexport const adopt = (context: CliContext, project: Project): Promise<void> =>\n withRunner(project, async (runner) => {\n const { values } = context;\n const adopted = await context.progress(\"Recording the local chain\", () =>\n runner.adopt(values.to ? { to: values.to } : {}),\n );\n context.emit({\n json: { adopted },\n plain: () =>\n adopted.length\n ? adopted.map((id) => `Adopted ${id}`).join(\"\\n\")\n : \"Nothing to adopt.\",\n });\n });\n\nexport const status = (context: CliContext, project: Project): Promise<void> =>\n withRunner(project, async (runner) => {\n const statuses = await context.progress(\"Reading migration history\", () =>\n runner.status(),\n );\n\n if (statuses.some((entry) => entry.status === \"incomplete\")) {\n process.exitCode = 1;\n }\n\n context.emit({\n json: { migrations: statuses },\n pretty: () => formatStatus(statuses, context.color),\n plain: () =>\n statuses.length\n ? statuses\n .map(\n (entry) =>\n `${entry.status.padEnd(7)} ${entry.id}${entry.status === \"incomplete\" ? ` · ${entry.direction} · ${entry.statement} confirmed statements · repair required` : \"\"}`,\n )\n .join(\"\\n\")\n : \"No migrations.\",\n });\n });\n\nexport const migrate = (context: CliContext, project: Project): Promise<void> =>\n withRunner(project, async (runner) => {\n const { values } = context;\n\n if (values.plan) {\n return plan(context, runner, \"up\");\n }\n\n const started = performance.now();\n const applied = await context.progress(\"Applying migrations\", () =>\n runner.migrate(values.to ? { to: values.to } : {}),\n );\n const durationMs = Math.round(performance.now() - started);\n // `--to` an applied migration does nothing; say where the database stands.\n const current =\n !applied.length && values.to\n ? (await runner.status())\n .filter((entry) => entry.status === \"applied\")\n .at(-1)?.id\n : undefined;\n const idle =\n current === undefined\n ? \"Database is up to date.\"\n : current === values.to\n ? `Database is already at ${values.to}.`\n : `${values.to} is already applied; the database is further along, at ${current}. Use rollback to go back.`;\n context.emit({\n json: { applied, durationMs },\n pretty: () =>\n current === undefined\n ? formatExecution(applied, \"Applied\", durationMs, context.color)\n : `\\n ${context.style(\"✓\", \"success\")} ${idle}\\n`,\n plain: () =>\n applied.length ? applied.map((id) => `Applied ${id}`).join(\"\\n\") : idle,\n });\n });\n\nexport const rollback = (\n context: CliContext,\n project: Project,\n): Promise<void> =>\n withRunner(project, async (runner) => {\n const { values } = context;\n\n if (values.plan) {\n return plan(context, runner, \"down\");\n }\n\n const steps = values.steps === undefined ? 1 : Number(values.steps);\n let expected: string[] | undefined;\n\n // down.sql usually removes columns or tables, so it never runs unasked.\n if (\n !values.yes &&\n (await runner.status()).some((entry) => entry.status !== \"pending\")\n ) {\n if (!context.interactive) {\n throw new Error(\n \"symmetria: rollback runs down.sql, which can remove data; review it with --plan and pass --yes to run it\",\n );\n }\n\n const planned = await runner.plan({ steps, direction: \"down\" });\n\n // What was shown is what runs: another process may roll back in between.\n expected = [...new Set(planned.map((step) => step.id))];\n\n const confirmed = await confirmRollback(\n rollbackSummary(planned),\n databaseName(project.databaseUrl),\n {\n write: (text) => process.stdout.write(text),\n select: context.select,\n ask: (question) => ask(question, context.color),\n },\n );\n\n if (!confirmed) {\n context.emit({\n json: { reverted: [], cancelled: true },\n pretty: () =>\n `\\n ${context.style(\"○\", \"muted\")} Rollback cancelled; nothing was changed.\\n`,\n plain: () => \"Rollback cancelled; nothing was changed.\",\n });\n\n return;\n }\n }\n\n const started = performance.now();\n const reverted = await context.progress(\"Rolling back migrations\", () =>\n runner.rollback({\n ...(values.steps === undefined ? {} : { steps }),\n ...(expected ? { expected } : {}),\n }),\n );\n const durationMs = Math.round(performance.now() - started);\n context.emit({\n json: { reverted, durationMs },\n pretty: () =>\n formatExecution(reverted, \"Reverted\", durationMs, context.color),\n plain: () =>\n reverted.length\n ? reverted.map((id) => `Reverted ${id}`).join(\"\\n\")\n : \"No applied migrations.\",\n });\n });\n","/**\n * Filesystem-only CLI commands: recover a crashed generation and squash the chain.\n */\nimport { recoverMigrationFiles, squashMigrations } from \"../../index\";\nimport type { CliContext, Project } from \"../context\";\n\n/** `recover`: finish or roll back a publication left behind by a crashed generator. */\nexport const recover = async (\n context: CliContext,\n project: Project,\n): Promise<void> => {\n const recovered = await recoverMigrationFiles(project.directory);\n context.emit({\n json: { recovered },\n plain: () =>\n recovered\n ? \"Migration files recovered.\"\n : \"Nothing to recover: no generation lock was left behind.\",\n });\n};\n\n/** `squash <name>`: replace the local chain with one baseline migration. */\nexport const squash = async (\n context: CliContext,\n project: Project,\n name: string,\n): Promise<void> => {\n const squashed = await context.progress(\"Squashing migrations\", () =>\n squashMigrations({\n directory: project.directory,\n name,\n ...(context.values[\"allow-custom-sql\"] ? { allowCustomSQL: true } : {}),\n }),\n );\n context.emit({\n json: squashed ? { id: squashed.id } : { id: null },\n plain: () =>\n squashed\n ? `Squashed into ${squashed.id}. Run \"symmetria adopt\" on databases that applied the old chain.`\n : \"Nothing to squash.\",\n });\n};\n","import { mkdir, writeFile } from \"node:fs/promises\";\nimport { basename, dirname, extname, resolve } from \"node:path\";\nimport { renderMermaid, schemaGraph } from \"../../graph/mermaid\";\nimport { loadMigrationState } from \"../../migrations/files\";\nimport type { CliContext, Project } from \"../context\";\nimport { formatCreated } from \"../ui/format\";\n\n/**\n * `graph [file]`: a Mermaid entity-relationship diagram of the declared schema,\n * or of the latest migration snapshot when the config declares no schema.\n * Printed to stdout, or written to a file (`.md` files get a ```mermaid fence).\n */\nexport const graph = async (\n context: CliContext,\n project: Project,\n name: string | undefined,\n): Promise<void> => {\n const { values, color } = context;\n const declared = project.snapshot();\n const snapshot =\n declared ??\n (await loadMigrationState(project.directory).then(\n ({ migrations, snapshot }) => (migrations.length ? snapshot : undefined),\n ));\n\n if (!snapshot) {\n throw new Error(\n \"symmetria: graph needs a schema in the config or a migration chain\",\n );\n }\n\n const model = schemaGraph(snapshot);\n const summary = `${model.tables.length} ${model.tables.length === 1 ? \"table\" : \"tables\"}, ${model.edges.length} ${model.edges.length === 1 ? \"relation\" : \"relations\"}`;\n\n if (!name) {\n context.emit({\n json: model,\n indent: 2,\n plain: () =>\n renderMermaid(model, { compact: !!values.compact }).trimEnd(),\n });\n\n return;\n }\n\n const path = resolve(name);\n const diagram = renderMermaid(model, {\n fenced: extname(path).toLowerCase() === \".md\",\n compact: !!values.compact,\n });\n await mkdir(dirname(path), { recursive: true });\n\n try {\n await writeFile(path, diagram, { flag: values.force ? \"w\" : \"wx\" });\n } catch (error) {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"EEXIST\"\n ) {\n throw new Error(`symmetria: ${path} exists; use --force to overwrite it`);\n }\n\n throw error;\n }\n\n context.emit({\n json: { path, tables: model.tables.length, relations: model.edges.length },\n indent: 2,\n pretty: () =>\n `${formatCreated(dirname(path), [basename(path)], color)} ${context.style(summary, \"muted\")}`,\n plain: () => `Created\\n ${path}\\n ${summary}`,\n });\n};\n","/**\n * `symmetria-kit init`: writes the starter schema, migrations directory and config files for a new project.\n */\nimport { lstat, mkdir, open, readdir, rm } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\n\nconst files: Readonly<Record<string, string>> = {\n \"src/database/tables/users.ts\": `import { table, uuid, text } from \"symmetria\";\\n\\nexport const users = table({\\n id: uuid.v4.brand(\"UserId\"),\\n email: text.unique,\\n name: text,\\n});\\n`,\n \"src/database/schema.ts\": `import { schema } from \"symmetria\";\\nimport { users } from \"./tables/users.ts\";\\n\\nexport const appSchema = schema({ users });\\n`,\n \"src/database/index.ts\": `import { createDatabase } from \"symmetria\";\\nimport { postgres } from \"symmetria/driver\";\\nimport { appSchema } from \"./schema.ts\";\\n\\nconst url = process.env.DATABASE_URL;\\n\\nif (!url) {\\n throw new Error(\"Set DATABASE_URL before connecting\");\\n}\\n\\nexport const db = createDatabase({\\n schema: appSchema,\\n driver: postgres({ url }),\\n});\\n`,\n \"symmetria.config.ts\": `import { defineMigrationConfig } from \"symmetria-kit\";\\nimport { appSchema } from \"./src/database/schema\";\\n\\nexport default defineMigrationConfig({\\n schema: appSchema,\\n directory: \"./migrations\",\\n databaseUrl: process.env.DATABASE_URL,\\n});\\n`,\n \".env.example\":\n \"DATABASE_URL=postgres://postgres:postgres@localhost:5432/app\\n\",\n};\n\nexport const initializeProject = async (\n directory: string,\n): Promise<string[]> => {\n // A configured project already owns its schema layout. Do not add a second one.\n for (const name of [\"symmetria.config.ts\", \"migrations.config.ts\"]) {\n const existing = await lstat(resolve(directory, name)).catch(\n (error: unknown) => {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n ) {\n return undefined;\n }\n\n throw error;\n },\n );\n\n if (existing) {\n return [];\n }\n }\n\n const migrations = await readdir(resolve(directory, \"migrations\"), {\n withFileTypes: true,\n }).catch((error: unknown) => {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n ) {\n return [];\n }\n\n throw error;\n });\n\n if (\n migrations.some(\n (entry) => entry.isDirectory() && /^\\d{6}_/.test(entry.name),\n )\n ) {\n return [];\n }\n\n const created: string[] = [];\n\n try {\n for (const [name, contents] of Object.entries(files)) {\n const path = resolve(directory, name);\n await mkdir(dirname(path), { recursive: true });\n const file = await open(path, \"wx\").catch((error: unknown) => {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"EEXIST\"\n ) {\n return undefined;\n }\n\n throw error;\n });\n\n if (!file) {\n continue;\n }\n\n created.push(name);\n\n try {\n await file.writeFile(contents);\n } finally {\n await file.close();\n }\n }\n\n return created;\n } catch (error) {\n await Promise.all(created.map((name) => rm(resolve(directory, name))));\n throw new Error(\n \"symmetria: init could not create the project files (existing files are preserved)\",\n { cause: error },\n );\n }\n};\n","import { relative, resolve } from \"node:path\";\nimport { formatCreated } from \"../ui/format\";\nimport { initializeProject } from \"../scaffold\";\nimport type { CliContext } from \"../context\";\n\nconst quoteArgument = (value: string) =>\n /^[\\w./-]+$/.test(value) ? value : `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n\n/** `init [directory]`: scaffold schema modules, a connection and migration config. */\nexport const init = async (\n context: CliContext,\n name: string | undefined,\n): Promise<void> => {\n const { style, color } = context;\n const directory = resolve(name ?? \".\");\n const files = await context.progress(\"Creating your project\", () =>\n initializeProject(directory),\n );\n\n if (!files.length) {\n context.emit({\n json: { directory, files },\n plain: () => \"Existing project files preserved; nothing to create.\",\n });\n\n return;\n }\n\n const invocation = \"bunx --package symmetria-kit symmetria\";\n const changeDirectory =\n directory === process.cwd()\n ? \"\"\n : ` cd ${quoteArgument(relative(process.cwd(), directory))}\\n`;\n const next = `${style(\"Next\", \"violet\")}\\n${changeDirectory} Set DATABASE_URL (see .env.example)\\n ${style(`${invocation} generate initial`, \"accent\")}\\n ${style(`${invocation} migrate`, \"accent\")}`;\n context.emit({\n json: { directory, files },\n pretty: () => `${formatCreated(directory, files, color)}\\n${next}`,\n plain: () =>\n `Created\\n${files.map((file) => ` ${file}`).join(\"\\n\")}\\n\\n${next}`,\n });\n};\n","/**\n * Live profiler screen: polls a running profiler endpoint and renders request and query timings.\n */\nimport { emitKeypressEvents } from \"node:readline\";\nimport type { ProfiledRequest, ProfiledQuery } from \"symmetria\";\nimport { fitLine, terminalWidth, theme, wrapLines } from \"../ui/style\";\nimport { withScreen } from \"../ui/terminal\";\nimport {\n explainLines,\n terminalText,\n wrapExplainLines,\n} from \"./query-inspector\";\n\n/** Why the profiler endpoint refused a request, with the fix for a wrong token. */\nexport const profilerHttpError = (status: number): string =>\n status === 403\n ? \"symmetria: the profiler rejected the token; pass --profile-token or set SYMMETRIA_PROFILE_TOKEN to the value used by profiler.serve()\"\n : `symmetria: profiler returned HTTP ${status}`;\n\nconst milliseconds = (value: number) => `${value.toFixed(3)} ms`;\n\n/**\n * The lines of one request's view: its timings, the error that ended it and\n * its queries, with the selected one marked. A request can fail before it runs\n * a query; then the error stands where the list would be.\n */\nexport const requestLines = (\n request: ProfiledRequest,\n selectedQuery: number,\n view: {\n width: number;\n height: number;\n style: ReturnType<typeof theme>[\"style\"];\n },\n): string[] => {\n const { width, height, style } = view;\n // Narrow terminals drop columns rather than cutting the timings off.\n const compact = width < 72;\n const lines = [\n style(\n `${request.label} · build ${milliseconds(request.buildMs)} · total ${milliseconds(request.durationMs)}`,\n \"pink\",\n ),\n ];\n\n if (request.error) {\n // Half the screen at most, so the queries that led to it stay visible.\n const message = wrapLines(\n style(`Error: ${terminalText(request.error)}`, \"danger\"),\n width,\n );\n const limit = request.queries.length\n ? Math.max(1, Math.floor(height / 2) - 1)\n : Math.max(1, height - 2);\n\n lines.push(\n ...message.slice(0, limit),\n ...(message.length > limit ? [style(\"…\", \"danger\")] : []),\n );\n }\n\n if (!request.queries.length) {\n lines.push(\n style(\n request.error\n ? \"The request ran no queries before it failed.\"\n : \"The request ran no queries.\",\n \"muted\",\n ),\n );\n\n return lines;\n }\n\n lines.push(\n style(\n compact\n ? `${\"Query\".padEnd(18)}${\"Database\".padStart(10)} ${\"Rows\".padStart(6)}`\n : \"Query Compile Database Decode Rows\",\n \"muted\",\n ),\n );\n const rows = Math.max(1, height - lines.length);\n const start = Math.max(0, selectedQuery - rows + 1);\n\n for (const [position, entry] of request.queries\n .slice(start, start + rows)\n .entries()) {\n const marker = start + position === selectedQuery ? \"›\" : \" \";\n lines.push(\n style(\n compact\n ? `${marker} ${entry.kind.padEnd(7)} #${String(entry.id).padEnd(6)} ${entry.databaseMs.toFixed(3).padStart(10)} ${String(entry.rows).padStart(6)}${entry.error ? \" ERROR\" : \"\"}`\n : `${marker} ${entry.kind.padEnd(9)} #${String(entry.id).padEnd(10)} ${entry.compileMs.toFixed(3).padStart(9)} ${entry.databaseMs.toFixed(3).padStart(14)} ${entry.decodeMs.toFixed(3).padStart(12)} ${String(entry.rows).padStart(7)}${entry.error ? \" ERROR\" : \"\"}`,\n start + position === selectedQuery ? \"selected\" : \"text\",\n ),\n );\n }\n\n return lines;\n};\n\nexport const profileScreen = async (\n address: string,\n token: string,\n color: boolean,\n): Promise<void> =>\n withScreen(\n () =>\n new Promise<void>((resolve, reject) => {\n const { style, brand } = theme(color);\n let requests: ProfiledRequest[] = [];\n let selectedRequest = 0;\n let selectedQuery = 0;\n let mode: \"requests\" | \"queries\" | \"sql\" | \"plan\" = \"requests\";\n let offset = 0;\n let error = \"\";\n // The plan tree, as the query inspector shows it.\n let plan: string[] = [];\n let closed = false;\n let pending = false;\n let activeRequest: ProfiledRequest | undefined;\n const wasRaw = process.stdin.isRaw;\n\n const query = (): ProfiledQuery | undefined =>\n activeRequest?.queries[selectedQuery];\n\n const draw = () => {\n const height = Math.max(1, (process.stdout.rows || 24) - 7);\n const selected = query();\n const lines: string[] = [];\n\n // Narrow terminals shorten labels and drop columns rather than\n // cutting the timings off.\n const width = terminalWidth();\n const labelWidth = Math.max(12, Math.min(42, width - 35));\n\n if (mode === \"requests\") {\n lines.push(\n style(\n `${\"Request\".padEnd(labelWidth + 3)}SQL Build Total`,\n \"muted\",\n ),\n );\n const start = Math.max(0, selectedRequest - height + 2);\n\n for (const [position, request] of requests\n .slice(start, start + height - 1)\n .entries()) {\n const duplicates =\n request.queries.length -\n new Set(request.queries.map((entry) => entry.sql)).size;\n lines.push(\n style(\n `${start + position === selectedRequest ? \"›\" : \" \"} ${fitLine(request.label, labelWidth).padEnd(labelWidth)} ${String(request.queries.length).padStart(3)} ${request.buildMs.toFixed(2).padStart(7)} ${request.durationMs.toFixed(2).padStart(7)}${duplicates ? ` ↻ ${duplicates}` : \"\"}${request.error ? \" ERROR\" : \"\"}`,\n start + position === selectedRequest ? \"selected\" : \"text\",\n ),\n );\n }\n\n if (!requests.length) {\n lines.push(\n \"Waiting for queries… Send a request to your application.\",\n );\n }\n } else if (mode === \"queries\") {\n lines.push(\n ...requestLines(activeRequest!, selectedQuery, {\n width,\n height,\n style,\n }),\n );\n } else {\n const wrapped =\n mode === \"plan\"\n ? wrapExplainLines(plan, terminalWidth())\n : wrapLines(\n `${selected!.sql}\\n\\nParameters\\n${JSON.stringify(selected!.parameters, null, 2)}${selected!.error ? `\\n\\n${selected!.error}` : \"\"}`,\n );\n offset = Math.min(offset, Math.max(0, wrapped.length - height));\n lines.push(...wrapped.slice(offset, offset + height));\n }\n\n process.stdout.write(\n `\\u001b[H\\u001b[2J ${fitLine(`${brand()} ${style(\"/ live profiler\", \"muted\")}`)}\\n ${style(fitLine(error || address), error ? \"danger\" : \"muted\")}\\n\\n${lines.map((line) => ` ${fitLine(line)}`).join(\"\\n\")}\\u001b[${Math.max(1, (process.stdout.rows || 24) - 1)};1H ${style(fitLine(\"↑ ↓ navigate · enter open · esc back · e explain · a analyze · q quit\"), \"muted\")}`,\n );\n };\n\n const refresh = async () => {\n if (pending || closed) {\n return;\n }\n\n pending = true;\n\n try {\n const response = await fetch(new URL(\"/requests\", address), {\n headers: { \"x-symmetria-token\": token },\n signal: AbortSignal.timeout(3000),\n });\n\n if (!response.ok) {\n throw new Error(profilerHttpError(response.status));\n }\n\n const updated = (await response.json()) as ProfiledRequest[];\n\n if (!Array.isArray(updated)) {\n throw new Error(\"Invalid profiler response\");\n }\n\n const selectedId = requests[selectedRequest]?.id;\n requests = updated.toSorted((left, right) => right.id - left.id);\n selectedRequest = Math.max(\n 0,\n requests.findIndex((entry) => entry.id === selectedId),\n );\n error = \"\";\n } catch (cause) {\n error = cause instanceof Error ? cause.message : String(cause);\n } finally {\n pending = false;\n\n if (!closed) {\n draw();\n } else {\n resolve();\n }\n }\n };\n\n const explain = async (analyze: boolean) => {\n const selected = query();\n\n if (!selected || pending) {\n return;\n }\n\n pending = true;\n error = analyze\n ? \"Running EXPLAIN ANALYZE…\"\n : \"Estimating query plan…\";\n draw();\n\n try {\n const response = await fetch(\n new URL(`/explain?id=${selected.id}&analyze=${analyze}`, address),\n {\n method: \"POST\",\n headers: { \"x-symmetria-token\": token },\n signal: AbortSignal.timeout(30000),\n },\n );\n const result = await response.json();\n\n if (!response.ok) {\n throw new Error(\n result && typeof result === \"object\" && \"error\" in result\n ? String(result.error)\n : `HTTP ${response.status}`,\n );\n }\n\n plan = Array.isArray(result) ? explainLines(result) : [];\n\n if (!plan.length) {\n plan = JSON.stringify(result, null, 2).split(\"\\n\");\n }\n\n mode = \"plan\";\n offset = 0;\n error = \"\";\n } catch (cause) {\n error = cause instanceof Error ? cause.message : String(cause);\n } finally {\n pending = false;\n\n if (!closed) {\n draw();\n } else {\n resolve();\n }\n }\n };\n\n const finish = () => {\n if (closed) {\n return;\n }\n\n closed = true;\n clearInterval(timer);\n process.stdin.off(\"keypress\", keypress);\n process.stdin.off(\"end\", finish);\n process.stdout.off(\"resize\", draw);\n process.stdin.setRawMode(wasRaw);\n process.stdin.pause();\n\n if (!pending) {\n resolve();\n }\n };\n\n const keypress = (\n input: string,\n key: { name?: string; ctrl?: boolean },\n ) => {\n if (input === \"q\" || (key.ctrl && key.name === \"c\")) {\n finish();\n\n return;\n }\n\n if (key.name === \"escape\" || key.name === \"left\") {\n if (mode === \"requests\") {\n finish();\n\n return;\n }\n\n mode = mode === \"queries\" ? \"requests\" : \"queries\";\n offset = 0;\n } else if (key.name === \"return\") {\n if (mode === \"requests\" && requests[selectedRequest]) {\n activeRequest = requests[selectedRequest];\n selectedQuery = 0;\n mode = \"queries\";\n } else if (mode === \"queries\" && query()) {\n mode = \"sql\";\n offset = 0;\n }\n } else if (input === \"e\" || input === \"a\") {\n if (mode !== \"requests\") {\n void explain(input === \"a\");\n }\n } else if (\n [\"up\", \"down\", \"pageup\", \"pagedown\"].includes(key.name ?? \"\")\n ) {\n const direction =\n key.name === \"up\" || key.name === \"pageup\" ? -1 : 1;\n const step = key.name?.startsWith(\"page\") ? 10 : 1;\n\n if (mode === \"requests\") {\n selectedRequest = Math.max(\n 0,\n Math.min(\n requests.length - 1,\n selectedRequest + direction * step,\n ),\n );\n } else if (mode === \"queries\") {\n selectedQuery = Math.max(\n 0,\n Math.min(\n activeRequest!.queries.length - 1,\n selectedQuery + direction * step,\n ),\n );\n } else {\n offset = Math.max(0, offset + direction * step);\n }\n }\n\n draw();\n };\n\n emitKeypressEvents(process.stdin);\n process.stdin.setRawMode(true);\n process.stdin.resume();\n process.stdin.on(\"keypress\", keypress);\n process.stdin.once(\"end\", finish);\n process.stdout.on(\"resize\", draw);\n process.stdout.write(\"\\u001b[?25l\");\n const timer = setInterval(() => {\n void refresh();\n }, 500);\n draw();\n void refresh().catch(reject);\n }),\n );\n","import { profileScreen, profilerHttpError } from \"../screens/profiler\";\nimport type { CliContext } from \"../context\";\n\n/** `profile`: the live profiler screen, or its JSON feed when not interactive. */\nexport const profile = async (context: CliContext): Promise<void> => {\n const { values, interactive, color, output } = context;\n const address = values[\"profile-url\"] ?? \"http://127.0.0.1:7331\";\n const token = values[\"profile-token\"] ?? process.env.SYMMETRIA_PROFILE_TOKEN;\n\n if (!token) {\n throw new Error(\n \"symmetria: profile requires --profile-token or SYMMETRIA_PROFILE_TOKEN, the token configured for or returned by profiler.serve()\",\n );\n }\n\n if (interactive) {\n return profileScreen(address, token, color);\n }\n\n const response = await fetch(new URL(\"/requests\", address), {\n headers: { \"x-symmetria-token\": token },\n });\n\n if (!response.ok) {\n throw new Error(profilerHttpError(response.status));\n }\n\n output(JSON.stringify({ requests: await response.json() }, null, 2));\n};\n","import { mkdir, writeFile } from \"node:fs/promises\";\nimport { basename, dirname, resolve } from \"node:path\";\nimport { pullSchema } from \"../../introspection\";\nimport { loadProject, withDatabase, type CliContext } from \"../context\";\nimport { formatCreated, formatPullWarnings } from \"../ui/format\";\n\n/**\n * `pull [file]`: introspect the configured database and write a schema module.\n * The connection comes from --database-url, the config (when it loads) or DATABASE_URL.\n */\nexport const pull = async (\n context: CliContext,\n name: string | undefined,\n): Promise<void> => {\n const { values, color } = context;\n const path = resolve(name ?? \"schema.ts\");\n const explicit = values[\"database-url\"] ?? process.env.DATABASE_URL;\n const project = await loadProject(context).catch((error: unknown) => {\n // A config that imports the schema module being generated cannot load yet.\n if (!explicit) {\n throw error;\n }\n\n return undefined;\n });\n const databaseUrl =\n values[\"database-url\"] ?? project?.databaseUrl ?? explicit;\n const { metadataSchema, metadataTable } = project?.config ?? {};\n // Only the tables the config and flags name: Prisma's history table, which\n // other commands leave out on their own, stays listed for review here.\n const ignoreTables = [\n ...new Set([\n ...(project?.config.ignoreTables ?? []),\n ...(values[\"ignore-table\"] ?? []),\n ]),\n ];\n const result = await withDatabase({ databaseUrl }, (driver) =>\n context.progress(\"Reading the database\", () =>\n pullSchema({\n execute: driver.execute,\n ...(metadataSchema ? { metadataSchema } : {}),\n ...(metadataTable ? { metadataTable } : {}),\n ...(ignoreTables.length ? { ignoreTables } : {}),\n }),\n ),\n );\n\n await mkdir(dirname(path), { recursive: true });\n\n try {\n await writeFile(path, result.source, { flag: values.force ? \"w\" : \"wx\" });\n } catch (error) {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"EEXIST\"\n ) {\n throw new Error(`symmetria: ${path} exists; use --force to overwrite it`);\n }\n\n throw error;\n }\n\n const summary = `${result.tables.length} ${result.tables.length === 1 ? \"table\" : \"tables\"} from schema \"${result.schemaName}\"`;\n context.emit({\n json: {\n path,\n schema: result.schemaName,\n tables: result.tables,\n enumerations: result.enumerations,\n warnings: result.warnings,\n },\n indent: 2,\n pretty: () =>\n `${formatCreated(dirname(path), [basename(path)], color)} ${context.style(summary, \"muted\")}\\n\\n${formatPullWarnings(result.warnings, color)}`,\n plain: () =>\n [\n \"Created\",\n ` ${path}`,\n ` ${summary}`,\n \"\",\n ...(result.warnings.length\n ? [\n `Review (${result.warnings.length})`,\n ...result.warnings.flatMap((warning) => [\n ` [${warning.code}] ${warning.message}`,\n ...(warning.fix ? [` fix: ${warning.fix}`] : []),\n ]),\n ]\n : [\"Nothing needs review; the schema matches the database.\"]),\n ].join(\"\\n\"),\n });\n};\n","import type { MigrationDiffOptions, MigrationSnapshot } from \"../../index\";\nimport type { Choose } from \"../ui/terminal\";\n\n/** Suggestions are decisions, never guessed renames; persisted SQL records the result. */\nexport const resolveRenames = async (\n before: MigrationSnapshot,\n after: MigrationSnapshot,\n select: Choose,\n options: MigrationDiffOptions = {},\n): Promise<MigrationDiffOptions> => {\n const tables = { ...options.renames?.tables };\n const columns: Record<string, Record<string, string>> = Object.fromEntries(\n Object.entries(options.renames?.columns ?? {}).map(([name, entries]) => [\n name,\n { ...entries },\n ]),\n );\n\n const shape = (table: MigrationSnapshot[\"tables\"][number]) =>\n JSON.stringify(\n table.columns.map((column) => [\n column.name,\n column.sqlType,\n column.notNull,\n ]),\n );\n\n for (const old of before.tables.filter(\n (table) =>\n !tables[table.name] &&\n !after.tables.some((next) => next.name === table.name),\n )) {\n const candidates = after.tables.filter(\n (next) =>\n !Object.values(tables).includes(next.name) &&\n !before.tables.some((table) => table.name === next.name) &&\n shape(old) === shape(next),\n );\n\n if (!candidates.length) {\n continue;\n }\n\n const choice = await select(\n `Table ${old.name} disappeared. How should this change be represented?`,\n [\n ...candidates.map(\n (candidate) => `Rename ${old.name} → ${candidate.name}`,\n ),\n \"Drop and add tables\",\n ],\n );\n\n if (choice === undefined) {\n throw new Error(\"symmetria: migration generation cancelled\");\n }\n\n if (choice < candidates.length) {\n tables[old.name] = candidates[choice]!.name;\n }\n }\n\n for (const oldTable of before.tables) {\n const table = after.tables.find(\n (next) => next.name === (tables[oldTable.name] ?? oldTable.name),\n );\n\n if (!table) {\n continue;\n }\n\n const hints = columns[table.name] ?? {};\n\n for (const old of oldTable.columns.filter(\n (column) =>\n !hints[column.name] &&\n !table.columns.some((next) => next.name === column.name),\n )) {\n const candidates = table.columns.filter(\n (next) =>\n !Object.values(hints).includes(next.name) &&\n !oldTable.columns.some((column) => column.name === next.name) &&\n next.sqlType === old.sqlType &&\n next.notNull === old.notNull,\n );\n\n if (!candidates.length) {\n continue;\n }\n\n const choice = await select(\n `${table.name}.${old.name} disappeared. How should this change be represented?`,\n [\n ...candidates.map(\n (candidate) => `Rename ${old.name} → ${candidate.name}`,\n ),\n \"Drop column and add new columns\",\n ],\n );\n\n if (choice === undefined) {\n throw new Error(\"symmetria: migration generation cancelled\");\n }\n\n if (choice < candidates.length) {\n hints[old.name] = candidates[choice]!.name;\n }\n }\n\n if (Object.keys(hints).length) {\n columns[table.name] = hints;\n }\n }\n\n return { ...options, renames: { tables, columns } };\n};\n","/**\n * Schema-only CLI commands that need no database: inspect, lint, diff and generate.\n */\nimport { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { postgres } from \"symmetria/driver\";\nimport type { SchemaSnapshot } from \"symmetria\";\nimport {\n diffSchemas,\n formatLintFindings,\n generateMigration,\n lintMigration,\n lintMigrationSQL,\n loadMigrationState,\n migrationSnapshot,\n migrator,\n type MigrationDiffOptions,\n} from \"../../index\";\nimport { formatCreated, formatDiff, formatSchema } from \"../ui/format\";\nimport { inspectSchema } from \"../screens/schema-browser\";\nimport { resolveRenames } from \"../screens/rename-prompt\";\nimport { ask, withScreen } from \"../ui/terminal\";\nimport type { CliContext, Project } from \"../context\";\n\n/** The declared schema, required unless the command can run without one. */\nconst declaredSchema = (\n project: Project,\n required: boolean,\n): SchemaSnapshot | undefined => {\n const snapshot = project.snapshot();\n\n if (required && !snapshot) {\n throw new Error(\n \"symmetria: configure schema in symmetria.config.ts before inspecting or generating a migration\",\n );\n }\n\n return snapshot;\n};\n\nconst readDiffOptions = async (\n context: CliContext,\n): Promise<MigrationDiffOptions> => {\n const { values } = context;\n const options: MigrationDiffOptions = values.diff\n ? JSON.parse(await readFile(resolve(values.diff), \"utf8\"))\n : {};\n\n return values.online ? { ...options, online: true } : options;\n};\n\n/** `inspect [table]`: the schema browser, or a listing of tables, columns and relations. */\nexport const inspect = async (\n context: CliContext,\n project: Project,\n name: string | undefined,\n): Promise<void> => {\n const { values, color } = context;\n const snapshot = declaredSchema(project, true)!;\n const tables = name\n ? snapshot.tables.filter(\n (table) => table.name === name || table.sqlName === name,\n )\n : snapshot.tables;\n\n if (name && !tables.length) {\n throw new Error(`symmetria: unknown table \"${name}\"`);\n }\n\n if (context.interactive) {\n return withScreen(() =>\n inspectSchema(snapshot, {\n color,\n ...(name ? { table: name } : {}),\n tab: values.relations ? \"Relations\" : \"Columns\",\n }),\n );\n }\n\n context.emit({\n json: {\n tables: values.relations\n ? tables.map((table) => ({\n name: table.name,\n relations: table.relations,\n }))\n : tables,\n },\n replacer: (_name, value) =>\n typeof value === \"bigint\" ? value.toString() : value,\n indent: 2,\n plain: () => formatSchema(snapshot, name, values.relations, color),\n });\n};\n\n/** `lint`: review saved up.sql files and the ungenerated schema diff. */\nexport const lint = async (\n context: CliContext,\n project: Project,\n): Promise<void> => {\n const { values } = context;\n const diffOptions = await readDiffOptions(context);\n const snapshot = declaredSchema(project, false);\n const { snapshot: before, migrations } = await loadMigrationState(\n project.directory,\n );\n const after = snapshot ? migrationSnapshot(snapshot) : before;\n const plan = diffSchemas(before, after, diffOptions);\n let selected = migrations;\n\n if (values.pending) {\n if (!project.databaseUrl) {\n throw new Error(\n \"symmetria: --pending needs a database: set databaseUrl in the config, DATABASE_URL or --database-url\",\n );\n }\n\n const driver = postgres(project.databaseUrl);\n\n try {\n const statuses = await migrator({\n driver,\n ...project.runnerOptions,\n }).status();\n\n if (statuses.some((entry) => entry.status === \"incomplete\")) {\n throw new Error(\n \"symmetria: repair incomplete migrations before linting the pending chain\",\n );\n }\n\n selected = migrations.filter((migration) =>\n statuses.some(\n (status) => status.id === migration.id && status.status === \"pending\",\n ),\n );\n } finally {\n await driver.close();\n }\n }\n\n const findings = [\n ...selected.flatMap((migration) =>\n lintMigrationSQL(migration.up, migration.id),\n ),\n ...lintMigration(plan, diffOptions.renames),\n ];\n context.emit({\n json: { findings },\n indent: 2,\n plain: () => formatLintFindings(findings),\n });\n\n if (\n findings.some((finding) => values.strict || finding.level !== \"caution\")\n ) {\n process.exitCode = 1;\n }\n};\n\n/** `diff`: compare the declared schema with the latest local snapshot. */\nexport const diff = async (\n context: CliContext,\n project: Project,\n): Promise<void> => {\n const { values, color, output } = context;\n const diffOptions = await readDiffOptions(context);\n const snapshot = declaredSchema(project, true)!;\n const { snapshot: before } = await loadMigrationState(project.directory);\n const plan = diffSchemas(before, migrationSnapshot(snapshot), diffOptions);\n\n if (values.sql) {\n output(plan.up.map((statement) => `${statement};`).join(\"\\n\\n\"));\n\n return;\n }\n\n context.emit({\n json: plan,\n indent: 2,\n plain: () => formatDiff(plan, color, diffOptions.renames),\n });\n};\n\n/** `generate [name]`: write up.sql, down.sql and the versioned snapshot. */\nexport const generate = async (\n context: CliContext,\n project: Project,\n requestedName: string | undefined,\n): Promise<void> => {\n const { values, color, pretty, interactive, output } = context;\n let diffOptions = await readDiffOptions(context);\n const snapshot = declaredSchema(project, !values.empty);\n const { snapshot: before } = await loadMigrationState(project.directory);\n const after =\n snapshot && !values.empty ? migrationSnapshot(snapshot) : before;\n\n if (interactive && !values.empty) {\n diffOptions = await resolveRenames(\n before,\n after,\n context.select,\n diffOptions,\n );\n }\n\n const plan = diffSchemas(before, after, diffOptions);\n const name = requestedName ?? (await ask(\"Migration name:\", color));\n\n if (!name) {\n throw new Error(\"symmetria: generate requires a migration name\");\n }\n\n if (pretty && !values.json && !values.empty) {\n output(formatDiff(plan, color, diffOptions.renames));\n }\n\n const migration = await context.progress(\"Writing migration\", () =>\n generateMigration({\n ...diffOptions,\n directory: project.directory,\n name,\n ...(snapshot ? { snapshot } : {}),\n ...(values.empty ? { empty: true } : {}),\n ...(values[\"allow-destructive\"] ? { allowDestructive: true } : {}),\n ...(values.transaction\n ? { transaction: values.transaction as \"batch\" | \"each\" | \"none\" }\n : {}),\n ...(values.online ? { online: true } : {}),\n }),\n );\n const directory = project.directory;\n context.emit({\n json: migration\n ? {\n id: migration.id,\n directory: resolve(directory, migration.id),\n metadataDirectory: resolve(directory, \"meta\"),\n up: migration.up,\n down: migration.down,\n }\n : { id: null, changed: false },\n pretty: () =>\n migration\n ? formatCreated(\n directory,\n [\n `${migration.id}/up.sql`,\n `${migration.id}/down.sql`,\n \"meta/snapshot.json\",\n \"meta/migration.json\",\n ],\n color,\n )\n : \"No schema changes.\",\n plain: () =>\n migration ? `Generated ${migration.id}` : \"No schema changes.\",\n });\n};\n","/**\n * Dispatches a parsed command line to the command implementation in ./schema, ./database,\n * ./files, ./graph, ./init, ./pull or ./profile.\n */\nimport { loadProject, type CliContext } from \"../context\";\nimport type { Command } from \"../options\";\nimport { dashboard } from \"../screens/dashboard\";\nimport {\n adopt,\n drift,\n migrate,\n repair,\n rollback,\n status,\n verify,\n} from \"./database\";\nimport { recover, squash } from \"./files\";\nimport { graph } from \"./graph\";\nimport { init } from \"./init\";\nimport { profile } from \"./profile\";\nimport { pull } from \"./pull\";\nimport { diff, generate, inspect, lint } from \"./schema\";\n\n/** Runs one command; every command except `profile`, `init` and `pull` works on the loaded project. */\nexport const runCommand = async (\n command: Command,\n name: string | undefined,\n context: CliContext,\n): Promise<void> => {\n switch (command) {\n case \"profile\":\n return profile(context);\n case \"init\":\n return init(context, name);\n case \"pull\":\n return pull(context, name);\n default:\n }\n\n const project = await loadProject(context);\n\n switch (command) {\n case \"recover\":\n return recover(context, project);\n case \"squash\":\n return squash(context, project, name!);\n case \"dashboard\":\n return dashboard(context, project);\n case \"inspect\":\n return inspect(context, project, name);\n case \"graph\":\n return graph(context, project, name);\n case \"lint\":\n return lint(context, project);\n case \"diff\":\n return diff(context, project);\n case \"generate\":\n return generate(context, project, name);\n case \"verify\":\n return verify(context, project);\n case \"drift\":\n return drift(context, project);\n case \"repair\":\n return repair(context, project, name!);\n case \"adopt\":\n return adopt(context, project);\n case \"status\":\n return status(context, project);\n case \"migrate\":\n return migrate(context, project);\n case \"rollback\":\n return rollback(context, project);\n }\n};\n","/** Command-line surface: help text, flag parsing and the rules that tie flags to commands. */\nimport { parseArgs } from \"node:util\";\n\nexport const help = `symmetria <command>\n\n init [directory] Create modular tables, connection and migration config\n pull [file] Write a schema module for an existing database (default: schema.ts)\n diff Compare schema code with the latest migration snapshot\n lint Review saved up.sql files and ungenerated schema changes\n inspect [table] Inspect tables, columns, relations, indexes and checks\n graph [file] Print or write a Mermaid entity-relationship diagram\n profile Observe live application requests and SQL timings\n generate <name> Generate up.sql and down.sql, and update the snapshot\n migrate Apply pending migrations atomically\n status Show applied and pending migrations\n rollback Revert the latest migration\n squash <name> Replace the migration chain with one baseline migration\n adopt Record the local chain as applied after a squash or baseline\n drift Compare the live database with the latest migration snapshot\n verify Exercise installation, upgrade and rollback in disposable databases\n repair <id> Resolve an incomplete migration after verifying its schema\n recover Recover files left by a crashed generation process\n (no command) Open the interactive dashboard in a terminal\n\n --config <file> Config module (default: symmetria.config.ts)\n --dir <directory> Override the migrations directory\n --database-url <url> Override config/database environment URL\n --profile-url <url> Profiler endpoint (default: http://127.0.0.1:7331)\n --profile-token <t> Profiler token (default: SYMMETRIA_PROFILE_TOKEN)\n --diff <file.json> Explicit rename hints and USING conversions for generate\n --empty Generate an empty, editable SQL migration\n --allow-destructive Explicitly permit destructive generation\n --allow-custom-sql squash: drop SQL that generate did not write (seeds, edits)\n --transaction <mode> batch (default), each, or none\n --pending Lint only migrations pending in the configured database\n --online generate/diff/lint: concurrent indexes and phased validation (transaction none)\n --plan Show SQL and transaction groups without executing migrations\n --action <action> repair: retry or complete, after manual data reconciliation\n --verify-url <url> Administrative PostgreSQL URL for disposable verification databases\n --snapshot <file> repair: meta/snapshot.json of the boundary to verify, instead of --verify-url\n --advisory-lock-timeout <ms> Migration lock wait (default: 10000)\n --lock-timeout <ms> DDL lock wait (default: 5000; 0 disables)\n --statement-timeout <ms> Statement duration (default: 600000, no default in transaction none migrations; 0 disables)\n --to <migration-id> Apply up to a migration\n --ignore-table <name> pull/drift/adopt/repair/verify: leave an undeclared table out (repeatable)\n --steps <number> Number of migrations to rollback (default: 1)\n --yes rollback: run down.sql without asking (required without a terminal)\n --strict Exit with code 1 when lint or drift report findings\n --force Overwrite the file written by pull or graph\n --compact graph: entities and relations without column lists\n --sql Print executable SQL for diff\n --json Machine-readable output\n --relations Show the relation graph with inspect\n --no-color Disable terminal colors\n --no-animation Disable logo and loading animations\n --no-interactive Disable dashboard, schema browser and rename questions\n --help, -h Show this help\n`;\n\nconst COMMANDS = [\n \"generate\",\n \"migrate\",\n \"status\",\n \"rollback\",\n \"init\",\n \"pull\",\n \"graph\",\n \"diff\",\n \"lint\",\n \"squash\",\n \"adopt\",\n \"drift\",\n \"inspect\",\n \"dashboard\",\n \"profile\",\n \"verify\",\n \"repair\",\n \"recover\",\n] as const;\nexport type Command = (typeof COMMANDS)[number];\n\n/** Every flag; `--help`, the README and the reference list each one. */\nexport const FLAGS = {\n config: { type: \"string\" },\n dir: { type: \"string\" },\n \"database-url\": { type: \"string\" },\n \"profile-url\": { type: \"string\" },\n \"profile-token\": { type: \"string\" },\n diff: { type: \"string\" },\n strict: { type: \"boolean\" },\n force: { type: \"boolean\" },\n compact: { type: \"boolean\" },\n empty: { type: \"boolean\" },\n \"allow-destructive\": { type: \"boolean\" },\n \"allow-custom-sql\": { type: \"boolean\" },\n \"ignore-table\": { type: \"string\", multiple: true },\n transaction: { type: \"string\" },\n pending: { type: \"boolean\" },\n online: { type: \"boolean\" },\n plan: { type: \"boolean\" },\n action: { type: \"string\" },\n \"verify-url\": { type: \"string\" },\n snapshot: { type: \"string\" },\n \"advisory-lock-timeout\": { type: \"string\" },\n \"lock-timeout\": { type: \"string\" },\n \"statement-timeout\": { type: \"string\" },\n to: { type: \"string\" },\n steps: { type: \"string\" },\n yes: { type: \"boolean\" },\n help: { type: \"boolean\", short: \"h\" },\n sql: { type: \"boolean\" },\n json: { type: \"boolean\" },\n relations: { type: \"boolean\" },\n \"no-color\": { type: \"boolean\" },\n \"no-animation\": { type: \"boolean\" },\n \"no-interactive\": { type: \"boolean\" },\n} as const;\n\nexport const parseCommandLine = (argumentsList: string[]) =>\n parseArgs({\n args: argumentsList,\n allowPositionals: true,\n strict: true,\n options: FLAGS,\n });\n\ntype CommandLine = ReturnType<typeof parseCommandLine>;\nexport type CliValues = CommandLine[\"values\"];\n\n/** Commands that take a second positional argument (a name or an ID). */\nconst NAMED: readonly Command[] = [\n \"generate\",\n \"inspect\",\n \"init\",\n \"pull\",\n \"graph\",\n \"squash\",\n \"repair\",\n];\n\n/** Flags that belong to specific commands, with the exact refusal wording. */\nconst SCOPED_FLAGS: readonly {\n readonly flags: readonly (keyof CliValues)[];\n readonly commands: readonly Command[];\n readonly message: string;\n}[] = [\n {\n flags: [\"allow-destructive\", \"transaction\"],\n commands: [\"generate\"],\n message:\n \"symmetria: --allow-destructive and --transaction are generate options\",\n },\n {\n flags: [\"online\"],\n commands: [\"generate\", \"diff\", \"lint\"],\n message: \"symmetria: --online is a generate/diff/lint option\",\n },\n {\n flags: [\"allow-custom-sql\"],\n commands: [\"squash\"],\n message: \"symmetria: --allow-custom-sql is a squash option\",\n },\n {\n flags: [\"ignore-table\"],\n commands: [\"pull\", \"drift\", \"adopt\", \"repair\", \"verify\"],\n message:\n \"symmetria: --ignore-table is a pull/drift/adopt/repair/verify option\",\n },\n {\n flags: [\"pending\"],\n commands: [\"lint\"],\n message: \"symmetria: --pending is a lint option\",\n },\n {\n flags: [\"plan\"],\n commands: [\"migrate\", \"rollback\"],\n message: \"symmetria: --plan is a migrate/rollback option\",\n },\n {\n flags: [\"action\"],\n commands: [\"repair\"],\n message: \"symmetria: --action is a repair option\",\n },\n {\n flags: [\"snapshot\"],\n commands: [\"repair\"],\n message: \"symmetria: --snapshot is a repair option\",\n },\n {\n flags: [\"strict\"],\n commands: [\"lint\", \"drift\"],\n message: \"symmetria: --strict is a lint/drift option\",\n },\n {\n flags: [\"diff\"],\n commands: [\"generate\", \"diff\", \"lint\"],\n message:\n \"symmetria: --diff is for generate/diff/lint; --empty is for generate\",\n },\n {\n flags: [\"empty\"],\n commands: [\"generate\"],\n message:\n \"symmetria: --diff is for generate/diff/lint; --empty is for generate\",\n },\n {\n flags: [\"sql\"],\n commands: [\"diff\"],\n message: \"symmetria: --sql is a diff option\",\n },\n {\n flags: [\"relations\"],\n commands: [\"inspect\"],\n message: \"symmetria: --relations is an inspect option\",\n },\n {\n flags: [\"to\"],\n commands: [\"migrate\", \"adopt\"],\n message: \"symmetria: --to is a migrate/adopt option\",\n },\n {\n flags: [\"steps\"],\n commands: [\"rollback\"],\n message: \"symmetria: --steps is a rollback option\",\n },\n {\n flags: [\"yes\"],\n commands: [\"rollback\"],\n message: \"symmetria: --yes is a rollback option\",\n },\n {\n flags: [\"force\"],\n commands: [\"pull\", \"graph\"],\n message: \"symmetria: --force is a pull/graph option\",\n },\n {\n flags: [\"compact\"],\n commands: [\"graph\"],\n message: \"symmetria: --compact is a graph option\",\n },\n];\n\n/** Resolves the command and its name, then rejects flags and arguments that do not fit it. */\nexport const resolveCommand = (\n { values, positionals }: CommandLine,\n interactive: boolean,\n): { command: Command; name: string | undefined } => {\n const command = (positionals[0] ?? \"dashboard\") as Command;\n const name = positionals[1];\n\n if (!COMMANDS.includes(command)) {\n throw new Error(`symmetria: unknown command \"${command}\"`);\n }\n\n if (positionals.length > (NAMED.includes(command) ? 2 : 1)) {\n throw new Error(\"symmetria: unexpected positional arguments\");\n }\n\n if (command === \"generate\" && !name && !interactive) {\n throw new Error(\"symmetria: generate requires a migration name\");\n }\n\n if (command === \"squash\" && !name) {\n throw new Error(\"symmetria: squash requires a migration name\");\n }\n\n for (const rule of SCOPED_FLAGS) {\n if (\n !rule.commands.includes(command) &&\n rule.flags.some((flag) => values[flag])\n ) {\n throw new Error(rule.message);\n }\n }\n\n if (\n values.transaction &&\n ![\"batch\", \"each\", \"none\"].includes(values.transaction)\n ) {\n throw new Error(\"symmetria: --transaction must be batch, each, or none\");\n }\n\n if (\n command === \"repair\" &&\n (!name || ![\"retry\", \"complete\"].includes(values.action ?? \"\"))\n ) {\n throw new Error(\n \"symmetria: repair requires an ID and --action retry|complete\",\n );\n }\n\n if (values.sql && values.json) {\n throw new Error(\"symmetria: choose either --sql or --json\");\n }\n\n return { command, name };\n};\n","#!/usr/bin/env node\n/**\n * `symmetria` command line. Parsing and flag rules live in ./options,\n * the shared environment in ./context and each command in ./commands.\n */\nimport { runCommand } from \"./commands\";\nimport { createContext, type Output } from \"./context\";\nimport { formatHelp } from \"./ui/format\";\nimport { help, parseCommandLine, resolveCommand } from \"./options\";\nimport { formatError, supportsColor } from \"./ui/style\";\nimport { sqlState } from \"symmetria\";\nimport { MigrationExecutionError } from \"../migrations/execution\";\n\n/** A failure as JSON: the message, plus the failing statement for migration errors. */\nconst errorJSON = (error: unknown, message: string) => {\n if (error instanceof MigrationExecutionError) {\n return {\n message,\n migration: error.migration,\n direction: error.direction,\n statement: error.statement,\n sql: error.sql,\n ...(error.sqlState ? { sqlState: error.sqlState } : {}),\n ...(error.detail ? { detail: error.detail } : {}),\n };\n }\n\n const state = sqlState(error);\n\n return state ? { message, sqlState: state } : { message };\n};\n\nconst runMigrationCLI = async (\n argumentsList: string[],\n output: Output = (message) => console.log(message),\n): Promise<void> => {\n const parsed = parseCommandLine(argumentsList);\n const context = createContext(parsed.values, output, runMigrationCLI);\n\n if (\n parsed.values.help ||\n (!parsed.positionals.length && !context.interactive)\n ) {\n output(\n context.pretty && !parsed.values.json && !parsed.values.sql\n ? formatHelp(help, context.color)\n : help,\n );\n\n return;\n }\n\n const { command, name } = resolveCommand(parsed, context.interactive);\n await runCommand(command, name, context);\n};\n\nif (import.meta.main) {\n try {\n try {\n // Bun loads .env on its own; releases before 1.4 lack process.loadEnvFile.\n process.loadEnvFile?.();\n } catch (error) {\n if (\n !(\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n )\n ) {\n throw error;\n }\n }\n\n await runMigrationCLI(process.argv.slice(2));\n } catch (error) {\n let cause: unknown = error;\n const messages: string[] = [];\n\n while (cause instanceof Error) {\n const { message } = cause;\n\n // Wrappers such as MigrationExecutionError already quote their cause.\n if (!messages.some((previous) => previous.includes(message))) {\n messages.push(message);\n }\n\n cause = cause.cause;\n }\n\n const message = messages.length ? messages.join(\"\\n\") : String(error);\n\n if (process.argv.includes(\"--json\")) {\n // Machine-readable runs get JSON on failure too, on stdout like a result.\n console.log(JSON.stringify({ error: errorJSON(error, message) }));\n } else {\n console.error(\n formatError(\n message,\n supportsColor() &&\n !process.argv.includes(\"--no-color\") &&\n !process.argv.includes(\"--sql\"),\n ),\n );\n }\n\n // Ctrl-C and SIGTERM already chose 130 and 143.\n if (!process.exitCode) {\n process.exitCode = 1;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8CA,MAAa,iBACX,QACA,QACA,UACe;CACf,MAAM,SAAS,CAAC,CAAC,QAAQ,OAAO,SAAS,QAAQ,IAAI,SAAS;CAC9D,MAAM,cACJ,CAAC,CAAC,QAAQ,MAAM,SAChB,UACA,CAAC,OAAO,qBACR,CAAC,OAAO,QACR,CAAC,OAAO;CACV,MAAM,QACJ,cAAc,KAAK,CAAC,OAAO,eAAe,CAAC,OAAO,QAAQ,CAAC,OAAO;CACpE,MAAM,EAAE,UAAU,MAAM,KAAK;CAE7B,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA,WAAW,OAAO,cAChB,YAAY,OAAO,WAAW;GAC5B,SAAS,UAAU,CAAC,OAAO,QAAQ,CAAC,OAAO;GAC3C;GACA,WAAW,CAAC,OAAO;EACrB,CAAC;EACH,SAAS,UAAU,YAAY,OAAO,UAAU,SAAS,EAAE,MAAM,CAAC;EAClE,OAAO,cAAc;GACnB,OACE,OAAO,OACH,KAAK,UAAU,UAAU,MAAM,UAAU,UAAU,UAAU,MAAM,IACn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,SAAS,YAAY,KACnC,CAAC,QAAQ,KAAK,SAAS,OAAO,CAClC,CACF;CAIF,IAAI,CAAC,QAAQ,UACX,QAAQ,WAAW;AAEvB"}
1
+ {"version":3,"file":"cli.js","names":["inspect","inspect"],"sources":["../src/cli/context.ts","../src/cli/screens/schema-browser.ts","../src/cli/screens/dashboard.ts","../src/cli/screens/rollback-prompt.ts","../src/cli/commands/database.ts","../src/cli/commands/files.ts","../src/cli/commands/graph.ts","../src/cli/scaffold.ts","../src/cli/commands/init.ts","../src/cli/screens/profiler.ts","../src/cli/commands/profile.ts","../src/cli/commands/pull.ts","../src/cli/screens/rename-prompt.ts","../src/cli/commands/schema.ts","../src/cli/commands/index.ts","../src/cli/options.ts","../src/cli/index.ts"],"sourcesContent":["/** Everything a command needs: terminal mode, output, the project configuration and a database driver. */\nimport { access } from \"node:fs/promises\";\nimport * as nodeModule from \"node:module\";\nimport { dirname, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { postgres, type PostgresDriver } from \"symmetria/driver\";\nimport type { SchemaSnapshot } from \"symmetria\";\nimport type { MigrationConfig } from \"../migrations/config\";\nimport type { MigratorOptions } from \"../migrations/runner\";\nimport { supportsColor, theme } from \"./ui/style\";\nimport { choose, withSpinner } from \"./ui/terminal\";\nimport type { CliValues } from \"./options\";\n\nexport type Output = (message: string) => void;\n\nexport type CliContext = {\n readonly values: CliValues;\n readonly output: Output;\n /** A terminal that can show formatted output and animations. */\n readonly pretty: boolean;\n /** A terminal that can also ask questions and open screens. */\n readonly interactive: boolean;\n readonly color: boolean;\n readonly style: ReturnType<typeof theme>[\"style\"];\n readonly progress: <Result>(\n label: string,\n operation: () => Promise<Result>,\n ) => Promise<Result>;\n readonly select: (\n question: string,\n choices: readonly string[],\n ) => Promise<number | undefined>;\n /** Prints one of three renderings: JSON when --json, the pretty form on a terminal, else plain text. */\n readonly emit: (rendering: Rendering) => void;\n /** Runs another command in this process, collecting its output (used by the dashboard). */\n readonly rerun: (argumentsList: string[], output: Output) => Promise<void>;\n};\n\ntype Rendering = {\n readonly json: unknown;\n readonly indent?: number;\n readonly replacer?: (name: string, value: unknown) => unknown;\n readonly pretty?: () => string;\n readonly plain: () => string;\n};\n\nexport const createContext = (\n values: CliValues,\n output: Output,\n rerun: CliContext[\"rerun\"],\n): CliContext => {\n const pretty = !!process.stdout.isTTY && process.env.TERM !== \"dumb\";\n const interactive =\n !!process.stdin.isTTY &&\n pretty &&\n !values[\"no-interactive\"] &&\n !values.json &&\n !values.sql;\n const color =\n supportsColor() && !values[\"no-color\"] && !values.json && !values.sql;\n const { style } = theme(color);\n\n return {\n values,\n output,\n pretty,\n interactive,\n color,\n style,\n progress: (label, operation) =>\n withSpinner(label, operation, {\n enabled: pretty && !values.json && !values.sql,\n color,\n animation: !values[\"no-animation\"],\n }),\n select: (question, choices) => choose(question, choices, { color }),\n emit: (rendering) => {\n output(\n values.json\n ? JSON.stringify(rendering.json, rendering.replacer, rendering.indent)\n : pretty && rendering.pretty\n ? rendering.pretty()\n : rendering.plain(),\n );\n },\n rerun,\n };\n};\n\n/** The migration project a command works on: config module, directories and connection settings. */\nexport type Project = {\n readonly configPath: string;\n readonly present: boolean;\n readonly config: MigrationConfig;\n readonly directory: string;\n readonly databaseUrl: string | undefined;\n readonly runnerOptions: Omit<MigratorOptions, \"driver\" | \"signal\">;\n /** The declared schema as a snapshot, when the config has one. */\n readonly snapshot: () => SchemaSnapshot | undefined;\n};\n\nconst TIMEOUT_FLAGS = [\n [\"advisoryLockTimeoutMs\", \"advisory-lock-timeout\"],\n [\"lockTimeoutMs\", \"lock-timeout\"],\n [\"statementTimeoutMs\", \"statement-timeout\"],\n] as const;\n\nconst RESOLVE_EXTENSIONS = [\n \".ts\",\n \".mts\",\n \".js\",\n \".mjs\",\n \"/index.ts\",\n \"/index.js\",\n];\nconst RELATIVE_SPECIFIER = /^(\\.\\.?\\/|\\/|file:)/;\nconst KNOWN_EXTENSION = /\\.[cm]?[jt]sx?$|\\.json$/;\nlet hooksRegistered = false;\n\n/**\n * Node resolves `./src/schema` only with an extension, so the config and the\n * modules it imports get extension fallbacks. Bun resolves them natively and\n * has no registerHooks.\n */\nconst registerExtensionHooks = (): void => {\n // Bun has no registerHooks and resolves extensionless specifiers itself.\n const registerHooks = (\n nodeModule as { registerHooks?: typeof nodeModule.registerHooks }\n ).registerHooks;\n\n if (hooksRegistered || typeof registerHooks !== \"function\") {\n return;\n }\n\n hooksRegistered = true;\n registerHooks({\n resolve(specifier, context, nextResolve) {\n try {\n return nextResolve(specifier, context);\n } catch (error) {\n const code = (error as { code?: unknown } | null)?.code;\n\n if (\n (code !== \"ERR_MODULE_NOT_FOUND\" &&\n code !== \"ERR_UNSUPPORTED_DIR_IMPORT\") ||\n !RELATIVE_SPECIFIER.test(specifier) ||\n KNOWN_EXTENSION.test(specifier)\n ) {\n throw error;\n }\n\n for (const extension of RESOLVE_EXTENSIONS) {\n try {\n return nextResolve(`${specifier}${extension}`, context);\n } catch {\n // try the next candidate\n }\n }\n\n throw error;\n }\n },\n });\n};\n\nexport const loadProject = async (context: CliContext): Promise<Project> => {\n const { values } = context;\n const configPath = resolve(values.config ?? \"symmetria.config.ts\");\n const present = await access(configPath).then(\n () => true,\n (error: unknown) => {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"ENOENT\" &&\n !values.config\n ) {\n return false;\n }\n\n throw error;\n },\n );\n let config: MigrationConfig = {};\n\n if (present) {\n registerExtensionHooks();\n const module = await context.progress(\n \"Loading schema\",\n () => import(pathToFileURL(configPath).href),\n );\n\n if (!module.default || typeof module.default !== \"object\") {\n throw new Error(\n \"symmetria: config must default-export a migration configuration\",\n );\n }\n\n config = module.default;\n }\n\n const directory = values.dir\n ? resolve(values.dir)\n : resolve(\n present ? dirname(configPath) : process.cwd(),\n config.directory ?? \"migrations\",\n );\n const databaseUrl =\n values[\"database-url\"] ?? config.databaseUrl ?? process.env.DATABASE_URL;\n const timeouts = Object.fromEntries(\n TIMEOUT_FLAGS.flatMap(([key, flag]) => {\n const value =\n values[flag] === undefined ? config[key] : Number(values[flag]);\n\n if (value === undefined) {\n return [];\n }\n\n if (!Number.isSafeInteger(value) || value < 0 || value > 2147483647) {\n throw new Error(`symmetria: invalid --${flag}`);\n }\n\n return [[key, value]];\n }),\n );\n const verificationDatabaseUrl =\n values[\"verify-url\"] ?? config.verificationDatabaseUrl;\n // Prisma's history table is never part of an application schema, and adopt\n // must work while it still exists; declared tables are compared regardless.\n const ignoreTables = [\n ...new Set([\n \"_prisma_migrations\",\n ...(config.ignoreTables ?? []),\n ...(values[\"ignore-table\"] ?? []),\n ]),\n ];\n\n return {\n configPath,\n present,\n config,\n directory,\n databaseUrl,\n runnerOptions: {\n directory,\n ...(config.metadataSchema\n ? { metadataSchema: config.metadataSchema }\n : {}),\n ...(config.metadataTable ? { metadataTable: config.metadataTable } : {}),\n ...(verificationDatabaseUrl ? { verificationDatabaseUrl } : {}),\n ignoreTables,\n ...timeouts,\n ...(config.onEvent ? { onEvent: config.onEvent } : {}),\n },\n snapshot: () => {\n const source = config.schema;\n\n return source\n ? \"$snapshot\" in source\n ? source.$snapshot()\n : source\n : undefined;\n },\n };\n};\n\n/**\n * Opens a driver for the configured database, turns SIGINT/SIGTERM into a\n * cancellation signal with the conventional exit codes, and always closes it.\n */\nexport const withDatabase = async <Result>(\n project: Pick<Project, \"databaseUrl\">,\n operation: (driver: PostgresDriver, signal: AbortSignal) => Promise<Result>,\n): Promise<Result> => {\n if (!project.databaseUrl) {\n throw new Error(\n \"symmetria: no database: set databaseUrl in the config, DATABASE_URL or --database-url\",\n );\n }\n\n const driver = postgres(project.databaseUrl);\n\n try {\n return await withCancellation((signal) => operation(driver, signal));\n } finally {\n await driver.close();\n }\n};\n\nexport const withCancellation = async <Result>(\n operation: (signal: AbortSignal) => Promise<Result>,\n): Promise<Result> => {\n const cancellation = new AbortController();\n\n const interrupt = () => {\n process.exitCode = 130;\n cancellation.abort(new Error(\"symmetria: interrupted\"));\n };\n\n const terminate = () => {\n process.exitCode = 143;\n cancellation.abort(new Error(\"symmetria: terminated\"));\n };\n\n process.once(\"SIGINT\", interrupt);\n process.once(\"SIGTERM\", terminate);\n\n try {\n return await operation(cancellation.signal);\n } finally {\n process.removeListener(\"SIGINT\", interrupt);\n process.removeListener(\"SIGTERM\", terminate);\n }\n};\n","/**\n * Interactive schema browser: navigates tables, columns, relations, indexes and generated DDL.\n */\nimport stringWidth from \"string-width\";\nimport { emitKeypressEvents } from \"node:readline\";\nimport { stripVTControlCharacters } from \"node:util\";\nimport type { SchemaSnapshot, TableSnapshot } from \"symmetria\";\nimport { fitLine, numberedLines, theme, wrapLines } from \"../ui/style\";\nimport {\n highlightSQL,\n inspectEntries,\n inspectTableSQL,\n inspectTabs,\n matchesEntry,\n matchesTableName,\n matchingTables,\n type InspectTab,\n} from \"./schema-browser-data\";\n\ntype InspectOptions = { color: boolean; table?: string; tab?: InspectTab };\ntype Position = {\n table: TableSnapshot | undefined;\n tab: InspectTab;\n row: number;\n search: string;\n focus: \"tables\" | \"details\";\n};\n\n/** Runs inside the caller's alternate screen, both standalone and in the dashboard. */\nexport const inspectSchema = (\n snapshot: SchemaSnapshot,\n options: InspectOptions,\n): Promise<void> => {\n const initial = options.table\n ? snapshot.tables.find(\n (table) =>\n table.name === options.table || table.sqlName === options.table,\n )\n : snapshot.tables[0];\n\n if (options.table && !initial) {\n throw new Error(`symmetria: unknown table \"${options.table}\"`);\n }\n\n if (!process.stdin.isTTY || !process.stdout.isTTY) {\n throw new Error(\"symmetria: schema browser requires a terminal\");\n }\n\n return new Promise((resolve, reject) => {\n const { style, brand } = theme(options.color);\n const position: Position = {\n table: initial,\n tab: options.tab ?? \"Columns\",\n row: 0,\n search: \"\",\n focus: options.table ? \"details\" : \"tables\",\n };\n const history: Position[] = [];\n const sqlCache = new Map<TableSnapshot, string>();\n let searchStart: Position | undefined;\n let finished = false;\n let previousLines: string[] = [];\n let pageSize = 1;\n let tablePageSize = 1;\n let rowCount = 0;\n const wasRaw = process.stdin.isRaw;\n\n const tables = () => matchingTables(snapshot, position.search);\n\n const entries = () =>\n position.table\n ? inspectEntries(position.table, position.tab).filter(\n (entry) =>\n !position.search ||\n matchesTableName(position.table!, position.search) ||\n matchesEntry(entry, position.search),\n )\n : [];\n\n const align = (text: string, width: number) => {\n const clipped = fitLine(text, width);\n\n return clipped + \" \".repeat(Math.max(0, width - stringWidth(clipped)));\n };\n\n const frame = (\n title: string,\n body: string[],\n width: number,\n focused: boolean,\n ) => {\n const tone = focused ? \"violet\" : \"border\";\n const top = `─ ${title} `;\n\n return [\n style(\n `╭${fitLine(top, width - 2)}${\"─\".repeat(Math.max(0, width - 2 - stringWidth(top)))}╮`,\n tone,\n ),\n ...body.map(\n (line) =>\n `${style(\"│\", tone)} ${align(line, width - 4)} ${style(\"│\", tone)}`,\n ),\n style(`╰${\"─\".repeat(width - 2)}╯`, tone),\n ];\n };\n\n const rowStyle = (\n line: string,\n selected: boolean,\n focused: boolean,\n width: number,\n ) =>\n selected\n ? style(\n align(stripVTControlCharacters(line), width),\n focused ? \"selected\" : \"accent\",\n )\n : align(line, width);\n\n const normalize = () => {\n const visible = tables();\n\n if (!position.table || !visible.includes(position.table)) {\n position.table = visible[0];\n position.row = 0;\n }\n };\n\n const render = () => {\n normalize();\n const width = Math.max(\n 1,\n Math.min(process.stdout.columns || 88, 160) - 4,\n );\n const height = process.stdout.rows || 24;\n\n if (width < 28 || height < 12) {\n return [\n fitLine(\" symmetria / inspect\", width),\n fitLine(\" Enlarge terminal to browse\", width),\n fitLine(\" Esc to return\", width),\n ];\n }\n\n const visible = tables();\n const selectedTableIndex = Math.max(0, visible.indexOf(position.table!));\n const split = width >= 72;\n const sidebarWidth = split\n ? Math.min(28, Math.max(19, Math.floor(width * 0.23)))\n : width;\n const detailWidth = split ? width - sidebarWidth - 2 : width;\n const innerWidth = detailWidth - 4;\n const innerHeight = height - 7;\n tablePageSize = innerHeight;\n const tableOffset = Math.max(\n 0,\n Math.min(\n selectedTableIndex - innerHeight + 1,\n visible.length - innerHeight,\n ),\n );\n const sidebar = visible\n .slice(tableOffset, tableOffset + innerHeight)\n .map((table) => {\n const selected = table === position.table;\n\n return rowStyle(\n `${selected ? \"›\" : \" \"} ${table.name}`,\n selected,\n position.focus === \"tables\",\n sidebarWidth - 4,\n );\n });\n\n if (!sidebar.length) {\n sidebar.push(style(\"No matching tables\", \"muted\"));\n }\n\n while (sidebar.length < innerHeight) {\n sidebar.push(\"\");\n }\n\n const selectedEntries = entries();\n const labels =\n innerWidth >= 66\n ? inspectTabs\n : [\"Cols\", \"Rels\", \"Idx\", \"Checks\", \"SQL\"];\n const tabs = inspectTabs\n .map((tab, index) => {\n const count =\n position.table && tab !== \"SQL\"\n ? ` ${inspectEntries(position.table, tab).length}`\n : \"\";\n const label = `${labels[index]}${count}`;\n\n return style(\n position.tab === tab ? `[${label}]` : label,\n position.tab === tab ? \"pink\" : \"muted\",\n );\n })\n .join(\" \");\n const tabLine =\n stringWidth(tabs) <= innerWidth\n ? tabs\n : `${style(`‹ ${position.tab} ›`, \"pink\")} ${style(`${inspectTabs.indexOf(position.tab) + 1}/5 · ← → tabs`, \"muted\")}`;\n const detail: string[] = [\n tabLine,\n style(\"─\".repeat(innerWidth), \"border\"),\n ];\n let pageLabel = \"\";\n\n if (position.tab === \"SQL\" && position.table) {\n if (!sqlCache.has(position.table)) {\n sqlCache.set(\n position.table,\n highlightSQL(\n inspectTableSQL(snapshot, position.table),\n options.color,\n ),\n );\n }\n\n const sqlLines = numberedLines(\n sqlCache.get(position.table)!,\n innerWidth - 5,\n (label) => style(label, \"muted\"),\n );\n pageSize = innerHeight - detail.length;\n rowCount = sqlLines.length;\n position.row = Math.max(0, Math.min(position.row, rowCount - pageSize));\n detail.push(...sqlLines.slice(position.row, position.row + pageSize));\n pageLabel = `SQL ${position.row + 1}–${Math.min(rowCount, position.row + pageSize)}/${rowCount}`;\n } else {\n const nameWidth = Math.min(\n Math.max(\n 10,\n ...selectedEntries.map((entry) => stringWidth(entry.name)),\n ),\n Math.floor(innerWidth * 0.43),\n );\n const typeWidth = Math.min(\n Math.max(\n 7,\n ...selectedEntries.map((entry) => stringWidth(entry.kind)),\n ),\n Math.floor(innerWidth * 0.25),\n );\n\n const entryLine = (name: string, kind: string, flags: string) =>\n `${align(name, nameWidth)} ${align(kind, typeWidth)} ${flags}`;\n\n const detailBudget = Math.min(\n 4,\n Math.max(2, Math.floor(innerHeight / 4)),\n );\n pageSize = Math.max(\n 1,\n innerHeight - detail.length - 1 - detailBudget - 1,\n );\n rowCount = selectedEntries.length;\n position.row = Math.max(0, Math.min(position.row, rowCount - 1));\n const offset = Math.max(\n 0,\n Math.min(position.row - pageSize + 1, rowCount - pageSize),\n );\n detail.push(style(` ${entryLine(\"NAME\", \"TYPE\", \"FLAGS\")}`, \"muted\"));\n const rows = selectedEntries\n .slice(offset, offset + pageSize)\n .map((entry, index) => {\n const selected = position.row === offset + index;\n\n return rowStyle(\n `${selected ? \"›\" : \" \"} ${entryLine(style(entry.name, \"accent\"), style(entry.kind, \"violet\"), entry.badges.map((badge) => style(badge, \"pink\")).join(\" · \"))}`,\n selected,\n position.focus === \"details\",\n innerWidth,\n );\n });\n\n if (!rows.length) {\n rows.push(\n style(\n position.search\n ? \"No matches in this tab\"\n : `No ${position.tab.toLowerCase()}`,\n \"muted\",\n ),\n );\n }\n\n while (rows.length < pageSize) {\n rows.push(\"\");\n }\n\n detail.push(...rows, style(\"─\".repeat(innerWidth), \"border\"));\n const selected = selectedEntries[position.row];\n const description = selected\n ? wrapLines(style(selected.description, \"muted\"), innerWidth).slice(\n 0,\n detailBudget,\n )\n : [\n style(\n position.table\n ? \"← → switch tabs · / search\"\n : \"No tables to inspect\",\n \"muted\",\n ),\n ];\n detail.push(...description);\n pageLabel = rowCount\n ? `${position.tab} ${position.row + 1}/${rowCount}`\n : position.tab;\n }\n\n while (detail.length < innerHeight) {\n detail.push(\"\");\n }\n\n const sidebarPanel = frame(\n `Tables · ${visible.length}/${snapshot.tables.length}`,\n sidebar,\n sidebarWidth,\n position.focus === \"tables\",\n );\n const detailPanel = frame(\n position.table?.name ?? \"Schema\",\n detail.slice(0, innerHeight),\n detailWidth,\n position.focus === \"details\",\n );\n const panels = split\n ? sidebarPanel.map((line, index) => `${line} ${detailPanel[index]}`)\n : position.focus === \"tables\"\n ? sidebarPanel\n : detailPanel;\n const breadcrumb = `${history.length ? `${history.at(-1)!.table?.name} → ` : \"\"}${position.table?.name ?? \"schema\"}`;\n const search = searchStart\n ? `${style(\"/\", \"pink\")} ${position.search}${style(\"▏\", \"pink\")} ${style(\"enter apply · esc cancel\", \"muted\")}`\n : position.search\n ? `${style(\"/\", \"pink\")} ${position.search} ${style(\"esc clear\", \"muted\")}`\n : style(\"/ search tables and fields\", \"muted\");\n const hint =\n width >= 90\n ? \"↑↓ select · Tab pane · ←→ tabs · Enter follow · / search · ⌫ back · Esc/q exit\"\n : width >= 64\n ? \"↑↓ select · Tab pane · ←→ tabs · Enter follow · / find · Esc back\"\n : \"Tab pane · ←→ tabs · / find · Esc back\";\n\n return [\n ` ${fitLine(`${brand()} ${style(`/ inspect / ${breadcrumb}`, \"muted\")}`, width)}`,\n ` ${fitLine(search, width)}`,\n ...panels.map((line) => ` ${line}`),\n ` ${fitLine(`${style(position.focus === \"tables\" ? \"TABLES\" : \"DETAILS\", \"violet\")} ${style(pageLabel, \"muted\")}${history.length ? style(\" · ⌫ previous table\", \"pink\") : \"\"}`, width)}`,\n ` ${style(fitLine(hint, width), \"muted\")}`,\n ];\n };\n\n const draw = () => {\n try {\n const lines = render();\n const changes = lines.flatMap((line, index) =>\n line === previousLines[index]\n ? []\n : [`\\u001b[${index + 1};1H\\u001b[2K${line}`],\n );\n\n for (let index = lines.length; index < previousLines.length; index++) {\n changes.push(`\\u001b[${index + 1};1H\\u001b[2K`);\n }\n\n process.stdout.write(changes.join(\"\"));\n previousLines = lines;\n } catch (error) {\n finish(error);\n }\n };\n\n const resize = () => {\n previousLines = [];\n process.stdout.write(\"\\u001b[H\\u001b[2J\");\n draw();\n };\n\n const finish = (error?: unknown) => {\n if (finished) {\n return;\n }\n\n finished = true;\n process.stdin.off(\"keypress\", keypress);\n process.stdin.off(\"end\", end);\n process.stdout.off(\"resize\", resize);\n process.stdin.setRawMode(wasRaw);\n process.stdin.pause();\n process.stdout.write(\"\\u001b[?25h\");\n\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n };\n\n const end = () => finish();\n\n const keypress = (\n input: string,\n key: { name?: string; ctrl?: boolean; meta?: boolean },\n ) => {\n if (key.ctrl && [\"c\", \"d\"].includes(key.name ?? \"\")) {\n return finish();\n }\n\n if (searchStart) {\n if (key.name === \"escape\") {\n Object.assign(position, searchStart);\n searchStart = undefined;\n } else if (key.name === \"return\") {\n searchStart = undefined;\n } else if (key.name === \"backspace\") {\n position.search = [...position.search].slice(0, -1).join(\"\");\n position.row = 0;\n } else if (key.ctrl && key.name === \"u\") {\n position.search = \"\";\n position.row = 0;\n } else if (!key.ctrl && !key.meta && input && !/[\\p{C}]/u.test(input)) {\n position.search += input;\n position.row = 0;\n }\n\n draw();\n\n return;\n }\n\n if (input === \"/\") {\n searchStart = { ...position };\n draw();\n\n return;\n }\n\n // q closes the browser as it does the query inspector and the profiler.\n if (input === \"q\" && !key.ctrl && !key.meta) {\n return finish();\n }\n\n if (key.name === \"escape\") {\n if (position.search) {\n position.search = \"\";\n position.row = 0;\n draw();\n\n return;\n }\n\n return finish();\n }\n\n if (key.name === \"tab\") {\n position.focus = position.focus === \"tables\" ? \"details\" : \"tables\";\n } else if (key.name === \"backspace\") {\n const previous = history.pop();\n\n if (previous) {\n Object.assign(position, previous);\n } else {\n position.focus = \"tables\";\n }\n } else if (\n key.name === \"left\" ||\n key.name === \"right\" ||\n /^[1-5]$/.test(input)\n ) {\n const index = inspectTabs.indexOf(position.tab);\n position.tab =\n inspectTabs[\n /^[1-5]$/.test(input)\n ? Number(input) - 1\n : (index + (key.name === \"left\" ? -1 : 1) + inspectTabs.length) %\n inspectTabs.length\n ]!;\n position.row = 0;\n position.focus = \"details\";\n } else if (key.name === \"return\") {\n if (position.focus === \"tables\") {\n position.focus = \"details\";\n } else {\n const target = entries()[position.row]?.target;\n const table =\n target &&\n snapshot.tables.find(\n (table) =>\n table.name === target.table || table.sqlName === target.table,\n );\n\n if (table) {\n history.push({ ...position });\n Object.assign(position, {\n table,\n tab: \"Columns\",\n search: \"\",\n row: Math.max(\n 0,\n table.columns.findIndex(\n (column) =>\n column.name === target.column ||\n column.sqlName === target.column,\n ),\n ),\n });\n }\n }\n } else if (\n [\"up\", \"down\", \"pageup\", \"pagedown\", \"home\", \"end\"].includes(\n key.name ?? \"\",\n )\n ) {\n const visible = tables();\n const maximum =\n position.focus === \"tables\"\n ? visible.length - 1\n : position.tab === \"SQL\"\n ? rowCount - pageSize\n : rowCount - 1;\n const current =\n position.focus === \"tables\"\n ? visible.indexOf(position.table!)\n : position.row;\n const step = position.focus === \"tables\" ? tablePageSize : pageSize;\n const amount =\n key.name === \"up\"\n ? -1\n : key.name === \"down\"\n ? 1\n : key.name === \"pageup\"\n ? -step\n : step;\n const next = Math.max(\n 0,\n Math.min(\n maximum,\n key.name === \"home\"\n ? 0\n : key.name === \"end\"\n ? maximum\n : current + amount,\n ),\n );\n\n if (position.focus === \"tables\") {\n position.table = visible[next];\n position.row = 0;\n } else {\n position.row = next;\n }\n } else {\n return;\n }\n\n draw();\n };\n\n emitKeypressEvents(process.stdin);\n process.stdin.setRawMode(true);\n process.stdin.resume();\n process.stdin.on(\"keypress\", keypress);\n process.stdin.once(\"end\", end);\n process.stdout.on(\"resize\", resize);\n process.stdout.write(\"\\u001b[?25l\");\n resize();\n });\n};\n","/**\n * Interactive dashboard: header with chain, connectivity and schema state, plus a menu for generate,\n * migrate, inspect, status and rollback.\n */\nimport { relative } from \"node:path\";\nimport { postgres } from \"symmetria/driver\";\nimport { diffSchemas, loadMigrationState, migrator } from \"../../index\";\nimport { formatDashboard } from \"../ui/format\";\nimport { inspectSchema } from \"./schema-browser\";\nimport { formatError } from \"../ui/style\";\nimport { choose, view, withScreen } from \"../ui/terminal\";\nimport type { CliContext, Project } from \"../context\";\n\nconst ACTIONS = [\n [\n \"View schema changes\",\n \"diff\",\n \"Compare your schema with the latest local snapshot.\",\n ],\n [\n \"Generate migration\",\n \"generate\",\n \"Turn schema changes into a versioned SQL migration.\",\n ],\n [\"Apply migrations\", \"migrate\", \"Run pending migrations against PostgreSQL.\"],\n [\n \"Inspect schema\",\n \"inspect\",\n \"Explore tables, columns, relationships and constraints.\",\n ],\n [\n \"Migration history\",\n \"status\",\n \"See applied and pending migrations at a glance.\",\n ],\n [\n \"Rollback latest migration\",\n \"rollback\",\n \"Execute down.sql for the latest applied migration.\",\n ],\n [\"Exit\", \"\", \"Back to your terminal.\"],\n] as const;\n\nconst clear = () => process.stdout.write(\"\\u001b[H\\u001b[2J\");\n\n/** What the dashboard header shows: local chain, database connectivity and schema changes. */\nconst overview = async (context: CliContext, project: Project) => {\n const { migrations, snapshot: before } = await loadMigrationState(\n project.directory,\n );\n const snapshot = project.snapshot();\n const summary = {\n migrations: `${migrations.length} local · database not configured`,\n address: \"Offline · set DATABASE_URL to connect\",\n connection: \"offline\" as \"connected\" | \"offline\" | \"unavailable\",\n pending: 0,\n applied: 0,\n };\n\n if (project.databaseUrl) {\n const url = new URL(project.databaseUrl);\n summary.address = `PostgreSQL · ${url.hostname}:${url.port || \"5432\"}${url.pathname}`;\n const driver = postgres(project.databaseUrl);\n\n try {\n const statuses = await context.progress(\"Checking PostgreSQL\", () =>\n migrator({ driver, ...project.runnerOptions }).status(),\n );\n summary.applied = statuses.filter(\n (entry) => entry.status === \"applied\",\n ).length;\n summary.pending = statuses.filter(\n (entry) => entry.status === \"pending\",\n ).length;\n summary.connection = \"connected\";\n summary.migrations = `${summary.applied} applied · ${summary.pending} pending`;\n const incomplete = statuses.length - summary.applied - summary.pending;\n\n if (incomplete) {\n summary.migrations += ` · ${incomplete} incomplete (repair required)`;\n }\n } catch (error) {\n summary.connection = \"unavailable\";\n summary.migrations = `Unavailable: ${error instanceof Error ? error.message : String(error)}`;\n } finally {\n await driver.close();\n }\n }\n\n return {\n ...summary,\n snapshot,\n local: migrations.length,\n changes: snapshot\n ? diffSchemas(before, snapshot).up.filter(\n (statement) => !statement.startsWith(\"--\"),\n ).length\n : undefined,\n config: project.present\n ? relative(process.cwd(), project.configPath) || project.configPath\n : \"No config · symmetria init to get started\",\n };\n};\n\n/** `dashboard` (the bare `symmetria` command): a menu that runs the other commands in place. */\nexport const dashboard = async (\n context: CliContext,\n project: Project,\n): Promise<void> => {\n const { values, color } = context;\n\n if (!context.interactive) {\n throw new Error(\"symmetria: dashboard requires an interactive terminal\");\n }\n\n const forwarded = [\n ...(values.config ? [\"--config\", values.config] : []),\n ...(values.dir ? [\"--dir\", values.dir] : []),\n ...(values[\"database-url\"]\n ? [\"--database-url\", values[\"database-url\"]]\n : []),\n ...(values[\"no-color\"] ? [\"--no-color\"] : []),\n ...(values[\"no-animation\"] ? [\"--no-animation\"] : []),\n ];\n\n return withScreen(async () => {\n while (true) {\n const state = await overview(context, project);\n const selected = await choose(\n \"Choose an action\",\n ACTIONS.map(([label]) => label),\n {\n color,\n animation: !values[\"no-animation\"],\n header: (frame) => formatDashboard(state, color, frame),\n descriptions: ACTIONS.map(([, , description]) => description),\n },\n );\n const action = selected === undefined ? \"\" : ACTIONS[selected]![1];\n\n if (!action) {\n return;\n }\n\n clear();\n\n if (action === \"inspect\" && state.snapshot) {\n try {\n await inspectSchema(state.snapshot, { color });\n } catch (error) {\n await view(\n \"inspect\",\n formatError(\n error instanceof Error ? error.message : String(error),\n color,\n ),\n color,\n );\n }\n\n clear();\n continue;\n }\n\n const messages: string[] = [];\n\n try {\n await context.rerun([action, ...forwarded], (message) => {\n messages.push(message);\n });\n } catch (error) {\n messages.push(\n formatError(\n error instanceof Error ? error.message : String(error),\n color,\n ),\n );\n }\n\n await view(action, messages.join(\"\\n\"), color);\n clear();\n }\n });\n};\n","/**\n * Confirmation before a rollback: shows what down.sql removes and asks before\n * anything runs. Dropping or emptying whole tables needs the database name\n * typed out.\n */\nimport { parseMigrationSQL } from \"../../migrations/sql\";\nimport { lintMigrationSQL } from \"../../migrations/sql-lint\";\nimport type { Choose } from \"../ui/terminal\";\n\nexport type RollbackSummary = {\n readonly migrations: readonly string[];\n readonly statements: number;\n readonly destructive: readonly string[];\n readonly droppedTables: number;\n readonly emptiedTables: number;\n};\n\n/** The statement's leading keywords, read past comments. */\nconst opening = (sql: string): string =>\n (parseMigrationSQL(`${sql};`)[0]?.words ?? []).slice(0, 2).join(\" \");\n\nconst EMPTIES_TABLES = /^(?:TRUNCATE\\b|DROP (?:SCHEMA|OWNED)$)/;\n\nconst oneLine = (sql: string): string => {\n const text = sql.replace(/\\s+/g, \" \").trim();\n\n return text.length > 96 ? `${text.slice(0, 95)}…` : text;\n};\n\nexport const rollbackSummary = (\n steps: readonly {\n readonly id: string;\n readonly statements: readonly string[];\n }[],\n): RollbackSummary => {\n const destructive = steps.flatMap((step) =>\n lintMigrationSQL(\n step.statements.map((sql) => `${sql};`).join(\"\\n\"),\n step.id,\n )\n .filter((finding) => finding.level === \"destructive\")\n .map((finding) => step.statements[finding.statement - 1]!),\n );\n const unique = [...new Set(destructive)];\n\n return {\n migrations: steps.map((step) => step.id),\n statements: steps.reduce((sum, step) => sum + step.statements.length, 0),\n destructive: unique.map(oneLine),\n droppedTables: unique.filter((sql) => opening(sql) === \"DROP TABLE\").length,\n emptiedTables: unique.filter((sql) => EMPTIES_TABLES.test(opening(sql)))\n .length,\n };\n};\n\n/** The database a URL points at, for the question and the typed confirmation. */\nexport const databaseName = (url: string | undefined): string => {\n try {\n return (\n decodeURIComponent(new URL(url ?? \"\").pathname.slice(1)) || \"postgres\"\n );\n } catch {\n return \"database\";\n }\n};\n\nexport const rollbackPreview = (\n summary: RollbackSummary,\n database: string,\n): string =>\n [\n \"\",\n ` Rollback on \"${database}\": ${summary.migrations.join(\", \")}`,\n ` ${summary.statements} SQL statement${summary.statements === 1 ? \"\" : \"s\"} from down.sql`,\n ...(summary.destructive.length\n ? [\n \"\",\n ` Removes data or database objects (${summary.destructive.length}):`,\n ...summary.destructive.slice(0, 12).map((sql) => ` ${sql}`),\n ...(summary.destructive.length > 12\n ? [` … and ${summary.destructive.length - 12} more (see --plan)`]\n : []),\n ]\n : []),\n \"\",\n ].join(\"\\n\");\n\n/** True only after an explicit yes; closing the question or a wrong name cancels. */\nexport const confirmRollback = async (\n summary: RollbackSummary,\n database: string,\n prompts: {\n readonly write: (text: string) => void;\n readonly select: Choose;\n readonly ask: (question: string) => Promise<string>;\n },\n): Promise<boolean> => {\n prompts.write(`${rollbackPreview(summary, database)}\\n`);\n\n if (summary.droppedTables || summary.emptiedTables) {\n const answer = await prompts.ask(\n `${\n summary.emptiedTables\n ? \"This drops or empties whole tables\"\n : `This drops ${summary.droppedTables} table${summary.droppedTables === 1 ? \"\" : \"s\"}`\n }. Type the database name \"${database}\" to continue:`,\n );\n\n return answer === database;\n }\n\n const count = summary.migrations.length;\n\n return (\n (await prompts.select(\n `Roll back ${count} migration${count === 1 ? \"\" : \"s\"} on \"${database}\"?`,\n [\"Cancel\", \"Roll back\"],\n )) === 1\n );\n};\n","/**\n * Database-backed CLI commands: verify, drift, repair, adopt, status, migrate and rollback.\n * Each one opens a connection through the shared context and prints or emits JSON.\n */\nimport { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport {\n detectDrift,\n formatDriftFindings,\n loadMigrationState,\n migrator,\n parseMigrationSnapshot,\n snapshotHash,\n verifyMigrations,\n} from \"../../index\";\nimport { boundaryDifferences } from \"../../migrations/verify\";\nimport { formatExecution, formatStatus } from \"../ui/format\";\nimport { ask } from \"../ui/terminal\";\nimport {\n confirmRollback,\n databaseName,\n rollbackSummary,\n} from \"../screens/rollback-prompt\";\nimport {\n withCancellation,\n withDatabase,\n type CliContext,\n type Project,\n} from \"../context\";\n\n/** `verify`: replay the chain in disposable databases on the verification server. */\nexport const verify = async (\n context: CliContext,\n project: Project,\n): Promise<void> => {\n const url = project.runnerOptions.verificationDatabaseUrl;\n\n if (!url) {\n throw new Error(\n \"symmetria: verify requires --verify-url or verificationDatabaseUrl: an administrative PostgreSQL URL with CREATEDB permission, separate from the application database\",\n );\n }\n\n const result = await withCancellation((signal) =>\n verifyMigrations({\n ...project.runnerOptions,\n ...project.config.verify,\n url,\n signal,\n }),\n );\n context.emit({\n json: result,\n plain: () =>\n `Verified ${result.migrations.length} migrations: installation, upgrade, rollback and reapplication.`,\n });\n};\n\n/**\n * `drift`: compare the live catalog with the latest snapshot or the declared\n * schema. A database that is some migrations behind the local chain, after a\n * rollback or before a deploy, is not compared with the latest snapshot: every\n * pending change would read as drift. There are no older snapshots, so its own\n * boundary is checked by replaying the chain on the verification server, when\n * one is configured.\n */\nexport const drift = async (\n context: CliContext,\n project: Project,\n): Promise<void> =>\n withDatabase(project, async (driver, signal) => {\n const state = await loadMigrationState(project.directory);\n const { migrations, snapshot } = state;\n const expected =\n (migrations.length ? snapshot : undefined) ?? project.snapshot();\n\n if (!expected) {\n throw new Error(\n \"symmetria: drift needs a migration chain or a schema in the config\",\n );\n }\n\n const { metadataSchema, metadataTable } = project.config;\n const { ignoreTables, verificationDatabaseUrl } = project.runnerOptions;\n const history = migrations.length\n ? await migrator({ ...project.runnerOptions, driver, signal }).status()\n : [];\n const applied = history.findLastIndex(\n (entry) => entry.status === \"applied\",\n );\n\n // A database with no applied migration is compared with the latest\n // snapshot, as before `adopt`; so is one whose pending migrations leave\n // the schema as it is.\n if (\n applied >= 0 &&\n applied < migrations.length - 1 &&\n migrations[applied]!.manifest.after !== snapshotHash(snapshot)\n ) {\n const lastApplied = migrations[applied]!.id;\n const pending = migrations.slice(applied + 1).map(({ id }) => id);\n const differences = verificationDatabaseUrl\n ? await context.progress(\"Replaying the applied migrations\", () =>\n boundaryDifferences({\n ...project.runnerOptions,\n execute: driver.execute,\n state,\n target: applied,\n url: verificationDatabaseUrl,\n signal,\n }),\n )\n : undefined;\n const summary = `The database is ${pending.length} ${pending.length === 1 ? \"migration\" : \"migrations\"} behind the local chain (last applied: ${lastApplied}); drift is checked against the latest snapshot only.`;\n\n context.emit({\n json: {\n findings: [],\n behind: {\n migrations: pending.length,\n lastApplied,\n pending,\n verified: differences ? differences.length === 0 : null,\n ...(differences?.length ? { differences } : {}),\n },\n },\n indent: 2,\n plain: () =>\n [\n summary,\n ...(differences === undefined\n ? [\n `Run migrate, or verify the database against ${lastApplied} with --verify-url.`,\n ]\n : differences.length\n ? [\n `Replaying the chain up to ${lastApplied} on the verification server gives a different schema:`,\n ...differences.map((line) => ` ${line}`),\n ]\n : [\n `Replaying the chain up to ${lastApplied} on the verification server gives the same schema: no schema drift detected.`,\n ]),\n ].join(\"\\n\"),\n });\n\n // Being behind is not drift; a boundary that does not match is.\n if (context.values.strict && differences?.length) {\n process.exitCode = 1;\n }\n\n return;\n }\n\n const findings = await context.progress(\"Inspecting the database\", () =>\n detectDrift({\n execute: driver.execute,\n snapshot: expected,\n ...(metadataSchema ? { metadataSchema } : {}),\n ...(metadataTable ? { metadataTable } : {}),\n ...(ignoreTables ? { ignoreTables } : {}),\n }),\n );\n context.emit({\n json: { findings },\n indent: 2,\n plain: () => formatDriftFindings(findings),\n });\n\n if (context.values.strict && findings.length) {\n process.exitCode = 1;\n }\n });\n\ntype Runner = ReturnType<typeof migrator>;\n\n/** `migrate`, `rollback`, `status`, `adopt` and `repair` share one migrator bound to the database. */\nconst withRunner = (\n project: Project,\n operation: (runner: Runner) => Promise<void>,\n): Promise<void> =>\n withDatabase(project, (driver, signal) =>\n operation(migrator({ ...project.runnerOptions, driver, signal })),\n );\n\nconst plan = async (\n context: CliContext,\n runner: Runner,\n direction: \"up\" | \"down\",\n): Promise<void> => {\n const { values } = context;\n const steps = await runner.plan({\n ...(values.to ? { to: values.to } : {}),\n ...(values.steps ? { steps: Number(values.steps) } : {}),\n direction,\n });\n context.emit({\n json: { steps },\n indent: 2,\n plain: () =>\n steps\n .map(\n (step) =>\n `-- group ${step.group}: ${step.transaction} · ${step.id}\\n${step.statements.map((sql) => `${sql};`).join(\"\\n\\n\")}`,\n )\n .join(\"\\n\\n\"),\n });\n};\n\nexport const repair = (\n context: CliContext,\n project: Project,\n id: string,\n): Promise<void> =>\n withRunner(project, async (runner) => {\n const action = context.values.action as \"retry\" | \"complete\";\n // The snapshot file of the boundary, such as meta/snapshot.json as it was\n // before the migration was generated; the runner checks its hash.\n const file = context.values.snapshot;\n const snapshot =\n file === undefined\n ? undefined\n : parseMigrationSnapshot(\n JSON.parse(await readFile(resolve(file), \"utf8\")),\n );\n await runner.repair({ id, action, ...(snapshot ? { snapshot } : {}) });\n context.emit({\n json: { repaired: id, action },\n plain: () => `Repaired ${id}: ${action}`,\n });\n });\n\nexport const adopt = (context: CliContext, project: Project): Promise<void> =>\n withRunner(project, async (runner) => {\n const { values } = context;\n const adopted = await context.progress(\"Recording the local chain\", () =>\n runner.adopt(values.to ? { to: values.to } : {}),\n );\n context.emit({\n json: { adopted },\n plain: () =>\n adopted.length\n ? adopted.map((id) => `Adopted ${id}`).join(\"\\n\")\n : \"Nothing to adopt.\",\n });\n });\n\nexport const status = (context: CliContext, project: Project): Promise<void> =>\n withRunner(project, async (runner) => {\n const statuses = await context.progress(\"Reading migration history\", () =>\n runner.status(),\n );\n\n if (statuses.some((entry) => entry.status === \"incomplete\")) {\n process.exitCode = 1;\n }\n\n context.emit({\n json: { migrations: statuses },\n pretty: () => formatStatus(statuses, context.color),\n plain: () =>\n statuses.length\n ? statuses\n .map(\n (entry) =>\n `${entry.status.padEnd(7)} ${entry.id}${entry.status === \"incomplete\" ? ` · ${entry.direction} · ${entry.statement} confirmed statements · repair required` : \"\"}`,\n )\n .join(\"\\n\")\n : \"No migrations.\",\n });\n });\n\nexport const migrate = (context: CliContext, project: Project): Promise<void> =>\n withRunner(project, async (runner) => {\n const { values } = context;\n\n if (values.plan) {\n return plan(context, runner, \"up\");\n }\n\n const started = performance.now();\n const applied = await context.progress(\"Applying migrations\", () =>\n runner.migrate(values.to ? { to: values.to } : {}),\n );\n const durationMs = Math.round(performance.now() - started);\n // `--to` an applied migration does nothing; say where the database stands.\n const current =\n !applied.length && values.to\n ? (await runner.status())\n .filter((entry) => entry.status === \"applied\")\n .at(-1)?.id\n : undefined;\n const idle =\n current === undefined\n ? \"Database is up to date.\"\n : current === values.to\n ? `Database is already at ${values.to}.`\n : `${values.to} is already applied; the database is further along, at ${current}. Use rollback to go back.`;\n context.emit({\n json: { applied, durationMs },\n pretty: () =>\n current === undefined\n ? formatExecution(applied, \"Applied\", durationMs, context.color)\n : `\\n ${context.style(\"✓\", \"success\")} ${idle}\\n`,\n plain: () =>\n applied.length ? applied.map((id) => `Applied ${id}`).join(\"\\n\") : idle,\n });\n });\n\nexport const rollback = (\n context: CliContext,\n project: Project,\n): Promise<void> =>\n withRunner(project, async (runner) => {\n const { values } = context;\n\n if (values.plan) {\n return plan(context, runner, \"down\");\n }\n\n const steps = values.steps === undefined ? 1 : Number(values.steps);\n let expected: string[] | undefined;\n\n // down.sql usually removes columns or tables, so it never runs unasked.\n if (\n !values.yes &&\n (await runner.status()).some((entry) => entry.status !== \"pending\")\n ) {\n if (!context.interactive) {\n throw new Error(\n \"symmetria: rollback runs down.sql, which can remove data; review it with --plan and pass --yes to run it\",\n );\n }\n\n const planned = await runner.plan({ steps, direction: \"down\" });\n\n // What was shown is what runs: another process may roll back in between.\n expected = [...new Set(planned.map((step) => step.id))];\n\n const confirmed = await confirmRollback(\n rollbackSummary(planned),\n databaseName(project.databaseUrl),\n {\n write: (text) => process.stdout.write(text),\n select: context.select,\n ask: (question) => ask(question, context.color),\n },\n );\n\n if (!confirmed) {\n context.emit({\n json: { reverted: [], cancelled: true },\n pretty: () =>\n `\\n ${context.style(\"○\", \"muted\")} Rollback cancelled; nothing was changed.\\n`,\n plain: () => \"Rollback cancelled; nothing was changed.\",\n });\n\n return;\n }\n }\n\n const started = performance.now();\n const reverted = await context.progress(\"Rolling back migrations\", () =>\n runner.rollback({\n ...(values.steps === undefined ? {} : { steps }),\n ...(expected ? { expected } : {}),\n }),\n );\n const durationMs = Math.round(performance.now() - started);\n context.emit({\n json: { reverted, durationMs },\n pretty: () =>\n formatExecution(reverted, \"Reverted\", durationMs, context.color),\n plain: () =>\n reverted.length\n ? reverted.map((id) => `Reverted ${id}`).join(\"\\n\")\n : \"No applied migrations.\",\n });\n });\n","/**\n * Filesystem CLI commands: recover a crashed generation, squash the chain and\n * discard the latest migration.\n */\nimport { postgres } from \"symmetria/driver\";\nimport {\n discardMigration,\n loadMigrationState,\n migrator,\n recoverMigrationFiles,\n squashMigrations,\n} from \"../../index\";\nimport type { CliContext, Project } from \"../context\";\n\n/** `recover`: finish or roll back a publication left behind by a crashed generator. */\nexport const recover = async (\n context: CliContext,\n project: Project,\n): Promise<void> => {\n const recovered = await recoverMigrationFiles(project.directory);\n context.emit({\n json: { recovered },\n plain: () =>\n recovered\n ? \"Migration files recovered.\"\n : \"Nothing to recover: no generation lock was left behind.\",\n });\n};\n\n/** `squash <name>`: replace the local chain with one baseline migration. */\nexport const squash = async (\n context: CliContext,\n project: Project,\n name: string,\n): Promise<void> => {\n const squashed = await context.progress(\"Squashing migrations\", () =>\n squashMigrations({\n directory: project.directory,\n name,\n ...(context.values[\"allow-custom-sql\"] ? { allowCustomSQL: true } : {}),\n }),\n );\n context.emit({\n json: squashed ? { id: squashed.id } : { id: null },\n plain: () =>\n squashed\n ? `Squashed into ${squashed.id}. Run \"symmetria adopt\" on databases that applied the old chain.`\n : \"Nothing to squash.\",\n });\n};\n\n/**\n * `discard [id]`: take back the latest migration while no database has\n * applied it. The configured database is asked first; without one, `--force`\n * says that none has.\n */\nexport const discard = async (\n context: CliContext,\n project: Project,\n id: string | undefined,\n): Promise<void> => {\n const { values } = context;\n const { migrations } = await loadMigrationState(project.directory).catch(\n () => ({ migrations: [] }),\n );\n const latest = migrations.at(-1)?.id;\n\n if (latest !== undefined) {\n if (project.databaseUrl) {\n const driver = postgres(project.databaseUrl);\n\n try {\n const entry = (\n await migrator({ driver, ...project.runnerOptions }).status()\n ).find((status) => status.id === latest);\n\n if (entry && entry.status !== \"pending\") {\n throw new Error(\n `symmetria: \"${latest}\" is ${entry.status} in the configured database; roll it back first (symmetria rollback), then discard it`,\n );\n }\n } finally {\n await driver.close();\n }\n } else if (!values.force) {\n throw new Error(\n `symmetria: discard asks the database whether \"${latest}\" was applied; set databaseUrl in the config, DATABASE_URL or --database-url, or pass --force when no database has applied it`,\n );\n }\n }\n\n const discarded = await discardMigration({\n directory: project.directory,\n ...(id ? { id } : {}),\n ...(values.force ? { allowEdited: true } : {}),\n });\n const from =\n discarded.source === \"git\" ? \" (the earlier snapshot came from Git)\" : \"\";\n context.emit({\n json: discarded,\n plain: () =>\n discarded.id\n ? `Discarded ${discarded.id}; the snapshot is the schema before it${from}.`\n : `The snapshot matches the journal again${from}.`,\n });\n};\n","import { mkdir, writeFile } from \"node:fs/promises\";\nimport { basename, dirname, extname, resolve } from \"node:path\";\nimport { renderMermaid, schemaGraph } from \"../../graph/mermaid\";\nimport { loadMigrationState } from \"../../migrations/files\";\nimport type { CliContext, Project } from \"../context\";\nimport { formatCreated } from \"../ui/format\";\n\n/**\n * `graph [file]`: a Mermaid entity-relationship diagram of the declared schema,\n * or of the latest migration snapshot when the config declares no schema.\n * Printed to stdout, or written to a file (`.md` files get a ```mermaid fence).\n */\nexport const graph = async (\n context: CliContext,\n project: Project,\n name: string | undefined,\n): Promise<void> => {\n const { values, color } = context;\n const declared = project.snapshot();\n const snapshot =\n declared ??\n (await loadMigrationState(project.directory).then(\n ({ migrations, snapshot }) => (migrations.length ? snapshot : undefined),\n ));\n\n if (!snapshot) {\n throw new Error(\n \"symmetria: graph needs a schema in the config or a migration chain\",\n );\n }\n\n const model = schemaGraph(snapshot);\n const summary = `${model.tables.length} ${model.tables.length === 1 ? \"table\" : \"tables\"}, ${model.edges.length} ${model.edges.length === 1 ? \"relation\" : \"relations\"}`;\n\n if (!name) {\n context.emit({\n json: model,\n indent: 2,\n plain: () =>\n renderMermaid(model, { compact: !!values.compact }).trimEnd(),\n });\n\n return;\n }\n\n const path = resolve(name);\n const diagram = renderMermaid(model, {\n fenced: extname(path).toLowerCase() === \".md\",\n compact: !!values.compact,\n });\n await mkdir(dirname(path), { recursive: true });\n\n try {\n await writeFile(path, diagram, { flag: values.force ? \"w\" : \"wx\" });\n } catch (error) {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"EEXIST\"\n ) {\n throw new Error(`symmetria: ${path} exists; use --force to overwrite it`);\n }\n\n throw error;\n }\n\n context.emit({\n json: { path, tables: model.tables.length, relations: model.edges.length },\n indent: 2,\n pretty: () =>\n `${formatCreated(dirname(path), [basename(path)], color)} ${context.style(summary, \"muted\")}`,\n plain: () => `Created\\n ${path}\\n ${summary}`,\n });\n};\n","/**\n * `symmetria-kit init`: writes the starter schema, migrations directory and config files for a new project.\n */\nimport { lstat, mkdir, open, readdir, rm } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\n\nconst files: Readonly<Record<string, string>> = {\n \"src/database/tables/users.ts\": `import { table, uuid, text } from \"symmetria\";\\n\\nexport const users = table({\\n id: uuid.v4.brand(\"UserId\"),\\n email: text.unique,\\n name: text,\\n});\\n`,\n \"src/database/schema.ts\": `import { schema } from \"symmetria\";\\nimport { users } from \"./tables/users.ts\";\\n\\nexport const appSchema = schema({ users });\\n`,\n \"src/database/index.ts\": `import { createDatabase } from \"symmetria\";\\nimport { postgres } from \"symmetria/driver\";\\nimport { appSchema } from \"./schema.ts\";\\n\\nconst url = process.env.DATABASE_URL;\\n\\nif (!url) {\\n throw new Error(\"Set DATABASE_URL before connecting\");\\n}\\n\\nexport const db = createDatabase({\\n schema: appSchema,\\n driver: postgres({ url }),\\n});\\n`,\n \"symmetria.config.ts\": `import { defineMigrationConfig } from \"symmetria-kit\";\\nimport { appSchema } from \"./src/database/schema\";\\n\\nexport default defineMigrationConfig({\\n schema: appSchema,\\n directory: \"./migrations\",\\n databaseUrl: process.env.DATABASE_URL,\\n});\\n`,\n \".env.example\":\n \"DATABASE_URL=postgres://postgres:postgres@localhost:5432/app\\n\",\n};\n\nexport const initializeProject = async (\n directory: string,\n): Promise<string[]> => {\n // A configured project already owns its schema layout. Do not add a second one.\n for (const name of [\"symmetria.config.ts\", \"migrations.config.ts\"]) {\n const existing = await lstat(resolve(directory, name)).catch(\n (error: unknown) => {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n ) {\n return undefined;\n }\n\n throw error;\n },\n );\n\n if (existing) {\n return [];\n }\n }\n\n const migrations = await readdir(resolve(directory, \"migrations\"), {\n withFileTypes: true,\n }).catch((error: unknown) => {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n ) {\n return [];\n }\n\n throw error;\n });\n\n if (\n migrations.some(\n (entry) => entry.isDirectory() && /^\\d{6}_/.test(entry.name),\n )\n ) {\n return [];\n }\n\n const created: string[] = [];\n\n try {\n for (const [name, contents] of Object.entries(files)) {\n const path = resolve(directory, name);\n await mkdir(dirname(path), { recursive: true });\n const file = await open(path, \"wx\").catch((error: unknown) => {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"EEXIST\"\n ) {\n return undefined;\n }\n\n throw error;\n });\n\n if (!file) {\n continue;\n }\n\n created.push(name);\n\n try {\n await file.writeFile(contents);\n } finally {\n await file.close();\n }\n }\n\n return created;\n } catch (error) {\n await Promise.all(created.map((name) => rm(resolve(directory, name))));\n throw new Error(\n \"symmetria: init could not create the project files (existing files are preserved)\",\n { cause: error },\n );\n }\n};\n","import { relative, resolve } from \"node:path\";\nimport { formatCreated } from \"../ui/format\";\nimport { initializeProject } from \"../scaffold\";\nimport type { CliContext } from \"../context\";\n\nconst quoteArgument = (value: string) =>\n /^[\\w./-]+$/.test(value) ? value : `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n\n/** `init [directory]`: scaffold schema modules, a connection and migration config. */\nexport const init = async (\n context: CliContext,\n name: string | undefined,\n): Promise<void> => {\n const { style, color } = context;\n const directory = resolve(name ?? \".\");\n const files = await context.progress(\"Creating your project\", () =>\n initializeProject(directory),\n );\n\n if (!files.length) {\n context.emit({\n json: { directory, files },\n plain: () => \"Existing project files preserved; nothing to create.\",\n });\n\n return;\n }\n\n const invocation = \"bunx --package symmetria-kit symmetria\";\n const changeDirectory =\n directory === process.cwd()\n ? \"\"\n : ` cd ${quoteArgument(relative(process.cwd(), directory))}\\n`;\n const next = `${style(\"Next\", \"violet\")}\\n${changeDirectory} Set DATABASE_URL (see .env.example)\\n ${style(`${invocation} generate initial`, \"accent\")}\\n ${style(`${invocation} migrate`, \"accent\")}`;\n context.emit({\n json: { directory, files },\n pretty: () => `${formatCreated(directory, files, color)}\\n${next}`,\n plain: () =>\n `Created\\n${files.map((file) => ` ${file}`).join(\"\\n\")}\\n\\n${next}`,\n });\n};\n","/**\n * Live profiler screen: polls a running profiler endpoint and renders request and query timings.\n */\nimport { emitKeypressEvents } from \"node:readline\";\nimport type { ProfiledRequest, ProfiledQuery } from \"symmetria\";\nimport { fitLine, terminalWidth, theme, wrapLines } from \"../ui/style\";\nimport { withScreen } from \"../ui/terminal\";\nimport {\n explainLines,\n terminalText,\n wrapExplainLines,\n} from \"./query-inspector\";\n\n/** Why the profiler endpoint refused a request, with the fix for a wrong token. */\nexport const profilerHttpError = (status: number): string =>\n status === 403\n ? \"symmetria: the profiler rejected the token; pass --profile-token or set SYMMETRIA_PROFILE_TOKEN to the value used by profiler.serve()\"\n : `symmetria: profiler returned HTTP ${status}`;\n\nconst milliseconds = (value: number) => `${value.toFixed(3)} ms`;\n\n/**\n * The lines of one request's view: its timings, the error that ended it and\n * its queries, with the selected one marked. A request can fail before it runs\n * a query; then the error stands where the list would be.\n */\nexport const requestLines = (\n request: ProfiledRequest,\n selectedQuery: number,\n view: {\n width: number;\n height: number;\n style: ReturnType<typeof theme>[\"style\"];\n },\n): string[] => {\n const { width, height, style } = view;\n // Narrow terminals drop columns rather than cutting the timings off.\n const compact = width < 72;\n const lines = [\n style(\n `${request.label} · build ${milliseconds(request.buildMs)} · total ${milliseconds(request.durationMs)}`,\n \"pink\",\n ),\n ];\n\n if (request.error) {\n // Half the screen at most, so the queries that led to it stay visible.\n const message = wrapLines(\n style(`Error: ${terminalText(request.error)}`, \"danger\"),\n width,\n );\n const limit = request.queries.length\n ? Math.max(1, Math.floor(height / 2) - 1)\n : Math.max(1, height - 2);\n\n lines.push(\n ...message.slice(0, limit),\n ...(message.length > limit ? [style(\"…\", \"danger\")] : []),\n );\n }\n\n if (!request.queries.length) {\n lines.push(\n style(\n request.error\n ? \"The request ran no queries before it failed.\"\n : \"The request ran no queries.\",\n \"muted\",\n ),\n );\n\n return lines;\n }\n\n lines.push(\n style(\n compact\n ? `${\"Query\".padEnd(18)}${\"Database\".padStart(10)} ${\"Rows\".padStart(6)}`\n : \"Query Compile Database Decode Rows\",\n \"muted\",\n ),\n );\n const rows = Math.max(1, height - lines.length);\n const start = Math.max(0, selectedQuery - rows + 1);\n\n for (const [position, entry] of request.queries\n .slice(start, start + rows)\n .entries()) {\n const marker = start + position === selectedQuery ? \"›\" : \" \";\n lines.push(\n style(\n compact\n ? `${marker} ${entry.kind.padEnd(7)} #${String(entry.id).padEnd(6)} ${entry.databaseMs.toFixed(3).padStart(10)} ${String(entry.rows).padStart(6)}${entry.error ? \" ERROR\" : \"\"}`\n : `${marker} ${entry.kind.padEnd(9)} #${String(entry.id).padEnd(10)} ${entry.compileMs.toFixed(3).padStart(9)} ${entry.databaseMs.toFixed(3).padStart(14)} ${entry.decodeMs.toFixed(3).padStart(12)} ${String(entry.rows).padStart(7)}${entry.error ? \" ERROR\" : \"\"}`,\n start + position === selectedQuery ? \"selected\" : \"text\",\n ),\n );\n }\n\n return lines;\n};\n\nexport const profileScreen = async (\n address: string,\n token: string,\n color: boolean,\n): Promise<void> =>\n withScreen(\n () =>\n new Promise<void>((resolve, reject) => {\n const { style, brand } = theme(color);\n let requests: ProfiledRequest[] = [];\n let selectedRequest = 0;\n let selectedQuery = 0;\n let mode: \"requests\" | \"queries\" | \"sql\" | \"plan\" = \"requests\";\n let offset = 0;\n let error = \"\";\n // The plan tree, as the query inspector shows it.\n let plan: string[] = [];\n let closed = false;\n let pending = false;\n let activeRequest: ProfiledRequest | undefined;\n const wasRaw = process.stdin.isRaw;\n\n const query = (): ProfiledQuery | undefined =>\n activeRequest?.queries[selectedQuery];\n\n const draw = () => {\n const height = Math.max(1, (process.stdout.rows || 24) - 7);\n const selected = query();\n const lines: string[] = [];\n\n // Narrow terminals shorten labels and drop columns rather than\n // cutting the timings off.\n const width = terminalWidth();\n const labelWidth = Math.max(12, Math.min(42, width - 35));\n\n if (mode === \"requests\") {\n lines.push(\n style(\n `${\"Request\".padEnd(labelWidth + 3)}SQL Build Total`,\n \"muted\",\n ),\n );\n const start = Math.max(0, selectedRequest - height + 2);\n\n for (const [position, request] of requests\n .slice(start, start + height - 1)\n .entries()) {\n const duplicates =\n request.queries.length -\n new Set(request.queries.map((entry) => entry.sql)).size;\n lines.push(\n style(\n `${start + position === selectedRequest ? \"›\" : \" \"} ${fitLine(request.label, labelWidth).padEnd(labelWidth)} ${String(request.queries.length).padStart(3)} ${request.buildMs.toFixed(2).padStart(7)} ${request.durationMs.toFixed(2).padStart(7)}${duplicates ? ` ↻ ${duplicates}` : \"\"}${request.error ? \" ERROR\" : \"\"}`,\n start + position === selectedRequest ? \"selected\" : \"text\",\n ),\n );\n }\n\n if (!requests.length) {\n lines.push(\n \"Waiting for queries… Send a request to your application.\",\n );\n }\n } else if (mode === \"queries\") {\n lines.push(\n ...requestLines(activeRequest!, selectedQuery, {\n width,\n height,\n style,\n }),\n );\n } else {\n const wrapped =\n mode === \"plan\"\n ? wrapExplainLines(plan, terminalWidth())\n : wrapLines(\n `${selected!.sql}\\n\\nParameters\\n${JSON.stringify(selected!.parameters, null, 2)}${selected!.error ? `\\n\\n${selected!.error}` : \"\"}`,\n );\n offset = Math.min(offset, Math.max(0, wrapped.length - height));\n lines.push(...wrapped.slice(offset, offset + height));\n }\n\n process.stdout.write(\n `\\u001b[H\\u001b[2J ${fitLine(`${brand()} ${style(\"/ live profiler\", \"muted\")}`)}\\n ${style(fitLine(error || address), error ? \"danger\" : \"muted\")}\\n\\n${lines.map((line) => ` ${fitLine(line)}`).join(\"\\n\")}\\u001b[${Math.max(1, (process.stdout.rows || 24) - 1)};1H ${style(fitLine(\"↑ ↓ navigate · enter open · esc back · e explain · a analyze · q quit\"), \"muted\")}`,\n );\n };\n\n const refresh = async () => {\n if (pending || closed) {\n return;\n }\n\n pending = true;\n\n try {\n const response = await fetch(new URL(\"/requests\", address), {\n headers: { \"x-symmetria-token\": token },\n signal: AbortSignal.timeout(3000),\n });\n\n if (!response.ok) {\n throw new Error(profilerHttpError(response.status));\n }\n\n const updated = (await response.json()) as ProfiledRequest[];\n\n if (!Array.isArray(updated)) {\n throw new Error(\"Invalid profiler response\");\n }\n\n const selectedId = requests[selectedRequest]?.id;\n requests = updated.toSorted((left, right) => right.id - left.id);\n selectedRequest = Math.max(\n 0,\n requests.findIndex((entry) => entry.id === selectedId),\n );\n error = \"\";\n } catch (cause) {\n error = cause instanceof Error ? cause.message : String(cause);\n } finally {\n pending = false;\n\n if (!closed) {\n draw();\n } else {\n resolve();\n }\n }\n };\n\n const explain = async (analyze: boolean) => {\n const selected = query();\n\n if (!selected || pending) {\n return;\n }\n\n pending = true;\n error = analyze\n ? \"Running EXPLAIN ANALYZE…\"\n : \"Estimating query plan…\";\n draw();\n\n try {\n const response = await fetch(\n new URL(`/explain?id=${selected.id}&analyze=${analyze}`, address),\n {\n method: \"POST\",\n headers: { \"x-symmetria-token\": token },\n signal: AbortSignal.timeout(30000),\n },\n );\n const result = await response.json();\n\n if (!response.ok) {\n throw new Error(\n result && typeof result === \"object\" && \"error\" in result\n ? String(result.error)\n : `HTTP ${response.status}`,\n );\n }\n\n plan = Array.isArray(result) ? explainLines(result) : [];\n\n if (!plan.length) {\n plan = JSON.stringify(result, null, 2).split(\"\\n\");\n }\n\n mode = \"plan\";\n offset = 0;\n error = \"\";\n } catch (cause) {\n error = cause instanceof Error ? cause.message : String(cause);\n } finally {\n pending = false;\n\n if (!closed) {\n draw();\n } else {\n resolve();\n }\n }\n };\n\n const finish = () => {\n if (closed) {\n return;\n }\n\n closed = true;\n clearInterval(timer);\n process.stdin.off(\"keypress\", keypress);\n process.stdin.off(\"end\", finish);\n process.stdout.off(\"resize\", draw);\n process.stdin.setRawMode(wasRaw);\n process.stdin.pause();\n\n if (!pending) {\n resolve();\n }\n };\n\n const keypress = (\n input: string,\n key: { name?: string; ctrl?: boolean },\n ) => {\n if (input === \"q\" || (key.ctrl && key.name === \"c\")) {\n finish();\n\n return;\n }\n\n if (key.name === \"escape\" || key.name === \"left\") {\n if (mode === \"requests\") {\n finish();\n\n return;\n }\n\n mode = mode === \"queries\" ? \"requests\" : \"queries\";\n offset = 0;\n } else if (key.name === \"return\") {\n if (mode === \"requests\" && requests[selectedRequest]) {\n activeRequest = requests[selectedRequest];\n selectedQuery = 0;\n mode = \"queries\";\n } else if (mode === \"queries\" && query()) {\n mode = \"sql\";\n offset = 0;\n }\n } else if (input === \"e\" || input === \"a\") {\n if (mode !== \"requests\") {\n void explain(input === \"a\");\n }\n } else if (\n [\"up\", \"down\", \"pageup\", \"pagedown\"].includes(key.name ?? \"\")\n ) {\n const direction =\n key.name === \"up\" || key.name === \"pageup\" ? -1 : 1;\n const step = key.name?.startsWith(\"page\") ? 10 : 1;\n\n if (mode === \"requests\") {\n selectedRequest = Math.max(\n 0,\n Math.min(\n requests.length - 1,\n selectedRequest + direction * step,\n ),\n );\n } else if (mode === \"queries\") {\n selectedQuery = Math.max(\n 0,\n Math.min(\n activeRequest!.queries.length - 1,\n selectedQuery + direction * step,\n ),\n );\n } else {\n offset = Math.max(0, offset + direction * step);\n }\n }\n\n draw();\n };\n\n emitKeypressEvents(process.stdin);\n process.stdin.setRawMode(true);\n process.stdin.resume();\n process.stdin.on(\"keypress\", keypress);\n process.stdin.once(\"end\", finish);\n process.stdout.on(\"resize\", draw);\n process.stdout.write(\"\\u001b[?25l\");\n const timer = setInterval(() => {\n void refresh();\n }, 500);\n draw();\n void refresh().catch(reject);\n }),\n );\n","import { profileScreen, profilerHttpError } from \"../screens/profiler\";\nimport type { CliContext } from \"../context\";\n\n/** `profile`: the live profiler screen, or its JSON feed when not interactive. */\nexport const profile = async (context: CliContext): Promise<void> => {\n const { values, interactive, color, output } = context;\n const address = values[\"profile-url\"] ?? \"http://127.0.0.1:7331\";\n const token = values[\"profile-token\"] ?? process.env.SYMMETRIA_PROFILE_TOKEN;\n\n if (!token) {\n throw new Error(\n \"symmetria: profile requires --profile-token or SYMMETRIA_PROFILE_TOKEN, the token configured for or returned by profiler.serve()\",\n );\n }\n\n if (interactive) {\n return profileScreen(address, token, color);\n }\n\n const response = await fetch(new URL(\"/requests\", address), {\n headers: { \"x-symmetria-token\": token },\n });\n\n if (!response.ok) {\n throw new Error(profilerHttpError(response.status));\n }\n\n output(JSON.stringify({ requests: await response.json() }, null, 2));\n};\n","import { mkdir, writeFile } from \"node:fs/promises\";\nimport { basename, dirname, resolve } from \"node:path\";\nimport { pullSchema } from \"../../introspection\";\nimport { loadProject, withDatabase, type CliContext } from \"../context\";\nimport { formatCreated, formatPullWarnings } from \"../ui/format\";\n\n/**\n * `pull [file]`: introspect the configured database and write a schema module.\n * The connection comes from --database-url, the config (when it loads) or DATABASE_URL.\n */\nexport const pull = async (\n context: CliContext,\n name: string | undefined,\n): Promise<void> => {\n const { values, color } = context;\n const path = resolve(name ?? \"schema.ts\");\n const explicit = values[\"database-url\"] ?? process.env.DATABASE_URL;\n const project = await loadProject(context).catch((error: unknown) => {\n // A config that imports the schema module being generated cannot load yet.\n if (!explicit) {\n throw error;\n }\n\n return undefined;\n });\n const databaseUrl =\n values[\"database-url\"] ?? project?.databaseUrl ?? explicit;\n const { metadataSchema, metadataTable } = project?.config ?? {};\n // Only the tables the config and flags name: Prisma's history table, which\n // other commands leave out on their own, stays listed for review here.\n const ignoreTables = [\n ...new Set([\n ...(project?.config.ignoreTables ?? []),\n ...(values[\"ignore-table\"] ?? []),\n ]),\n ];\n const result = await withDatabase({ databaseUrl }, (driver) =>\n context.progress(\"Reading the database\", () =>\n pullSchema({\n execute: driver.execute,\n ...(metadataSchema ? { metadataSchema } : {}),\n ...(metadataTable ? { metadataTable } : {}),\n ...(ignoreTables.length ? { ignoreTables } : {}),\n }),\n ),\n );\n\n await mkdir(dirname(path), { recursive: true });\n\n try {\n await writeFile(path, result.source, { flag: values.force ? \"w\" : \"wx\" });\n } catch (error) {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"EEXIST\"\n ) {\n throw new Error(`symmetria: ${path} exists; use --force to overwrite it`);\n }\n\n throw error;\n }\n\n const summary = `${result.tables.length} ${result.tables.length === 1 ? \"table\" : \"tables\"} from schema \"${result.schemaName}\"`;\n context.emit({\n json: {\n path,\n schema: result.schemaName,\n tables: result.tables,\n enumerations: result.enumerations,\n warnings: result.warnings,\n },\n indent: 2,\n pretty: () =>\n `${formatCreated(dirname(path), [basename(path)], color)} ${context.style(summary, \"muted\")}\\n\\n${formatPullWarnings(result.warnings, color)}`,\n plain: () =>\n [\n \"Created\",\n ` ${path}`,\n ` ${summary}`,\n \"\",\n ...(result.warnings.length\n ? [\n `Review (${result.warnings.length})`,\n ...result.warnings.flatMap((warning) => [\n ` [${warning.code}] ${warning.message}`,\n ...(warning.fix ? [` fix: ${warning.fix}`] : []),\n ]),\n ]\n : [\"Nothing needs review; the schema matches the database.\"]),\n ].join(\"\\n\"),\n });\n};\n","import type { MigrationDiffOptions, MigrationSnapshot } from \"../../index\";\nimport type { Choose } from \"../ui/terminal\";\n\n/** Suggestions are decisions, never guessed renames; persisted SQL records the result. */\nexport const resolveRenames = async (\n before: MigrationSnapshot,\n after: MigrationSnapshot,\n select: Choose,\n options: MigrationDiffOptions = {},\n): Promise<MigrationDiffOptions> => {\n const tables = { ...options.renames?.tables };\n const columns: Record<string, Record<string, string>> = Object.fromEntries(\n Object.entries(options.renames?.columns ?? {}).map(([name, entries]) => [\n name,\n { ...entries },\n ]),\n );\n\n const shape = (table: MigrationSnapshot[\"tables\"][number]) =>\n JSON.stringify(\n table.columns.map((column) => [\n column.name,\n column.sqlType,\n column.notNull,\n ]),\n );\n\n for (const old of before.tables.filter(\n (table) =>\n !tables[table.name] &&\n !after.tables.some((next) => next.name === table.name),\n )) {\n const candidates = after.tables.filter(\n (next) =>\n !Object.values(tables).includes(next.name) &&\n !before.tables.some((table) => table.name === next.name) &&\n shape(old) === shape(next),\n );\n\n if (!candidates.length) {\n continue;\n }\n\n const choice = await select(\n `Table ${old.name} disappeared. How should this change be represented?`,\n [\n ...candidates.map(\n (candidate) => `Rename ${old.name} → ${candidate.name}`,\n ),\n \"Drop and add tables\",\n ],\n );\n\n if (choice === undefined) {\n throw new Error(\"symmetria: migration generation cancelled\");\n }\n\n if (choice < candidates.length) {\n tables[old.name] = candidates[choice]!.name;\n }\n }\n\n for (const oldTable of before.tables) {\n const table = after.tables.find(\n (next) => next.name === (tables[oldTable.name] ?? oldTable.name),\n );\n\n if (!table) {\n continue;\n }\n\n const hints = columns[table.name] ?? {};\n\n for (const old of oldTable.columns.filter(\n (column) =>\n !hints[column.name] &&\n !table.columns.some((next) => next.name === column.name),\n )) {\n const candidates = table.columns.filter(\n (next) =>\n !Object.values(hints).includes(next.name) &&\n !oldTable.columns.some((column) => column.name === next.name) &&\n next.sqlType === old.sqlType &&\n next.notNull === old.notNull,\n );\n\n if (!candidates.length) {\n continue;\n }\n\n const choice = await select(\n `${table.name}.${old.name} disappeared. How should this change be represented?`,\n [\n ...candidates.map(\n (candidate) => `Rename ${old.name} → ${candidate.name}`,\n ),\n \"Drop column and add new columns\",\n ],\n );\n\n if (choice === undefined) {\n throw new Error(\"symmetria: migration generation cancelled\");\n }\n\n if (choice < candidates.length) {\n hints[old.name] = candidates[choice]!.name;\n }\n }\n\n if (Object.keys(hints).length) {\n columns[table.name] = hints;\n }\n }\n\n return { ...options, renames: { tables, columns } };\n};\n","/**\n * Schema-only CLI commands that need no database: inspect, lint, diff and generate.\n */\nimport { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { postgres } from \"symmetria/driver\";\nimport type { SchemaSnapshot } from \"symmetria\";\nimport {\n diffSchemas,\n formatLintFindings,\n generateMigration,\n lintMigration,\n lintMigrationSQL,\n loadMigrationState,\n migrationSnapshot,\n migrator,\n type MigrationDiffOptions,\n} from \"../../index\";\nimport { formatCreated, formatDiff, formatSchema } from \"../ui/format\";\nimport { inspectSchema } from \"../screens/schema-browser\";\nimport { resolveRenames } from \"../screens/rename-prompt\";\nimport { ask, withScreen } from \"../ui/terminal\";\nimport type { CliContext, Project } from \"../context\";\n\n/** The declared schema, required unless the command can run without one. */\nconst declaredSchema = (\n project: Project,\n required: boolean,\n): SchemaSnapshot | undefined => {\n const snapshot = project.snapshot();\n\n if (required && !snapshot) {\n throw new Error(\n \"symmetria: configure schema in symmetria.config.ts before inspecting or generating a migration\",\n );\n }\n\n return snapshot;\n};\n\nconst readDiffOptions = async (\n context: CliContext,\n): Promise<MigrationDiffOptions> => {\n const { values } = context;\n const options: MigrationDiffOptions = values.diff\n ? JSON.parse(await readFile(resolve(values.diff), \"utf8\"))\n : {};\n\n return values.online ? { ...options, online: true } : options;\n};\n\n/** `inspect [table]`: the schema browser, or a listing of tables, columns and relations. */\nexport const inspect = async (\n context: CliContext,\n project: Project,\n name: string | undefined,\n): Promise<void> => {\n const { values, color } = context;\n const snapshot = declaredSchema(project, true)!;\n const tables = name\n ? snapshot.tables.filter(\n (table) => table.name === name || table.sqlName === name,\n )\n : snapshot.tables;\n\n if (name && !tables.length) {\n throw new Error(`symmetria: unknown table \"${name}\"`);\n }\n\n if (context.interactive) {\n return withScreen(() =>\n inspectSchema(snapshot, {\n color,\n ...(name ? { table: name } : {}),\n tab: values.relations ? \"Relations\" : \"Columns\",\n }),\n );\n }\n\n context.emit({\n json: {\n tables: values.relations\n ? tables.map((table) => ({\n name: table.name,\n relations: table.relations,\n }))\n : tables,\n },\n replacer: (_name, value) =>\n typeof value === \"bigint\" ? value.toString() : value,\n indent: 2,\n plain: () => formatSchema(snapshot, name, values.relations, color),\n });\n};\n\n/** `lint`: review saved up.sql files and the ungenerated schema diff. */\nexport const lint = async (\n context: CliContext,\n project: Project,\n): Promise<void> => {\n const { values } = context;\n const diffOptions = await readDiffOptions(context);\n const snapshot = declaredSchema(project, false);\n const { snapshot: before, migrations } = await loadMigrationState(\n project.directory,\n );\n const after = snapshot ? migrationSnapshot(snapshot) : before;\n const plan = diffSchemas(before, after, diffOptions);\n let selected = migrations;\n\n if (values.pending) {\n if (!project.databaseUrl) {\n throw new Error(\n \"symmetria: --pending needs a database: set databaseUrl in the config, DATABASE_URL or --database-url\",\n );\n }\n\n const driver = postgres(project.databaseUrl);\n\n try {\n const statuses = await migrator({\n driver,\n ...project.runnerOptions,\n }).status();\n\n if (statuses.some((entry) => entry.status === \"incomplete\")) {\n throw new Error(\n \"symmetria: repair incomplete migrations before linting the pending chain\",\n );\n }\n\n selected = migrations.filter((migration) =>\n statuses.some(\n (status) => status.id === migration.id && status.status === \"pending\",\n ),\n );\n } finally {\n await driver.close();\n }\n }\n\n const findings = [\n ...selected.flatMap((migration) =>\n lintMigrationSQL(migration.up, migration.id),\n ),\n ...lintMigration(plan, diffOptions.renames),\n ];\n context.emit({\n json: { findings },\n indent: 2,\n plain: () => formatLintFindings(findings),\n });\n\n if (\n findings.some((finding) => values.strict || finding.level !== \"caution\")\n ) {\n process.exitCode = 1;\n }\n};\n\n/** `diff`: compare the declared schema with the latest local snapshot. */\nexport const diff = async (\n context: CliContext,\n project: Project,\n): Promise<void> => {\n const { values, color, output } = context;\n const diffOptions = await readDiffOptions(context);\n const snapshot = declaredSchema(project, true)!;\n const { snapshot: before } = await loadMigrationState(project.directory);\n const plan = diffSchemas(before, migrationSnapshot(snapshot), diffOptions);\n\n if (values.sql) {\n output(plan.up.map((statement) => `${statement};`).join(\"\\n\\n\"));\n\n return;\n }\n\n context.emit({\n json: plan,\n indent: 2,\n plain: () => formatDiff(plan, color, diffOptions.renames),\n });\n};\n\n/** `generate [name]`: write up.sql, down.sql and the versioned snapshot. */\nexport const generate = async (\n context: CliContext,\n project: Project,\n requestedName: string | undefined,\n): Promise<void> => {\n const { values, color, pretty, interactive, output } = context;\n let diffOptions = await readDiffOptions(context);\n const snapshot = declaredSchema(project, !values.empty);\n const { snapshot: before } = await loadMigrationState(project.directory);\n const after =\n snapshot && !values.empty ? migrationSnapshot(snapshot) : before;\n\n if (interactive && !values.empty) {\n diffOptions = await resolveRenames(\n before,\n after,\n context.select,\n diffOptions,\n );\n }\n\n const plan = diffSchemas(before, after, diffOptions);\n const name = requestedName ?? (await ask(\"Migration name:\", color));\n\n if (!name) {\n throw new Error(\"symmetria: generate requires a migration name\");\n }\n\n if (pretty && !values.json && !values.empty) {\n output(formatDiff(plan, color, diffOptions.renames));\n }\n\n const migration = await context.progress(\"Writing migration\", () =>\n generateMigration({\n ...diffOptions,\n directory: project.directory,\n name,\n ...(snapshot ? { snapshot } : {}),\n ...(values.empty ? { empty: true } : {}),\n ...(values[\"allow-destructive\"] ? { allowDestructive: true } : {}),\n ...(values.transaction\n ? { transaction: values.transaction as \"batch\" | \"each\" | \"none\" }\n : {}),\n ...(values.online ? { online: true } : {}),\n }),\n );\n const directory = project.directory;\n // What the migration does to existing data and to the running application:\n // the same review as lint, shown where the migration is made.\n const findings = migration ? lintMigration(plan, diffOptions.renames) : [];\n const review = findings.length\n ? `\\n\\nReview before applying:\\n${formatLintFindings(findings)}`\n : \"\";\n context.emit({\n json: migration\n ? {\n id: migration.id,\n directory: resolve(directory, migration.id),\n metadataDirectory: resolve(directory, \"meta\"),\n up: migration.up,\n down: migration.down,\n findings,\n }\n : { id: null, changed: false },\n pretty: () =>\n migration\n ? `${formatCreated(\n directory,\n [\n `${migration.id}/up.sql`,\n `${migration.id}/down.sql`,\n \"meta/snapshot.json\",\n \"meta/migration.json\",\n ],\n color,\n )}${review}`\n : \"No schema changes.\",\n plain: () =>\n migration ? `Generated ${migration.id}${review}` : \"No schema changes.\",\n });\n};\n","/**\n * Dispatches a parsed command line to the command implementation in ./schema, ./database,\n * ./files, ./graph, ./init, ./pull or ./profile.\n */\nimport { loadProject, type CliContext } from \"../context\";\nimport type { Command } from \"../options\";\nimport { dashboard } from \"../screens/dashboard\";\nimport {\n adopt,\n drift,\n migrate,\n repair,\n rollback,\n status,\n verify,\n} from \"./database\";\nimport { discard, recover, squash } from \"./files\";\nimport { graph } from \"./graph\";\nimport { init } from \"./init\";\nimport { profile } from \"./profile\";\nimport { pull } from \"./pull\";\nimport { diff, generate, inspect, lint } from \"./schema\";\n\n/** Runs one command; every command except `profile`, `init` and `pull` works on the loaded project. */\nexport const runCommand = async (\n command: Command,\n name: string | undefined,\n context: CliContext,\n): Promise<void> => {\n switch (command) {\n case \"profile\":\n return profile(context);\n case \"init\":\n return init(context, name);\n case \"pull\":\n return pull(context, name);\n default:\n }\n\n const project = await loadProject(context);\n\n switch (command) {\n case \"recover\":\n return recover(context, project);\n case \"squash\":\n return squash(context, project, name!);\n case \"discard\":\n return discard(context, project, name);\n case \"dashboard\":\n return dashboard(context, project);\n case \"inspect\":\n return inspect(context, project, name);\n case \"graph\":\n return graph(context, project, name);\n case \"lint\":\n return lint(context, project);\n case \"diff\":\n return diff(context, project);\n case \"generate\":\n return generate(context, project, name);\n case \"verify\":\n return verify(context, project);\n case \"drift\":\n return drift(context, project);\n case \"repair\":\n return repair(context, project, name!);\n case \"adopt\":\n return adopt(context, project);\n case \"status\":\n return status(context, project);\n case \"migrate\":\n return migrate(context, project);\n case \"rollback\":\n return rollback(context, project);\n }\n};\n","/** Command-line surface: help text, flag parsing and the rules that tie flags to commands. */\nimport { parseArgs } from \"node:util\";\n\nexport const help = `symmetria <command>\n\n init [directory] Create modular tables, connection and migration config\n pull [file] Write a schema module for an existing database (default: schema.ts)\n diff Compare schema code with the latest migration snapshot\n lint Review saved up.sql files and ungenerated schema changes\n inspect [table] Inspect tables, columns, relations, indexes and checks\n graph [file] Print or write a Mermaid entity-relationship diagram\n profile Observe live application requests and SQL timings\n generate <name> Generate up.sql and down.sql, and update the snapshot\n discard [id] Take back the latest migration while no database has applied it\n migrate Apply pending migrations atomically\n status Show applied and pending migrations\n rollback Revert the latest migration\n squash <name> Replace the migration chain with one baseline migration\n adopt Record the local chain as applied after a squash or baseline\n drift Compare the live database with the latest migration snapshot\n verify Exercise installation, upgrade and rollback in disposable databases\n repair <id> Resolve an incomplete migration after verifying its schema\n recover Recover files left by a crashed generation process\n (no command) Open the interactive dashboard in a terminal\n\n --config <file> Config module (default: symmetria.config.ts)\n --dir <directory> Override the migrations directory\n --database-url <url> Override config/database environment URL\n --profile-url <url> Profiler endpoint (default: http://127.0.0.1:7331)\n --profile-token <t> Profiler token (default: SYMMETRIA_PROFILE_TOKEN)\n --diff <file.json> Explicit rename hints and USING conversions for generate\n --empty Generate an empty, editable SQL migration\n --allow-destructive Explicitly permit destructive generation\n --allow-custom-sql squash: drop SQL that generate did not write (seeds, edits)\n --transaction <mode> batch (default), each, or none\n --pending Lint only migrations pending in the configured database\n --online generate/diff/lint: concurrent indexes and phased validation (transaction none)\n --plan Show SQL and transaction groups without executing migrations\n --action <action> repair: retry or complete, after manual data reconciliation\n --verify-url <url> Administrative PostgreSQL URL for disposable verification databases\n --snapshot <file> repair: meta/snapshot.json of the boundary to verify, instead of --verify-url\n --advisory-lock-timeout <ms> Migration lock wait (default: 10000)\n --lock-timeout <ms> DDL lock wait (default: 5000; 0 disables)\n --statement-timeout <ms> Statement duration (default: 600000, no default in transaction none migrations; 0 disables)\n --to <migration-id> Apply up to a migration\n --ignore-table <name> pull/drift/adopt/repair/verify: leave an undeclared table out (repeatable)\n --steps <number> Number of migrations to rollback (default: 1)\n --yes rollback: run down.sql without asking (required without a terminal)\n --strict Exit with code 1 when lint or drift report findings\n --force pull/graph: overwrite the file; discard: without a database, or an edited up.sql\n --compact graph: entities and relations without column lists\n --sql Print executable SQL for diff\n --json Machine-readable output\n --relations Show the relation graph with inspect\n --no-color Disable terminal colors\n --no-animation Disable logo and loading animations\n --no-interactive Disable dashboard, schema browser and rename questions\n --help, -h Show this help\n`;\n\nconst COMMANDS = [\n \"generate\",\n \"migrate\",\n \"status\",\n \"rollback\",\n \"init\",\n \"pull\",\n \"graph\",\n \"diff\",\n \"lint\",\n \"squash\",\n \"adopt\",\n \"drift\",\n \"inspect\",\n \"dashboard\",\n \"profile\",\n \"verify\",\n \"repair\",\n \"recover\",\n \"discard\",\n] as const;\nexport type Command = (typeof COMMANDS)[number];\n\n/** Every flag; `--help`, the README and the reference list each one. */\nexport const FLAGS = {\n config: { type: \"string\" },\n dir: { type: \"string\" },\n \"database-url\": { type: \"string\" },\n \"profile-url\": { type: \"string\" },\n \"profile-token\": { type: \"string\" },\n diff: { type: \"string\" },\n strict: { type: \"boolean\" },\n force: { type: \"boolean\" },\n compact: { type: \"boolean\" },\n empty: { type: \"boolean\" },\n \"allow-destructive\": { type: \"boolean\" },\n \"allow-custom-sql\": { type: \"boolean\" },\n \"ignore-table\": { type: \"string\", multiple: true },\n transaction: { type: \"string\" },\n pending: { type: \"boolean\" },\n online: { type: \"boolean\" },\n plan: { type: \"boolean\" },\n action: { type: \"string\" },\n \"verify-url\": { type: \"string\" },\n snapshot: { type: \"string\" },\n \"advisory-lock-timeout\": { type: \"string\" },\n \"lock-timeout\": { type: \"string\" },\n \"statement-timeout\": { type: \"string\" },\n to: { type: \"string\" },\n steps: { type: \"string\" },\n yes: { type: \"boolean\" },\n help: { type: \"boolean\", short: \"h\" },\n sql: { type: \"boolean\" },\n json: { type: \"boolean\" },\n relations: { type: \"boolean\" },\n \"no-color\": { type: \"boolean\" },\n \"no-animation\": { type: \"boolean\" },\n \"no-interactive\": { type: \"boolean\" },\n} as const;\n\nexport const parseCommandLine = (argumentsList: string[]) =>\n parseArgs({\n args: argumentsList,\n allowPositionals: true,\n strict: true,\n options: FLAGS,\n });\n\ntype CommandLine = ReturnType<typeof parseCommandLine>;\nexport type CliValues = CommandLine[\"values\"];\n\n/** Commands that take a second positional argument (a name or an ID). */\nconst NAMED: readonly Command[] = [\n \"generate\",\n \"inspect\",\n \"init\",\n \"pull\",\n \"graph\",\n \"squash\",\n \"repair\",\n \"discard\",\n];\n\n/** Flags that belong to specific commands, with the exact refusal wording. */\nconst SCOPED_FLAGS: readonly {\n readonly flags: readonly (keyof CliValues)[];\n readonly commands: readonly Command[];\n readonly message: string;\n}[] = [\n {\n flags: [\"allow-destructive\", \"transaction\"],\n commands: [\"generate\"],\n message:\n \"symmetria: --allow-destructive and --transaction are generate options\",\n },\n {\n flags: [\"online\"],\n commands: [\"generate\", \"diff\", \"lint\"],\n message: \"symmetria: --online is a generate/diff/lint option\",\n },\n {\n flags: [\"allow-custom-sql\"],\n commands: [\"squash\"],\n message: \"symmetria: --allow-custom-sql is a squash option\",\n },\n {\n flags: [\"ignore-table\"],\n commands: [\"pull\", \"drift\", \"adopt\", \"repair\", \"verify\"],\n message:\n \"symmetria: --ignore-table is a pull/drift/adopt/repair/verify option\",\n },\n {\n flags: [\"pending\"],\n commands: [\"lint\"],\n message: \"symmetria: --pending is a lint option\",\n },\n {\n flags: [\"plan\"],\n commands: [\"migrate\", \"rollback\"],\n message: \"symmetria: --plan is a migrate/rollback option\",\n },\n {\n flags: [\"action\"],\n commands: [\"repair\"],\n message: \"symmetria: --action is a repair option\",\n },\n {\n flags: [\"snapshot\"],\n commands: [\"repair\"],\n message: \"symmetria: --snapshot is a repair option\",\n },\n {\n flags: [\"strict\"],\n commands: [\"lint\", \"drift\"],\n message: \"symmetria: --strict is a lint/drift option\",\n },\n {\n flags: [\"diff\"],\n commands: [\"generate\", \"diff\", \"lint\"],\n message:\n \"symmetria: --diff is for generate/diff/lint; --empty is for generate\",\n },\n {\n flags: [\"empty\"],\n commands: [\"generate\"],\n message:\n \"symmetria: --diff is for generate/diff/lint; --empty is for generate\",\n },\n {\n flags: [\"sql\"],\n commands: [\"diff\"],\n message: \"symmetria: --sql is a diff option\",\n },\n {\n flags: [\"relations\"],\n commands: [\"inspect\"],\n message: \"symmetria: --relations is an inspect option\",\n },\n {\n flags: [\"to\"],\n commands: [\"migrate\", \"adopt\"],\n message: \"symmetria: --to is a migrate/adopt option\",\n },\n {\n flags: [\"steps\"],\n commands: [\"rollback\"],\n message: \"symmetria: --steps is a rollback option\",\n },\n {\n flags: [\"yes\"],\n commands: [\"rollback\"],\n message: \"symmetria: --yes is a rollback option\",\n },\n {\n flags: [\"force\"],\n commands: [\"pull\", \"graph\", \"discard\"],\n message: \"symmetria: --force is a pull/graph/discard option\",\n },\n {\n flags: [\"compact\"],\n commands: [\"graph\"],\n message: \"symmetria: --compact is a graph option\",\n },\n];\n\n/** Resolves the command and its name, then rejects flags and arguments that do not fit it. */\nexport const resolveCommand = (\n { values, positionals }: CommandLine,\n interactive: boolean,\n): { command: Command; name: string | undefined } => {\n const command = (positionals[0] ?? \"dashboard\") as Command;\n const name = positionals[1];\n\n if (!COMMANDS.includes(command)) {\n throw new Error(`symmetria: unknown command \"${command}\"`);\n }\n\n if (positionals.length > (NAMED.includes(command) ? 2 : 1)) {\n throw new Error(\"symmetria: unexpected positional arguments\");\n }\n\n if (command === \"generate\" && !name && !interactive) {\n throw new Error(\"symmetria: generate requires a migration name\");\n }\n\n if (command === \"squash\" && !name) {\n throw new Error(\"symmetria: squash requires a migration name\");\n }\n\n for (const rule of SCOPED_FLAGS) {\n if (\n !rule.commands.includes(command) &&\n rule.flags.some((flag) => values[flag])\n ) {\n throw new Error(rule.message);\n }\n }\n\n if (\n values.transaction &&\n ![\"batch\", \"each\", \"none\"].includes(values.transaction)\n ) {\n throw new Error(\"symmetria: --transaction must be batch, each, or none\");\n }\n\n if (\n command === \"repair\" &&\n (!name || ![\"retry\", \"complete\"].includes(values.action ?? \"\"))\n ) {\n throw new Error(\n \"symmetria: repair requires an ID and --action retry|complete\",\n );\n }\n\n if (values.sql && values.json) {\n throw new Error(\"symmetria: choose either --sql or --json\");\n }\n\n return { command, name };\n};\n","#!/usr/bin/env node\n/**\n * `symmetria` command line. Parsing and flag rules live in ./options,\n * the shared environment in ./context and each command in ./commands.\n */\nimport { runCommand } from \"./commands\";\nimport { createContext, type Output } from \"./context\";\nimport { formatHelp } from \"./ui/format\";\nimport { help, parseCommandLine, resolveCommand } from \"./options\";\nimport { formatError, supportsColor } from \"./ui/style\";\nimport { sqlState } from \"symmetria\";\nimport { MigrationExecutionError } from \"../migrations/execution\";\n\n/** A failure as JSON: the message, plus the failing statement for migration errors. */\nconst errorJSON = (error: unknown, message: string) => {\n if (error instanceof MigrationExecutionError) {\n return {\n message,\n migration: error.migration,\n direction: error.direction,\n statement: error.statement,\n sql: error.sql,\n ...(error.sqlState ? { sqlState: error.sqlState } : {}),\n ...(error.detail ? { detail: error.detail } : {}),\n };\n }\n\n const state = sqlState(error);\n\n return state ? { message, sqlState: state } : { message };\n};\n\nconst runMigrationCLI = async (\n argumentsList: string[],\n output: Output = (message) => console.log(message),\n): Promise<void> => {\n const parsed = parseCommandLine(argumentsList);\n const context = createContext(parsed.values, output, runMigrationCLI);\n\n if (\n parsed.values.help ||\n (!parsed.positionals.length && !context.interactive)\n ) {\n output(\n context.pretty && !parsed.values.json && !parsed.values.sql\n ? formatHelp(help, context.color)\n : help,\n );\n\n return;\n }\n\n const { command, name } = resolveCommand(parsed, context.interactive);\n await runCommand(command, name, context);\n};\n\nif (import.meta.main) {\n try {\n try {\n // Bun loads .env on its own; releases before 1.4 lack process.loadEnvFile.\n process.loadEnvFile?.();\n } catch (error) {\n if (\n !(\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n )\n ) {\n throw error;\n }\n }\n\n await runMigrationCLI(process.argv.slice(2));\n } catch (error) {\n let cause: unknown = error;\n const messages: string[] = [];\n\n while (cause instanceof Error) {\n const { message } = cause;\n\n // Wrappers such as MigrationExecutionError already quote their cause.\n if (!messages.some((previous) => previous.includes(message))) {\n messages.push(message);\n }\n\n cause = cause.cause;\n }\n\n const message = messages.length ? messages.join(\"\\n\") : String(error);\n\n if (process.argv.includes(\"--json\")) {\n // Machine-readable runs get JSON on failure too, on stdout like a result.\n console.log(JSON.stringify({ error: errorJSON(error, message) }));\n } else {\n console.error(\n formatError(\n message,\n supportsColor() &&\n !process.argv.includes(\"--no-color\") &&\n !process.argv.includes(\"--sql\"),\n ),\n );\n }\n\n // Ctrl-C and SIGTERM already chose 130 and 143.\n if (!process.exitCode) {\n process.exitCode = 1;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8CA,MAAa,iBACX,QACA,QACA,UACe;CACf,MAAM,SAAS,CAAC,CAAC,QAAQ,OAAO,SAAS,QAAQ,IAAI,SAAS;CAC9D,MAAM,cACJ,CAAC,CAAC,QAAQ,MAAM,SAChB,UACA,CAAC,OAAO,qBACR,CAAC,OAAO,QACR,CAAC,OAAO;CACV,MAAM,QACJ,cAAc,KAAK,CAAC,OAAO,eAAe,CAAC,OAAO,QAAQ,CAAC,OAAO;CACpE,MAAM,EAAE,UAAU,MAAM,KAAK;CAE7B,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA,WAAW,OAAO,cAChB,YAAY,OAAO,WAAW;GAC5B,SAAS,UAAU,CAAC,OAAO,QAAQ,CAAC,OAAO;GAC3C;GACA,WAAW,CAAC,OAAO;EACrB,CAAC;EACH,SAAS,UAAU,YAAY,OAAO,UAAU,SAAS,EAAE,MAAM,CAAC;EAClE,OAAO,cAAc;GACnB,OACE,OAAO,OACH,KAAK,UAAU,UAAU,MAAM,UAAU,UAAU,UAAU,MAAM,IACnE,UAAU,UAAU,SAClB,UAAU,OAAO,IACjB,UAAU,MAAM,CACxB;EACF;EACA;CACF;AACF;AAcA,MAAM,gBAAgB;CACpB,C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