@forinda/kickjs-db 8.7.0 → 8.8.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/bin/kickjs-db.mjs +4 -1
- package/dist/cli.d.mts +2 -2
- package/dist/cli.d.mts.map +1 -1
- package/dist/cli.mjs +3 -3
- package/dist/cli.mjs.map +1 -1
- package/dist/create-K_h9SGPl.mjs +29 -0
- package/dist/create-K_h9SGPl.mjs.map +1 -0
- package/dist/{custom-type-CqYKyYJW.mjs → custom-type-BPJpUuWz.mjs} +2 -2
- package/dist/{custom-type-CqYKyYJW.mjs.map → custom-type-BPJpUuWz.mjs.map} +1 -1
- package/dist/devtools-events.d.mts +1 -1
- package/dist/devtools-events.mjs +1 -1
- package/dist/{index-DH4qiCqU.d.mts → index-sRSu3kiL.d.mts} +53 -9
- package/dist/{index-DH4qiCqU.d.mts.map → index-sRSu3kiL.d.mts.map} +1 -1
- package/dist/index.d.mts +6 -6
- package/dist/index.mjs +2 -2
- package/dist/mysql.d.mts +2 -2
- package/dist/mysql.mjs +2 -2
- package/dist/{pg-DGxRYyFW.mjs → pg-CJr6OX2u.mjs} +3 -3
- package/dist/{pg-DGxRYyFW.mjs.map → pg-CJr6OX2u.mjs.map} +1 -1
- package/dist/pg.d.mts +3 -3
- package/dist/pg.mjs +2 -2
- package/dist/{schema-BIPOM1xj.d.mts → schema-BP_TZ1Sv.d.mts} +3 -3
- package/dist/{schema-BIPOM1xj.d.mts.map → schema-BP_TZ1Sv.d.mts.map} +1 -1
- package/dist/{schema-types-DIccweFR.d.mts → schema-types-DqdkKV19.d.mts} +3 -3
- package/dist/{schema-types-DIccweFR.d.mts.map → schema-types-DqdkKV19.d.mts.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +2 -2
- package/dist/{split-statements-BTlvQSAj.mjs → split-statements-E5gaoZIS.mjs} +2 -2
- package/dist/{split-statements-BTlvQSAj.mjs.map → split-statements-E5gaoZIS.mjs.map} +1 -1
- package/dist/sqlite.d.mts +1 -1
- package/dist/sqlite.d.mts.map +1 -1
- package/dist/sqlite.mjs +5 -5
- package/dist/sqlite.mjs.map +1 -1
- package/dist/{src-CcX7Jjfq.mjs → src-TXge_81j.mjs} +5 -5
- package/dist/src-TXge_81j.mjs.map +1 -0
- package/dist/{table-B_TVt7EC.d.mts → table-xq-X29gB.d.mts} +2 -2
- package/dist/{table-B_TVt7EC.d.mts.map → table-xq-X29gB.d.mts.map} +1 -1
- package/dist/testing.d.mts +2 -2
- package/dist/testing.mjs +2 -2
- package/dist/{types-DtX5fIbn.d.mts → types-LCdRbLC1.d.mts} +22 -1
- package/dist/types-LCdRbLC1.d.mts.map +1 -0
- package/dist/{types-p2E6CrKO.d.mts → types-ydAqBLR1.d.mts} +43 -6
- package/dist/types-ydAqBLR1.d.mts.map +1 -0
- package/package.json +4 -4
- package/dist/create-BS-WBMOA.mjs +0 -29
- package/dist/create-BS-WBMOA.mjs.map +0 -1
- package/dist/src-CcX7Jjfq.mjs.map +0 -1
- package/dist/types-DtX5fIbn.d.mts.map +0 -1
- package/dist/types-p2E6CrKO.d.mts.map +0 -1
package/bin/kickjs-db.mjs
CHANGED
|
@@ -42,7 +42,10 @@ async function importConfig(file) {
|
|
|
42
42
|
`Install it (\`npm i -D jiti\`) or use a .js/.mjs/.json config.`,
|
|
43
43
|
)
|
|
44
44
|
})
|
|
45
|
-
|
|
45
|
+
// From the config's own location, with the project's tsconfig `paths`:
|
|
46
|
+
// a lazy `db.adapter()` that imports src/db/client.ts, which imports
|
|
47
|
+
// `@/config`, resolves the alias the way the app does.
|
|
48
|
+
const jiti = createJiti(pathToFileURL(file).href, { tsconfigPaths: true })
|
|
46
49
|
return await jiti.import(file, { default: true })
|
|
47
50
|
}
|
|
48
51
|
const mod = await import(pathToFileURL(file).href)
|
package/dist/cli.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
import { m as Dialect } from "./types-
|
|
3
|
-
import {
|
|
2
|
+
import { m as Dialect } from "./types-LCdRbLC1.mjs";
|
|
3
|
+
import { Gi as TenantsConfig, Ui as DbConfig, Wi as MigrationAdapterFactory, qi as DriftBehavior } from "./index-sRSu3kiL.mjs";
|
|
4
4
|
import { CliTypegen, KickCliPlugin } from "@forinda/kickjs-cli-kit";
|
|
5
5
|
import { Command } from "commander";
|
|
6
6
|
//#region src/cli-typegen.d.ts
|
package/dist/cli.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.d.mts","names":["_$__cli_config0.TenantsConfig"],"sources":["../src/cli-typegen.ts","../src/cli.ts"],"mappings":";;;;;;qBA4Ba,qBAAoB;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"cli.d.mts","names":["_$__cli_config0.TenantsConfig"],"sources":["../src/cli-typegen.ts","../src/cli.ts"],"mappings":";;;;;;qBA4Ba,qBAAoB;;;;;;;;;iBCmDhB;EACf;EACA;;EAEA;EACA,UAAU;EACV;EACA,UAAU;;;;;;EAMV,aAAa;;EAEb;;EAEA;;EAEA,UANaA;;;;;;EAYb;;;;;;;;wBASc,mBAAmB,KAAK,oBAAoB;;;;;;wBAS5C,qBACX,UAAU,mCACZ;;wBAKa,oBAAoB,OAAO,gCAAgC;;YA4F/D,yBAAyB,WAAW,QAAQ;;;;;;;;;wBAUxC,mBAAmB,QAAQ,SAAS,WAAW;;;;;;;;;;;;;;qBA8alD,aAAa"}
|
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-db v8.
|
|
2
|
+
* @forinda/kickjs-db v8.8.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,8 +8,8 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{X as removeCasing,d as migrateLatest,f as migrateRollback,m as migrateUp,p as migrateStatus,u as migrateDown,w as loadModule}from"./create-
|
|
11
|
+
import{X as removeCasing,d as migrateLatest,f as migrateRollback,m as migrateUp,p as migrateStatus,u as migrateDown,w as loadModule}from"./create-K_h9SGPl.mjs";import{Ct as migrateTenants,Gt as renderSchemaSource,Ht as detectCompositeReferences,St as reviewMigration,_t as runSeeds,bt as pushSchema,vt as checkMigrations,xt as generate}from"./src-TXge_81j.mjs";import{writeFile}from"node:fs/promises";import{existsSync}from"node:fs";import path from"node:path";import{defineCliPlugin}from"@forinda/kickjs-cli-kit";import{createInterface}from"node:readline/promises";const DEFAULT_SCHEMA_PATHS=[`src/db/schema.ts`,`src/db/schema/index.ts`,`src/db/schema`],kickDbTypegen=()=>({id:`kick/db`,inputs:[`src/db/schema.ts`,`src/db/schema/**/*.ts`],async generate(ctx){let schemaAbs=resolveSchema(ctx.cwd,ctx.config?.db?.schemaPath);if(!schemaAbs)return null;let typesDir=path.resolve(ctx.cwd,`.kickjs/types`);return[`import type { SchemaToTypes, SchemaToRelationsRegister, KickDbClient } from '@forinda/kickjs-db'`,`import type * as appSchema from '${posix(path.relative(typesDir,schemaAbs)).replace(/\.ts$/,``).replace(/\/index$/,``)}'`,``,`declare global {`,` interface KickDbSchema extends SchemaToTypes<typeof appSchema> {}`,`}`,``,`declare module '@forinda/kickjs-db' {`,` interface KickDbRegister {`,` db: KickDbClient<KickDbSchema>`,` }`,``,` interface KickDbRelationsRegister {`,` db: SchemaToRelationsRegister<typeof appSchema>`,` }`,`}`].join(`
|
|
12
12
|
`)}});function resolveSchema(cwd,configuredPath){if(configuredPath){let abs=path.resolve(cwd,configuredPath);if(existsSync(abs))return abs;let idx=path.join(abs,`index.ts`);if(existsSync(idx))return idx}for(let candidate of DEFAULT_SCHEMA_PATHS){let abs=path.resolve(cwd,candidate);if(candidate.endsWith(`.ts`)){if(existsSync(abs))return abs}else{let idx=path.join(abs,`index.ts`);if(existsSync(idx))return idx}}return null}function posix(p){return p.replace(/\\/g,`/`)}function parseRenameFlags(tables=[],columns=[]){let pairs=(values,flag)=>values.map(v=>{let eq=v.indexOf(`=`);if(eq<=0||eq===v.length-1)throw Error(`kickjs-db: ${flag} expects old=new, got '${v}'`);return[v.slice(0,eq),v.slice(eq+1)]});for(let[from]of pairs(columns,`--rename-column`))if(!from.includes(`.`))throw Error(`kickjs-db: --rename-column expects table.old=new, got '${from}'`);return{tables:Object.fromEntries(pairs(tables,`--rename-table`)),columns:Object.fromEntries(pairs(columns,`--rename-column`))}}async function askRenamesInTerminal(candidates,io={input:process.stdin,output:process.stdout}){let rl=createInterface({input:io.input,output:io.output}),hints={tables:{},columns:{}};try{let ask=async(what,options)=>{let free=options.filter(o=>!Object.values(hints.tables).includes(o)&&!Object.values(hints.columns).includes(o));if(free.length===0)return;let list=free.map((o,i)=>` ${i+1}) renamed to ${o}`).join(`
|
|
13
|
-
`);for(;;){let answer=(await rl.question(`${what} is gone. Was it renamed?\n 0) no, drop it\n${list}\n> `)).trim(),n=answer===``?0:Number(answer);if(Number.isInteger(n)&&n>=0&&n<=free.length)return n===0?void 0:free[n-1]}};for(let c of candidates.tables){let to=await ask(`Table ${c.from}`,c.to);to&&(hints.tables[c.from]=to)}for(let c of candidates.columns){let to=await ask(`Column ${c.table}.${c.from}`,c.to);to&&(hints.columns[`${c.table}.${c.from}`]=to)}}finally{rl.close()}return hints}async function confirmInTerminal(question,io={input:process.stdin,output:process.stdout}){let rl=createInterface({input:io.input,output:io.output});try{return/^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim())}finally{rl.close()}}function runDirs(config){return config.migrationsDirs?.length?[config.migrationsDir,...config.migrationsDirs]:config.migrationsDir}function folderOf(config,id){return[config.migrationsDir,...config.migrationsDirs??[]].find(d=>existsSync(path.join(d,id)))??config.migrationsDir}function defineKickDbConfig(cfg){return cfg}function mergeKickDbConfig(...configs){return Object.assign({},...configs.filter(Boolean))}function resolveKickDbConfig(block){let db=block??{};return{schemaPath:db.schemaPath??`src/db/schema.ts`,migrationsDir:db.migrationsDir??`db/migrations`,seedsDir:db.seedsDir??`db/seeds`,dialect:db.dialect??`postgres`,connectionString:db.connectionString??process.env.DATABASE_URL,adapter:db.adapter,driftCheck:db.driftCheck,casing:db.casing,migrationsTable:db.migrationsTable,migrationsDirs:db.migrationsDirs,tenants:db.tenants}}async function resolveAdapter(config){if(config.adapter){let adapter=await config.adapter();return{adapter,cleanup:async()=>adapter.close()}}if(!config.connectionString)throw Error(`kickjs-db: no adapter resolved — set db.connectionString (or DATABASE_URL), or supply a db.adapter() factory`);let dialect=config.dialect??`postgres`;if(dialect!==`postgres`)throw Error(`kickjs-db: the built-in CLI adapter only supports postgres (dialect=${dialect}); supply a db.adapter() factory for other dialects`);let[{pgAdapter},pg]=await Promise.all([import(`./pg.mjs`),import(`pg`)]),pool=new pg.default.Pool({connectionString:config.connectionString}),adapter=pgAdapter({pool,migrationsTable:config.migrationsTable});return{adapter,cleanup:async()=>{await adapter.close(),await pool.end()}}}async function tryResolvePgQueryRunner(config){if(config.adapter||(config.dialect??`postgres`)!==`postgres`||!config.connectionString)return null;let pool=new(await(import(`pg`))).default.Pool({connectionString:config.connectionString});return{runner:pool,cleanup:async()=>void await pool.end()}}function printStatusTable(status){status.length===0?console.log(`No migrations.`):console.table(status.map(s=>({id:s.id,state:s.state,batch:s.batch??`-`,reviewed:s.reviewed,applied:s.appliedAt??`-`})))}function registerDbCommands(parent,getConfig){parent.command(`generate <name>`).description(`Generate a new migration from schema diff`).option(`-e, --empty`,`Skip schema diff and create an empty migration shell (data migration, seed, freeform SQL)`).option(`--rename-table <old=new>`,`Treat a dropped table as renamed (repeatable)`,(v,all=[])=>[...all,v]).option(`--rename-column <table.old=new>`,`Treat a dropped column as renamed (repeatable)`,(v,all=[])=>[...all,v]).option(`--no-interactive`,`Don't ask which drops are renames, even in a terminal`).option(`--ts`,`Write the migration in TypeScript — a migration.ts with up(db) / down(db) — for data changes that need code`).action(async(name,opts)=>{let cwd=process.cwd(),config=await getConfig(),probe=await tryResolvePgQueryRunner(config),detectCompositeRefs=probe?enumName=>detectCompositeReferences(probe.runner,enumName):void 0;try{let renames=parseRenameFlags(opts.renameTable,opts.renameColumn),askRenames=opts.interactive!==!1&&process.stdin.isTTY?askRenamesInTerminal:void 0,result=await generate({name,config,cwd,empty:opts.empty,typescript:opts.ts,detectCompositeRefs,renames,askRenames,onPossibleRename:askRenames?void 0:drop=>console.warn(`Warning: ${drop.what} will be dropped. If it was renamed, generate again with ${drop.flag} — the data goes with a drop.`)});if(result.status===`no-changes`){console.log(`No schema changes detected.`);return}if(result.empty){console.log(opts.ts?`Created migration ${result.migrationDir} (write up() and down() in migration.ts).`:`Created empty migration ${result.migrationDir} (author up.sql + down.sql).`);return}let plural=result.changeCount===1?``:`s`;console.log(`Created migration ${result.migrationDir} (${result.changeCount} change${plural}).`)}finally{await probe?.cleanup()}}),parent.command(`check`).description(`Fail if the schema has changes no migration covers, or a migration is unreviewed or edited (no database needed — for CI)`).action(async()=>{let config=await getConfig(),r=await checkMigrations({config,cwd:process.cwd()});if(r.unmigratedChanges>0){let plural=r.unmigratedChanges===1?``:`s`;console.error(`The schema has ${r.unmigratedChanges} change${plural} no migration covers — run \`kick db generate <name>\`.`)}for(let id of r.unreviewed)console.error(`${id} is not reviewed — read it, then \`kick db migrate review ${id}\`.`);for(let id of r.modified)console.error(`${id} was edited after it was reviewed — review it again, or revert the edit.`);r.ok?console.log(`Migrations are in step with the schema.`):process.exitCode=1}),parent.command(`push`).description(`Make the database match the schema with no migration file — for prototyping; refused on a database with migrations applied`).option(`--rename-table <old=new>`,`Treat a dropped table as renamed (repeatable)`,(v,all=[])=>[...all,v]).option(`--rename-column <table.old=new>`,`Treat a dropped column as renamed (repeatable)`,(v,all=[])=>[...all,v]).option(`--no-interactive`,`Don't ask about renames or data loss, even in a terminal`).option(`--accept-data-loss`,`Apply changes that drop tables, columns or enum values`).action(async opts=>{let config=await getConfig(),interactive=opts.interactive!==!1&&process.stdin.isTTY,schema=await loadModule(path.resolve(process.cwd(),config.schemaPath),{fresh:!0}),{adapter,cleanup}=await resolveAdapter(config);try{let r=await pushSchema({adapter,schema,casing:config.casing,renames:parseRenameFlags(opts.renameTable,opts.renameColumn),askRenames:interactive?askRenamesInTerminal:void 0,confirmDataLoss:opts.acceptDataLoss?async()=>!0:interactive?losses=>confirmInTerminal(`This loses data:\n${losses.map(l=>` - ${l}`).join(`
|
|
13
|
+
`);for(;;){let answer=(await rl.question(`${what} is gone. Was it renamed?\n 0) no, drop it\n${list}\n> `)).trim(),n=answer===``?0:Number(answer);if(Number.isInteger(n)&&n>=0&&n<=free.length)return n===0?void 0:free[n-1]}};for(let c of candidates.tables){let to=await ask(`Table ${c.from}`,c.to);to&&(hints.tables[c.from]=to)}for(let c of candidates.columns){let to=await ask(`Column ${c.table}.${c.from}`,c.to);to&&(hints.columns[`${c.table}.${c.from}`]=to)}}finally{rl.close()}return hints}async function confirmInTerminal(question,io={input:process.stdin,output:process.stdout}){let rl=createInterface({input:io.input,output:io.output});try{return/^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim())}finally{rl.close()}}function remoteHost(connectionString){let match=/^[a-z][\w+.-]*:\/\/(?:[^@/?#]*@)?([^/?#]*)[^?#]*(?:\?([^#]*))?/i.exec(connectionString??``);if(match)return(new URLSearchParams(match[2]??``).get(`host`)??decodeURIComponent(match[1]??``)).split(`,`).map(h=>stripPort(h.trim()).toLowerCase()).filter(h=>h&&!h.startsWith(`/`)).find(host=>!isLocal(host))}function stripPort(entry){return entry.startsWith(`[`)?entry.slice(1,entry.indexOf(`]`)):entry.replace(/:\d+$/,``)}function isLocal(host){return host===`localhost`||host===`::1`||host===`0.0.0.0`||host.startsWith(`127.`)||host.endsWith(`.localhost`)||host.endsWith(`.local`)||!host.includes(`.`)}function runDirs(config){return config.migrationsDirs?.length?[config.migrationsDir,...config.migrationsDirs]:config.migrationsDir}function folderOf(config,id){return[config.migrationsDir,...config.migrationsDirs??[]].find(d=>existsSync(path.join(d,id)))??config.migrationsDir}function defineKickDbConfig(cfg){return cfg}function mergeKickDbConfig(...configs){return Object.assign({},...configs.filter(Boolean))}function resolveKickDbConfig(block){let db=block??{};return{schemaPath:db.schemaPath??`src/db/schema.ts`,migrationsDir:db.migrationsDir??`db/migrations`,seedsDir:db.seedsDir??`db/seeds`,dialect:db.dialect??`postgres`,connectionString:db.connectionString??process.env.DATABASE_URL,adapter:db.adapter,driftCheck:db.driftCheck,casing:db.casing,migrationsTable:db.migrationsTable,migrationsDirs:db.migrationsDirs,tenants:db.tenants}}async function resolveAdapter(config){if(config.adapter){let adapter=await config.adapter();return{adapter,cleanup:async()=>adapter.close()}}if(!config.connectionString)throw Error(`kickjs-db: no adapter resolved — set db.connectionString (or DATABASE_URL), or supply a db.adapter() factory`);let dialect=config.dialect??`postgres`;if(dialect!==`postgres`)throw Error(`kickjs-db: the built-in CLI adapter only supports postgres (dialect=${dialect}); supply a db.adapter() factory for other dialects`);let[{pgAdapter},pg]=await Promise.all([import(`./pg.mjs`),import(`pg`)]),pool=new pg.default.Pool({connectionString:config.connectionString}),adapter=pgAdapter({pool,migrationsTable:config.migrationsTable});return{adapter,cleanup:async()=>{await adapter.close(),await pool.end()}}}async function tryResolvePgQueryRunner(config){if(config.adapter||(config.dialect??`postgres`)!==`postgres`||!config.connectionString)return null;let pool=new(await(import(`pg`))).default.Pool({connectionString:config.connectionString});return{runner:pool,cleanup:async()=>void await pool.end()}}function printStatusTable(status){status.length===0?console.log(`No migrations.`):console.table(status.map(s=>({id:s.id,state:s.state,batch:s.batch??`-`,reviewed:s.reviewed,applied:s.appliedAt??`-`})))}function registerDbCommands(parent,getConfig){parent.command(`generate <name>`).description(`Generate a new migration from schema diff`).option(`-e, --empty`,`Skip schema diff and create an empty migration shell (data migration, seed, freeform SQL)`).option(`--rename-table <old=new>`,`Treat a dropped table as renamed (repeatable)`,(v,all=[])=>[...all,v]).option(`--rename-column <table.old=new>`,`Treat a dropped column as renamed (repeatable)`,(v,all=[])=>[...all,v]).option(`--no-interactive`,`Don't ask which drops are renames, even in a terminal`).option(`--ts`,`Write the migration in TypeScript — a migration.ts with up(db) / down(db) — for data changes that need code`).action(async(name,opts)=>{let cwd=process.cwd(),config=await getConfig(),probe=await tryResolvePgQueryRunner(config),detectCompositeRefs=probe?enumName=>detectCompositeReferences(probe.runner,enumName):void 0;try{let renames=parseRenameFlags(opts.renameTable,opts.renameColumn),askRenames=opts.interactive!==!1&&process.stdin.isTTY?askRenamesInTerminal:void 0,result=await generate({name,config,cwd,empty:opts.empty,typescript:opts.ts,detectCompositeRefs,renames,askRenames,onPossibleRename:askRenames?void 0:drop=>console.warn(`Warning: ${drop.what} will be dropped. If it was renamed, generate again with ${drop.flag} — the data goes with a drop.`)});if(result.status===`no-changes`){console.log(`No schema changes detected.`);return}if(result.empty){console.log(opts.ts?`Created migration ${result.migrationDir} (write up() and down() in migration.ts).`:`Created empty migration ${result.migrationDir} (author up.sql + down.sql).`);return}let plural=result.changeCount===1?``:`s`;console.log(`Created migration ${result.migrationDir} (${result.changeCount} change${plural}).`)}finally{await probe?.cleanup()}}),parent.command(`check`).description(`Fail if the schema has changes no migration covers, or a migration is unreviewed or edited (no database needed — for CI)`).action(async()=>{let config=await getConfig(),r=await checkMigrations({config,cwd:process.cwd()});if(r.unmigratedChanges>0){let plural=r.unmigratedChanges===1?``:`s`;console.error(`The schema has ${r.unmigratedChanges} change${plural} no migration covers — run \`kick db generate <name>\`.`)}for(let id of r.unreviewed)console.error(`${id} is not reviewed — read it, then \`kick db migrate review ${id}\`.`);for(let id of r.modified)console.error(`${id} was edited after it was reviewed — review it again, or revert the edit.`);r.ok?console.log(`Migrations are in step with the schema.`):process.exitCode=1}),parent.command(`push`).description(`Make the database match the schema with no migration file — for prototyping; refused on a database with migrations applied`).option(`--rename-table <old=new>`,`Treat a dropped table as renamed (repeatable)`,(v,all=[])=>[...all,v]).option(`--rename-column <table.old=new>`,`Treat a dropped column as renamed (repeatable)`,(v,all=[])=>[...all,v]).option(`--no-interactive`,`Don't ask about renames or data loss, even in a terminal`).option(`--accept-data-loss`,`Apply changes that drop tables, columns or enum values`).option(`-y, --yes`,`Push to a remote database without asking`).action(async opts=>{let config=await getConfig(),interactive=opts.interactive!==!1&&process.stdin.isTTY,remote=remoteHost(config.connectionString);if(remote&&!opts.yes&&!(interactive&&await confirmInTerminal(`Push changes the database at ${remote} without a migration file. Continue?`)))throw Error(`kickjs-db: refusing to push to ${remote} — push is for a local prototyping database. Pass --yes if this is one.`);let schema=await loadModule(path.resolve(process.cwd(),config.schemaPath),{fresh:!0}),{adapter,cleanup}=await resolveAdapter(config);try{let r=await pushSchema({adapter,schema,casing:config.casing,renames:parseRenameFlags(opts.renameTable,opts.renameColumn),askRenames:interactive?askRenamesInTerminal:void 0,confirmDataLoss:opts.acceptDataLoss?async()=>!0:interactive?losses=>confirmInTerminal(`This loses data:\n${losses.map(l=>` - ${l}`).join(`
|
|
14
14
|
`)}\nApply it?`):void 0}),plural=r.changeCount===1?``:`s`;console.log(r.status===`no-changes`?`The database already matches the schema.`:`Pushed ${r.changeCount} change${plural}.`)}finally{await cleanup()}}),parent.command(`seed [names...]`).description(`Run the seed files in db/seeds (or only those named), in name order — no migration tracking, so make them safe to re-run`).action(async names=>{let config=await getConfig(),dir=path.resolve(process.cwd(),config.seedsDir??`db/seeds`);try{let{ran}=await runSeeds({dir,names});console.log(ran.length===0?`No seeds in ${dir}.`:`Ran ${ran.length} seed(s): ${ran.join(`, `)}`)}catch(err){console.error(err instanceof Error?err.message:String(err)),process.exitCode=1}process.stderr.write(``,()=>process.stdout.write(``,()=>process.exit(process.exitCode??0)))});let migrate=parent.command(`migrate`).description(`Migration runner subcommands`);migrate.command(`latest`).description(`Apply all pending migrations in a new batch`).option(`--confirm-enum-drop`,"Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply",!1).option(`--tenants`,`Migrate every tenant's schema or database (db.tenants in kick.config)`).action(async opts=>{let config=await getConfig();if(opts.tenants){if(!config.tenants)throw Error("kick db migrate latest --tenants needs a `tenants: { list, adapter }` db config");let r=await migrateTenants({tenants:config.tenants.list,adapterFor:config.tenants.adapter,concurrency:config.tenants.concurrency,migrationsDir:runDirs(config),driftCheck:config.driftCheck,confirmEnumDrop:opts.confirmEnumDrop,onTenant:t=>console.log(t.error?`✗ ${t.tenant}: ${t.error instanceof Error?t.error.message:String(t.error)}`:`✓ ${t.tenant}: ${t.summary.applied.length===0?`up to date`:t.summary.applied.join(`, `)}`)});console.log(`${r.results.length-r.failed.length} migrated, ${r.failed.length} failed`),r.failed.length>0&&(process.exitCode=1);return}let{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateLatest({adapter,migrationsDir:runDirs(config),driftCheck:config.driftCheck,confirmEnumDrop:opts.confirmEnumDrop});console.log(r.applied.length===0?`No pending migrations.`:`Applied batch ${r.batch}: ${r.applied.join(`, `)}`)}finally{await cleanup()}}),migrate.command(`up`).description(`Apply the next single pending migration, or every one up to --to`).option(`--to <migration>`,`Apply pending migrations up to and including this one (id or name)`).option(`--confirm-enum-drop`,"Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply",!1).action(async opts=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateUp({adapter,migrationsDir:runDirs(config),driftCheck:config.driftCheck,confirmEnumDrop:opts.confirmEnumDrop,to:opts.to});console.log(r.applied.length===0?`No pending migrations.`:`Applied ${r.applied.join(`, `)} (batch ${r.batch})`)}finally{await cleanup()}}),migrate.command(`down`).description(`Reverse the most recent applied migration, or every one after --to`).option(`--to <migration>`,`Reverse every migration applied after this one (id or name), which stays`).action(async opts=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateDown({adapter,migrationsDir:runDirs(config),driftCheck:config.driftCheck,to:opts.to});console.log(r.reversedAll.length>0?`Reversed ${r.reversedAll.join(`, `)}.`:`Nothing to reverse.`)}finally{await cleanup()}}),migrate.command(`rollback`).description(`Reverse the entire last batch as a single unit, or with --all every migration`).option(`--all`,`Reverse every applied migration, newest first`).action(async opts=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateRollback({adapter,migrationsDir:runDirs(config),driftCheck:config.driftCheck,all:opts.all});console.log(r.reversed.length===0?`Nothing to roll back.`:opts.all?`Rolled back every migration: ${r.reversed.join(`, `)}`:`Rolled back batch ${r.batch}: ${r.reversed.join(`, `)}`)}finally{await cleanup()}}),migrate.command(`status`).description(`Print applied + pending migrations`).action(async()=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{printStatusTable(await migrateStatus({adapter,migrationsDir:runDirs(config)}))}finally{await cleanup()}}),migrate.command(`unlock`).description(`Release the migration lock left by a run that was killed mid-migration (make sure none is running)`).action(async()=>{let{adapter,cleanup}=await resolveAdapter(await getConfig());try{await adapter.releaseLock(),console.log(`Released the migration lock.`)}finally{await cleanup()}}),migrate.command(`review <id>`).description(`Mark a migration reviewed (flips meta.json; migrates legacy -- REVIEWED markers)`).action(async id=>{let config=await getConfig(),r=await reviewMigration(folderOf(config,id),id);console.log(r.alreadyReviewed?`${r.id} was already reviewed — recorded its current contents as reviewed.`:`Reviewed ${r.id} — it can now be applied.`)}),parent.command(`introspect`).description(`Generate a TypeScript schema file from a live database`).option(`--out <path>`,`Output file (defaults to db.schemaPath from config)`).option(`--json`,`Print the raw SchemaSnapshot JSON to stdout instead of writing TS source`).action(async opts=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let snapshot=await adapter.introspect();if(opts.json){console.log(JSON.stringify(snapshot,null,2));return}let out=opts.out??config.schemaPath,source=config.casing===`snake_case`?removeCasing(snapshot):snapshot;await writeFile(out,renderSchemaSource(source),`utf8`);let n=Object.keys(snapshot.tables).length;console.log(`Wrote ${out} (${n} table${n===1?``:`s`}).`)}finally{await cleanup()}})}function dbBlockOf(config){return config?.db}const dbCliPlugin=defineCliPlugin({name:`kick/db`,register(program,ctx){registerDbCommands(program.command(`db`).description(`Database commands (kickjs-db)`),()=>resolveKickDbConfig(dbBlockOf(ctx.config)))},typegens:[kickDbTypegen()]});export{dbCliPlugin,defineKickDbConfig,kickDbTypegen,mergeKickDbConfig,registerDbCommands,resolveKickDbConfig};
|
|
15
15
|
//# sourceMappingURL=cli.mjs.map
|
package/dist/cli.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.mjs","names":[],"sources":["../src/cli-typegen.ts","../src/cli/renames.ts","../src/cli.ts"],"sourcesContent":["/**\n * `kick/db` typegen — reads the adopter's schema (`src/db/schema.ts` or a\n * `src/db/schema/` barrel) and emits `.kickjs/types/kick__db.d.ts` with\n * three augmentations:\n *\n * 1. global `KickDbSchema = SchemaToTypes<typeof appSchema>` — column\n * shapes computed at type-check time, no runtime cost.\n * 2. `KickDbRegister.db = KickDbClient<KickDbSchema>` — bare\n * `KickDbClient` widens automatically.\n * 3. `KickDbRelationsRegister.db = SchemaToRelationsRegister<typeof\n * appSchema>` — typed `with` keys for `db.query.X.findMany`.\n *\n * Shipped on {@link dbCliPlugin} (`typegens`) so mounting the db plugin\n * brings both the `kick db` commands and this type generation. Typed\n * against the `@forinda/kickjs-cli-kit` `CliTypegen` contract so it needs\n * no kickjs-cli internals — it only reads `ctx.cwd`.\n */\nimport path from 'node:path'\nimport { existsSync } from 'node:fs'\n\nimport type { CliTypegen } from '@forinda/kickjs-cli-kit'\n\nconst DEFAULT_SCHEMA_PATHS = [\n 'src/db/schema.ts',\n 'src/db/schema/index.ts',\n 'src/db/schema',\n] as const\n\nexport const kickDbTypegen = (): CliTypegen => ({\n id: 'kick/db',\n inputs: ['src/db/schema.ts', 'src/db/schema/**/*.ts'],\n async generate(ctx: { cwd: string; config?: { db?: { schemaPath?: string } } }) {\n // Parity with `kick db generate` (cli/config.ts resolveDbConfig):\n // an adopter-configured `db.schemaPath` must drive BOTH the\n // migration engine and this augmentation — previously only the\n // default candidates were probed, so a custom path produced\n // working migrations but a silently untyped client.\n const schemaAbs = resolveSchema(ctx.cwd, ctx.config?.db?.schemaPath)\n if (!schemaAbs) return null\n\n // Strip the `.ts` extension and any trailing `/index` so the import\n // specifier stays stable across single-file vs barrel-folder layouts.\n const typesDir = path.resolve(ctx.cwd, '.kickjs/types')\n const rel = posix(path.relative(typesDir, schemaAbs))\n .replace(/\\.ts$/, '')\n .replace(/\\/index$/, '')\n\n return [\n `import type { SchemaToTypes, SchemaToRelationsRegister, KickDbClient } from '@forinda/kickjs-db'`,\n `import type * as appSchema from '${rel}'`,\n ``,\n `declare global {`,\n ` interface KickDbSchema extends SchemaToTypes<typeof appSchema> {}`,\n `}`,\n ``,\n `declare module '@forinda/kickjs-db' {`,\n ` interface KickDbRegister {`,\n ` db: KickDbClient<KickDbSchema>`,\n ` }`,\n ``,\n ` interface KickDbRelationsRegister {`,\n ` db: SchemaToRelationsRegister<typeof appSchema>`,\n ` }`,\n `}`,\n ].join('\\n')\n },\n})\n\nfunction resolveSchema(cwd: string, configuredPath?: string): string | null {\n // kick.config `db.schemaPath` wins when the file exists; a configured-\n // but-missing path falls through to the candidates rather than\n // emitting an augmentation with a broken import specifier.\n if (configuredPath) {\n const abs = path.resolve(cwd, configuredPath)\n if (existsSync(abs)) return abs\n const idx = path.join(abs, 'index.ts')\n if (existsSync(idx)) return idx\n }\n for (const candidate of DEFAULT_SCHEMA_PATHS) {\n const abs = path.resolve(cwd, candidate)\n if (candidate.endsWith('.ts')) {\n if (existsSync(abs)) return abs\n } else {\n const idx = path.join(abs, 'index.ts')\n if (existsSync(idx)) return idx\n }\n }\n return null\n}\n\nfunction posix(p: string): string {\n return p.replace(/\\\\/g, '/')\n}\n","import { createInterface } from 'node:readline/promises'\nimport type { RenameCandidates, RenameHints } from '../diff/engine'\n\n/**\n * Parse `--rename-table old=new` / `--rename-column table.old=new` values.\n * A column's table is everything before its last dot, so a schema-qualified\n * table (`billing.invoices.total=amount`) works.\n */\nexport function parseRenameFlags(tables: string[] = [], columns: string[] = []): RenameHints {\n const pairs = (values: string[], flag: string) =>\n values.map((v) => {\n const eq = v.indexOf('=')\n if (eq <= 0 || eq === v.length - 1) {\n throw new Error(`kickjs-db: ${flag} expects old=new, got '${v}'`)\n }\n return [v.slice(0, eq), v.slice(eq + 1)] as const\n })\n for (const [from] of pairs(columns, '--rename-column')) {\n if (!from.includes('.')) {\n throw new Error(`kickjs-db: --rename-column expects table.old=new, got '${from}'`)\n }\n }\n return {\n tables: Object.fromEntries(pairs(tables, '--rename-table')),\n columns: Object.fromEntries(pairs(columns, '--rename-column')),\n }\n}\n\n/**\n * Ask in the terminal which drops are renames. Each candidate lists what it\n * could have become; the default (Enter) is to drop it — nothing is renamed\n * that someone didn't pick.\n */\nexport async function askRenamesInTerminal(\n candidates: RenameCandidates,\n io: { input: NodeJS.ReadableStream; output: NodeJS.WritableStream } = {\n input: process.stdin,\n output: process.stdout,\n },\n): Promise<RenameHints> {\n const rl = createInterface({ input: io.input, output: io.output })\n const hints: Required<RenameHints> = { tables: {}, columns: {} }\n try {\n const ask = async (what: string, options: string[]): Promise<string | undefined> => {\n const free = options.filter(\n (o) =>\n !Object.values(hints.tables).includes(o) && !Object.values(hints.columns).includes(o),\n )\n if (free.length === 0) return undefined\n const list = free.map((o, i) => ` ${i + 1}) renamed to ${o}`).join('\\n')\n for (;;) {\n const answer = (\n await rl.question(`${what} is gone. Was it renamed?\\n 0) no, drop it\\n${list}\\n> `)\n ).trim()\n const n = answer === '' ? 0 : Number(answer)\n if (Number.isInteger(n) && n >= 0 && n <= free.length)\n return n === 0 ? undefined : free[n - 1]\n }\n }\n for (const c of candidates.tables) {\n const to = await ask(`Table ${c.from}`, c.to)\n if (to) hints.tables[c.from] = to\n }\n for (const c of candidates.columns) {\n const to = await ask(`Column ${c.table}.${c.from}`, c.to)\n if (to) hints.columns[`${c.table}.${c.from}`] = to\n }\n } finally {\n rl.close()\n }\n return hints\n}\n\n/** Ask a yes/no question in the terminal; anything but y/yes is no. */\nexport async function confirmInTerminal(\n question: string,\n io: { input: NodeJS.ReadableStream; output: NodeJS.WritableStream } = {\n input: process.stdin,\n output: process.stdout,\n },\n): Promise<boolean> {\n const rl = createInterface({ input: io.input, output: io.output })\n try {\n return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim())\n } finally {\n rl.close()\n }\n}\n","/**\n * `@forinda/kickjs-db/cli` — the database command tree as a mountable CLI\n * plugin + the building blocks for a standalone `kickjs-db` bin.\n *\n * Two ways to use it:\n * 1. **As a kickjs-cli plugin** — add `dbCliPlugin` to `kick.config.ts`\n * `plugins: []`. The host CLI calls `register(program, ctx)` and the\n * db config is read from `ctx.config.db` (already loaded — no re-parse).\n * 2. **Standalone** — the `kickjs-db` bin builds a commander program,\n * resolves config from `kickjs-db.config.ts` (or a `kick.config.ts`\n * `db` block), and calls {@link registerDbCommands} directly. Lets\n * `npx kickjs-db migrate latest` work without installing kickjs-cli.\n *\n * @module @forinda/kickjs-db/cli\n */\n\nimport { existsSync } from 'node:fs'\nimport { writeFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport type { Command } from 'commander'\n\nimport { defineCliPlugin, type KickCliPlugin } from '@forinda/kickjs-cli-kit'\nimport { kickDbTypegen } from './cli-typegen'\nimport { checkMigrations } from './cli/check'\nimport { runSeeds } from './cli/seed'\nimport { removeCasing } from './snapshot/casing'\nimport { askRenamesInTerminal, confirmInTerminal, parseRenameFlags } from './cli/renames'\nimport { loadModule } from './cli/load-module'\n\n/** Every folder the runner reads: `migrationsDir`, then `migrationsDirs`. */\nfunction runDirs(config: DbConfig): string | string[] {\n return config.migrationsDirs?.length\n ? [config.migrationsDir, ...config.migrationsDirs]\n : config.migrationsDir\n}\n\n/** The folder holding a migration, among every folder the runner reads. */\nfunction folderOf(config: DbConfig, id: string): string {\n const dirs = [config.migrationsDir, ...(config.migrationsDirs ?? [])]\n return dirs.find((d) => existsSync(path.join(d, id))) ?? config.migrationsDir\n}\n\ninterface GenerateFlags {\n empty?: boolean\n ts?: boolean\n renameTable?: string[]\n renameColumn?: string[]\n interactive?: boolean\n}\n\nexport { kickDbTypegen } from './cli-typegen'\n\nimport {\n detectCompositeReferences,\n generate,\n migrateLatest,\n migrateTenants,\n migrateUp,\n migrateDown,\n migrateRollback,\n migrateStatus,\n pushSchema,\n reviewMigration,\n renderSchemaSource,\n type CompositeQueryRunner,\n type DbConfig,\n type MigrationAdapter,\n} from './index'\nimport type { Dialect } from './snapshot/types'\nimport type { MigrationAdapterFactory } from './cli/config'\nimport type { DriftBehavior } from './migrate/drift'\n\n/**\n * Authoring shape for the db config — every field optional, defaults\n * applied by {@link resolveKickDbConfig}. This is the same shape as the\n * `db` block in `kick.config.ts`, so a config authored with\n * `defineKickDbConfig` drops straight into either place.\n */\nexport interface KickDbConfigInput {\n schemaPath?: string\n migrationsDir?: string\n /** Where `kick db seed` finds seed files. Default `db/seeds`. */\n seedsDir?: string\n dialect?: Dialect\n connectionString?: string\n adapter?: MigrationAdapterFactory\n /**\n * How `migrate` reacts to out-of-band schema (drift): `'error'`\n * (default), `'warn'`, or `'ignore'`. The check is dialect-normalised,\n * so SQLite/MySQL's lossy introspection doesn't false-positive.\n */\n driftCheck?: DriftBehavior\n /** `'snake_case'`: snake_case tables and columns under camelCase keys. Match the client's `casing`. */\n casing?: 'snake_case'\n /** The table migrations are recorded in. Default `kick_migrations`. */\n migrationsTable?: string\n /** Schema- or database-per-tenant: see `kick db migrate latest --tenants`. */\n tenants?: import('./cli/config').TenantsConfig\n /**\n * More migration folders, run with `migrationsDir` as one history ordered by\n * migration id — a package's own migrations, say. `generate` writes to\n * `migrationsDir`.\n */\n migrationsDirs?: string[]\n}\n\n/**\n * Identity helper for type inference — mirrors vite's `defineConfig`.\n * Use it in a standalone `kickjs-db.config.ts` (`export default\n * defineKickDbConfig({ ... })`) or as the value of `kick.config.ts`'s\n * `db` field. Both resolve through {@link resolveKickDbConfig}.\n */\nexport function defineKickDbConfig(cfg: KickDbConfigInput): KickDbConfigInput {\n return cfg\n}\n\n/**\n * Shallow-merge db configs, later wins (vite's `mergeConfig` spirit).\n * Lets a standalone `kickjs-db.config.ts` layer over a project's\n * `kick.config.ts` `db` block, or vice versa.\n */\nexport function mergeKickDbConfig(\n ...configs: (KickDbConfigInput | undefined)[]\n): KickDbConfigInput {\n return Object.assign({}, ...configs.filter(Boolean))\n}\n\n/** Apply defaults to a {@link KickDbConfigInput}, yielding a resolved {@link DbConfig}. */\nexport function resolveKickDbConfig(block: KickDbConfigInput | undefined): DbConfig {\n const db = block ?? {}\n return {\n schemaPath: db.schemaPath ?? 'src/db/schema.ts',\n migrationsDir: db.migrationsDir ?? 'db/migrations',\n seedsDir: db.seedsDir ?? 'db/seeds',\n dialect: db.dialect ?? 'postgres',\n connectionString: db.connectionString ?? process.env.DATABASE_URL,\n adapter: db.adapter,\n driftCheck: db.driftCheck,\n casing: db.casing,\n migrationsTable: db.migrationsTable,\n migrationsDirs: db.migrationsDirs,\n tenants: db.tenants,\n }\n}\n\n/**\n * Resolve a MigrationAdapter from config:\n * 1. config.adapter() — explicit factory wins.\n * 2. config.connectionString — built-in pgAdapter path; dynamically\n * imports `./pg` + `pg` so non-PG workflows don't pull pg.\n */\nasync function resolveAdapter(config: DbConfig): Promise<{\n adapter: MigrationAdapter\n cleanup: () => Promise<void>\n}> {\n if (config.adapter) {\n const adapter = await config.adapter()\n return { adapter, cleanup: async () => adapter.close() }\n }\n if (!config.connectionString) {\n throw new Error(\n 'kickjs-db: no adapter resolved — set db.connectionString (or DATABASE_URL), or supply a db.adapter() factory',\n )\n }\n const dialect = config.dialect ?? 'postgres'\n if (dialect !== 'postgres') {\n throw new Error(\n `kickjs-db: the built-in CLI adapter only supports postgres (dialect=${dialect}); supply a db.adapter() factory for other dialects`,\n )\n }\n // Dynamic import so we don't hard-require pg unless this path runs.\n const [{ pgAdapter }, pg] = await Promise.all([import('./pg'), import('pg')])\n const pool = new pg.default.Pool({ connectionString: config.connectionString })\n const adapter = pgAdapter({ pool, migrationsTable: config.migrationsTable })\n return {\n adapter,\n cleanup: async () => {\n await adapter.close()\n await pool.end()\n },\n }\n}\n\ninterface PgQueryRunnerProbe {\n runner: CompositeQueryRunner\n cleanup: () => Promise<void>\n}\n\n/**\n * Resolve a pg-protocol query runner for the composite-type check at\n * `generate` time. Only fires for the built-in pgAdapter path\n * (dialect=postgres + connection string, no custom adapter factory).\n */\nasync function tryResolvePgQueryRunner(config: DbConfig): Promise<PgQueryRunnerProbe | null> {\n if (config.adapter) return null\n if ((config.dialect ?? 'postgres') !== 'postgres') return null\n if (!config.connectionString) return null\n\n const pg = await import('pg')\n const pool = new pg.default.Pool({ connectionString: config.connectionString })\n return { runner: pool, cleanup: async () => void (await pool.end()) }\n}\n\nfunction printStatusTable(status: Awaited<ReturnType<typeof migrateStatus>>): void {\n if (status.length === 0) {\n console.log('No migrations.')\n return\n }\n console.table(\n status.map((s) => ({\n id: s.id,\n state: s.state,\n batch: s.batch ?? '-',\n reviewed: s.reviewed,\n applied: s.appliedAt ?? '-',\n })),\n )\n}\n\n/** A config source — resolved lazily so each command reads fresh config. */\nexport type DbConfigResolver = () => DbConfig | Promise<DbConfig>\n\n/**\n * Attach the db commands (`generate`, `migrate *`, `introspect`) onto a\n * commander command. `parent` is the command they hang off — the plugin\n * passes a `db` subcommand (so `kick db generate`), the standalone bin\n * passes the root program (so `kickjs-db generate`). `getConfig` supplies\n * the resolved {@link DbConfig} — under kickjs-cli from `ctx.config.db`,\n * standalone from `kickjs-db.config.ts`.\n */\nexport function registerDbCommands(parent: Command, getConfig: DbConfigResolver): void {\n parent\n .command('generate <name>')\n .description('Generate a new migration from schema diff')\n .option(\n '-e, --empty',\n 'Skip schema diff and create an empty migration shell (data migration, seed, freeform SQL)',\n )\n .option(\n '--rename-table <old=new>',\n 'Treat a dropped table as renamed (repeatable)',\n (v: string, all: string[] = []) => [...all, v],\n )\n .option(\n '--rename-column <table.old=new>',\n 'Treat a dropped column as renamed (repeatable)',\n (v: string, all: string[] = []) => [...all, v],\n )\n .option('--no-interactive', \"Don't ask which drops are renames, even in a terminal\")\n .option(\n '--ts',\n 'Write the migration in TypeScript — a migration.ts with up(db) / down(db) — for data changes that need code',\n )\n .action(async (name: string, opts: GenerateFlags) => {\n const cwd = process.cwd()\n const config = await getConfig()\n\n const probe = await tryResolvePgQueryRunner(config)\n const detectCompositeRefs = probe\n ? (enumName: string) => detectCompositeReferences(probe.runner, enumName)\n : undefined\n\n try {\n const renames = parseRenameFlags(opts.renameTable, opts.renameColumn)\n // Asked only in a terminal; in CI, name renames with the flags.\n const askRenames =\n opts.interactive !== false && process.stdin.isTTY ? askRenamesInTerminal : undefined\n const result = await generate({\n name,\n config,\n cwd,\n empty: opts.empty,\n typescript: opts.ts,\n detectCompositeRefs,\n renames,\n askRenames,\n onPossibleRename: askRenames\n ? undefined\n : (drop) =>\n console.warn(\n `Warning: ${drop.what} will be dropped. If it was renamed, generate again with ` +\n `${drop.flag} — the data goes with a drop.`,\n ),\n })\n if (result.status === 'no-changes') {\n console.log('No schema changes detected.')\n return\n }\n if (result.empty) {\n console.log(\n opts.ts\n ? `Created migration ${result.migrationDir} (write up() and down() in migration.ts).`\n : `Created empty migration ${result.migrationDir} (author up.sql + down.sql).`,\n )\n return\n }\n const plural = result.changeCount === 1 ? '' : 's'\n console.log(\n `Created migration ${result.migrationDir} (${result.changeCount} change${plural}).`,\n )\n } finally {\n await probe?.cleanup()\n }\n })\n\n parent\n .command('check')\n .description(\n 'Fail if the schema has changes no migration covers, or a migration is unreviewed or edited (no database needed — for CI)',\n )\n .action(async () => {\n const config = await getConfig()\n const r = await checkMigrations({ config, cwd: process.cwd() })\n if (r.unmigratedChanges > 0) {\n const plural = r.unmigratedChanges === 1 ? '' : 's'\n console.error(\n `The schema has ${r.unmigratedChanges} change${plural} no migration covers — run \\`kick db generate <name>\\`.`,\n )\n }\n for (const id of r.unreviewed) {\n console.error(`${id} is not reviewed — read it, then \\`kick db migrate review ${id}\\`.`)\n }\n for (const id of r.modified) {\n console.error(\n `${id} was edited after it was reviewed — review it again, or revert the edit.`,\n )\n }\n if (r.ok) console.log('Migrations are in step with the schema.')\n else process.exitCode = 1\n })\n\n parent\n .command('push')\n .description(\n 'Make the database match the schema with no migration file — for prototyping; refused on a database with migrations applied',\n )\n .option(\n '--rename-table <old=new>',\n 'Treat a dropped table as renamed (repeatable)',\n (v: string, all: string[] = []) => [...all, v],\n )\n .option(\n '--rename-column <table.old=new>',\n 'Treat a dropped column as renamed (repeatable)',\n (v: string, all: string[] = []) => [...all, v],\n )\n .option('--no-interactive', \"Don't ask about renames or data loss, even in a terminal\")\n .option('--accept-data-loss', 'Apply changes that drop tables, columns or enum values')\n .action(async (opts: Omit<GenerateFlags, 'empty' | 'ts'> & { acceptDataLoss?: boolean }) => {\n const config = await getConfig()\n const interactive = opts.interactive !== false && process.stdin.isTTY\n const schema = await loadModule(path.resolve(process.cwd(), config.schemaPath), {\n fresh: true,\n })\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await pushSchema({\n adapter,\n schema,\n casing: config.casing,\n renames: parseRenameFlags(opts.renameTable, opts.renameColumn),\n askRenames: interactive ? askRenamesInTerminal : undefined,\n confirmDataLoss: opts.acceptDataLoss\n ? async () => true\n : interactive\n ? (losses) =>\n confirmInTerminal(\n `This loses data:\\n${losses.map((l) => ` - ${l}`).join('\\n')}\\nApply it?`,\n )\n : undefined,\n })\n const plural = r.changeCount === 1 ? '' : 's'\n console.log(\n r.status === 'no-changes'\n ? 'The database already matches the schema.'\n : `Pushed ${r.changeCount} change${plural}.`,\n )\n } finally {\n await cleanup()\n }\n })\n\n parent\n .command('seed [names...]')\n .description(\n 'Run the seed files in db/seeds (or only those named), in name order — no migration tracking, so make them safe to re-run',\n )\n .action(async (names: string[]) => {\n const config = await getConfig()\n const dir = path.resolve(process.cwd(), config.seedsDir ?? 'db/seeds')\n try {\n const { ran } = await runSeeds({ dir, names })\n console.log(\n ran.length === 0 ? `No seeds in ${dir}.` : `Ran ${ran.length} seed(s): ${ran.join(', ')}`,\n )\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err))\n process.exitCode = 1\n }\n // A seed imports the app's own client, whose pool would keep the\n // command alive; it's done, so exit once output is flushed.\n process.stderr.write('', () =>\n process.stdout.write('', () => process.exit(process.exitCode ?? 0)),\n )\n })\n\n // ── migrate runner subcommands ─────────────────────────────────────────\n const migrate = parent.command('migrate').description('Migration runner subcommands')\n\n migrate\n .command('latest')\n .description('Apply all pending migrations in a new batch')\n .option(\n '--confirm-enum-drop',\n 'Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply',\n false,\n )\n .option('--tenants', \"Migrate every tenant's schema or database (db.tenants in kick.config)\")\n .action(async (opts: { confirmEnumDrop?: boolean; tenants?: boolean }) => {\n const config = await getConfig()\n if (opts.tenants) {\n if (!config.tenants) {\n throw new Error(\n 'kick db migrate latest --tenants needs a `tenants: { list, adapter }` db config',\n )\n }\n const r = await migrateTenants({\n tenants: config.tenants.list,\n adapterFor: config.tenants.adapter,\n concurrency: config.tenants.concurrency,\n migrationsDir: runDirs(config),\n driftCheck: config.driftCheck,\n confirmEnumDrop: opts.confirmEnumDrop,\n onTenant: (t) =>\n console.log(\n t.error\n ? `✗ ${t.tenant}: ${t.error instanceof Error ? t.error.message : String(t.error)}`\n : `✓ ${t.tenant}: ${t.summary!.applied.length === 0 ? 'up to date' : t.summary!.applied.join(', ')}`,\n ),\n })\n console.log(`${r.results.length - r.failed.length} migrated, ${r.failed.length} failed`)\n if (r.failed.length > 0) process.exitCode = 1\n return\n }\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateLatest({\n adapter,\n migrationsDir: runDirs(config),\n driftCheck: config.driftCheck,\n confirmEnumDrop: opts.confirmEnumDrop,\n })\n console.log(\n r.applied.length === 0\n ? 'No pending migrations.'\n : `Applied batch ${r.batch}: ${r.applied.join(', ')}`,\n )\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('up')\n .description('Apply the next single pending migration, or every one up to --to')\n .option(\n '--to <migration>',\n 'Apply pending migrations up to and including this one (id or name)',\n )\n .option(\n '--confirm-enum-drop',\n 'Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply',\n false,\n )\n .action(async (opts: { confirmEnumDrop?: boolean; to?: string }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateUp({\n adapter,\n migrationsDir: runDirs(config),\n driftCheck: config.driftCheck,\n confirmEnumDrop: opts.confirmEnumDrop,\n to: opts.to,\n })\n console.log(\n r.applied.length === 0\n ? 'No pending migrations.'\n : `Applied ${r.applied.join(', ')} (batch ${r.batch})`,\n )\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('down')\n .description('Reverse the most recent applied migration, or every one after --to')\n .option(\n '--to <migration>',\n 'Reverse every migration applied after this one (id or name), which stays',\n )\n .action(async (opts: { to?: string }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateDown({\n adapter,\n migrationsDir: runDirs(config),\n driftCheck: config.driftCheck,\n to: opts.to,\n })\n console.log(\n r.reversedAll.length > 0\n ? `Reversed ${r.reversedAll.join(', ')}.`\n : 'Nothing to reverse.',\n )\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('rollback')\n .description('Reverse the entire last batch as a single unit, or with --all every migration')\n .option('--all', 'Reverse every applied migration, newest first')\n .action(async (opts: { all?: boolean }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateRollback({\n adapter,\n migrationsDir: runDirs(config),\n driftCheck: config.driftCheck,\n all: opts.all,\n })\n console.log(\n r.reversed.length === 0\n ? 'Nothing to roll back.'\n : opts.all\n ? `Rolled back every migration: ${r.reversed.join(', ')}`\n : `Rolled back batch ${r.batch}: ${r.reversed.join(', ')}`,\n )\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('status')\n .description('Print applied + pending migrations')\n .action(async () => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n printStatusTable(await migrateStatus({ adapter, migrationsDir: runDirs(config) }))\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('unlock')\n .description(\n 'Release the migration lock left by a run that was killed mid-migration (make sure none is running)',\n )\n .action(async () => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n await adapter.releaseLock()\n console.log('Released the migration lock.')\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('review <id>')\n .description('Mark a migration reviewed (flips meta.json; migrates legacy -- REVIEWED markers)')\n .action(async (id: string) => {\n // No adapter/DB needed — review only touches the migration files.\n const config = await getConfig()\n const r = await reviewMigration(folderOf(config, id), id)\n console.log(\n r.alreadyReviewed\n ? `${r.id} was already reviewed — recorded its current contents as reviewed.`\n : `Reviewed ${r.id} — it can now be applied.`,\n )\n })\n\n // ── kick db introspect ─────────────────────────────────────────────────\n parent\n .command('introspect')\n .description('Generate a TypeScript schema file from a live database')\n .option('--out <path>', 'Output file (defaults to db.schemaPath from config)')\n .option('--json', 'Print the raw SchemaSnapshot JSON to stdout instead of writing TS source')\n .action(async (opts: { out?: string; json?: boolean }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const snapshot = await adapter.introspect()\n if (opts.json) {\n console.log(JSON.stringify(snapshot, null, 2))\n return\n }\n const out = opts.out ?? config.schemaPath\n // With casing, the database's snake_case names become camelCase keys.\n const source = config.casing === 'snake_case' ? removeCasing(snapshot) : snapshot\n await writeFile(out, renderSchemaSource(source), 'utf8')\n const n = Object.keys(snapshot.tables).length\n console.log(`Wrote ${out} (${n} table${n === 1 ? '' : 's'}).`)\n } finally {\n await cleanup()\n }\n })\n}\n\n/**\n * Read the `db` block off a host CLI config object. The kit types\n * `ctx.config` as `unknown`; the db block is structurally a\n * {@link KickDbConfigInput}.\n */\nfunction dbBlockOf(config: unknown): KickDbConfigInput | undefined {\n return (config as { db?: KickDbConfigInput } | null)?.db\n}\n\n/**\n * The database CLI plugin. Mount it in `kick.config.ts`:\n *\n * ```ts\n * import { defineConfig } from '@forinda/kickjs-cli'\n * import { dbCliPlugin } from '@forinda/kickjs-db/cli'\n *\n * export default defineConfig({ plugins: [dbCliPlugin] })\n * ```\n *\n * `kick db generate|migrate|introspect` then read config from the\n * `db` block of the same `kick.config.ts`.\n */\nexport const dbCliPlugin: KickCliPlugin = defineCliPlugin({\n name: 'kick/db',\n register(program, ctx) {\n const db = program.command('db').description('Database commands (kickjs-db)')\n registerDbCommands(db, () => resolveKickDbConfig(dbBlockOf(ctx.config)))\n },\n // Mounting the plugin also wires `.kickjs/types/kick__db.d.ts` generation\n // into `kick typegen` — db commands + db types from one opt-in plugin.\n typegens: [kickDbTypegen()],\n})\n"],"mappings":";;;;;;;;;;sjBAsBA,MAAM,qBAAuB,CAC3B,mBACA,yBACA,eACF,EAEa,mBAAmC,CAC9C,GAAI,UACJ,OAAQ,CAAC,mBAAoB,uBAAuB,EACpD,MAAM,SAAS,IAAiE,CAM9E,IAAM,UAAY,cAAc,IAAI,IAAK,IAAI,QAAQ,IAAI,UAAU,EACnE,GAAI,CAAC,UAAW,OAAO,KAIvB,IAAM,SAAW,KAAK,QAAQ,IAAI,IAAK,eAAe,EAKtD,MAAO,CACL,mGACA,oCANU,MAAM,KAAK,SAAS,SAAU,SAAS,CAAC,CAAC,CAClD,QAAQ,QAAS,EAAE,CAAC,CACpB,QAAQ,WAAY,EAIiB,EAAE,GACxC,GACA,mBACA,sEACA,IACA,GACA,wCACA,+BACA,qCACA,MACA,GACA,wCACA,sDACA,MACA,GACF,CAAC,CAAC,KAAK;CAAI,CACb,CACF,GAEA,SAAS,cAAc,IAAa,eAAwC,CAI1E,GAAI,eAAgB,CAClB,IAAM,IAAM,KAAK,QAAQ,IAAK,cAAc,EAC5C,GAAI,WAAW,GAAG,EAAG,OAAO,IAC5B,IAAM,IAAM,KAAK,KAAK,IAAK,UAAU,EACrC,GAAI,WAAW,GAAG,EAAG,OAAO,GAC9B,CACA,IAAK,IAAM,aAAa,qBAAsB,CAC5C,IAAM,IAAM,KAAK,QAAQ,IAAK,SAAS,EACvC,G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C,CAC5F,OAAO,KAAO,OAA2C,CACxD,IAAM,OAAS,MAAM,UAAU,EACzB,CAAE,QAAS,SAAY,MAAM,eAAe,MAAM,EACxD,GAAI,CACF,IAAM,SAAW,MAAM,QAAQ,WAAW,EAC1C,GAAI,KAAK,KAAM,CACb,QAAQ,IAAI,KAAK,UAAU,SAAU,KAAM,CAAC,CAAC,EAC7C,MACF,CACA,IAAM,IAAM,KAAK,KAAO,OAAO,WAEzB,OAAS,OAAO,SAAW,aAAe,aAAa,QAAQ,EAAI,SACzE,MAAM,UAAU,IAAK,mBAAmB,MAAM,EAAG,MAAM,EACvD,IAAM,EAAI,OAAO,KAAK,SAAS,MAAM,CAAC,CAAC,OACvC,QAAQ,IAAI,SAAS,IAAI,IAAI,EAAE,QAAQ,IAAM,EAAI,GAAK,IAAI,GAAG,CAC/D,QAAU,CACR,MAAM,QAAQ,CAChB,CACF,CAAC,CACL,CAOA,SAAS,UAAU,OAAgD,CACjE,OAAQ,QAA8C,EACxD,CAeA,MAAa,YAA6B,gBAAgB,CACxD,KAAM,UACN,SAAS,QAAS,IAAK,CAErB,mBADW,QAAQ,QAAQ,IAAI,CAAC,CAAC,YAAY,+BACzB,MAAS,oBAAoB,UAAU,IAAI,MAAM,CAAC,CAAC,CACzE,EAGA,SAAU,CAAC,cAAc,CAAC,CAC5B,CAAC"}
|
|
1
|
+
{"version":3,"file":"cli.mjs","names":[],"sources":["../src/cli-typegen.ts","../src/cli/renames.ts","../src/cli/push-target.ts","../src/cli.ts"],"sourcesContent":["/**\n * `kick/db` typegen — reads the adopter's schema (`src/db/schema.ts` or a\n * `src/db/schema/` barrel) and emits `.kickjs/types/kick__db.d.ts` with\n * three augmentations:\n *\n * 1. global `KickDbSchema = SchemaToTypes<typeof appSchema>` — column\n * shapes computed at type-check time, no runtime cost.\n * 2. `KickDbRegister.db = KickDbClient<KickDbSchema>` — bare\n * `KickDbClient` widens automatically.\n * 3. `KickDbRelationsRegister.db = SchemaToRelationsRegister<typeof\n * appSchema>` — typed `with` keys for `db.query.X.findMany`.\n *\n * Shipped on {@link dbCliPlugin} (`typegens`) so mounting the db plugin\n * brings both the `kick db` commands and this type generation. Typed\n * against the `@forinda/kickjs-cli-kit` `CliTypegen` contract so it needs\n * no kickjs-cli internals — it only reads `ctx.cwd`.\n */\nimport path from 'node:path'\nimport { existsSync } from 'node:fs'\n\nimport type { CliTypegen } from '@forinda/kickjs-cli-kit'\n\nconst DEFAULT_SCHEMA_PATHS = [\n 'src/db/schema.ts',\n 'src/db/schema/index.ts',\n 'src/db/schema',\n] as const\n\nexport const kickDbTypegen = (): CliTypegen => ({\n id: 'kick/db',\n inputs: ['src/db/schema.ts', 'src/db/schema/**/*.ts'],\n async generate(ctx: { cwd: string; config?: { db?: { schemaPath?: string } } }) {\n // Parity with `kick db generate` (cli/config.ts resolveDbConfig):\n // an adopter-configured `db.schemaPath` must drive BOTH the\n // migration engine and this augmentation — previously only the\n // default candidates were probed, so a custom path produced\n // working migrations but a silently untyped client.\n const schemaAbs = resolveSchema(ctx.cwd, ctx.config?.db?.schemaPath)\n if (!schemaAbs) return null\n\n // Strip the `.ts` extension and any trailing `/index` so the import\n // specifier stays stable across single-file vs barrel-folder layouts.\n const typesDir = path.resolve(ctx.cwd, '.kickjs/types')\n const rel = posix(path.relative(typesDir, schemaAbs))\n .replace(/\\.ts$/, '')\n .replace(/\\/index$/, '')\n\n return [\n `import type { SchemaToTypes, SchemaToRelationsRegister, KickDbClient } from '@forinda/kickjs-db'`,\n `import type * as appSchema from '${rel}'`,\n ``,\n `declare global {`,\n ` interface KickDbSchema extends SchemaToTypes<typeof appSchema> {}`,\n `}`,\n ``,\n `declare module '@forinda/kickjs-db' {`,\n ` interface KickDbRegister {`,\n ` db: KickDbClient<KickDbSchema>`,\n ` }`,\n ``,\n ` interface KickDbRelationsRegister {`,\n ` db: SchemaToRelationsRegister<typeof appSchema>`,\n ` }`,\n `}`,\n ].join('\\n')\n },\n})\n\nfunction resolveSchema(cwd: string, configuredPath?: string): string | null {\n // kick.config `db.schemaPath` wins when the file exists; a configured-\n // but-missing path falls through to the candidates rather than\n // emitting an augmentation with a broken import specifier.\n if (configuredPath) {\n const abs = path.resolve(cwd, configuredPath)\n if (existsSync(abs)) return abs\n const idx = path.join(abs, 'index.ts')\n if (existsSync(idx)) return idx\n }\n for (const candidate of DEFAULT_SCHEMA_PATHS) {\n const abs = path.resolve(cwd, candidate)\n if (candidate.endsWith('.ts')) {\n if (existsSync(abs)) return abs\n } else {\n const idx = path.join(abs, 'index.ts')\n if (existsSync(idx)) return idx\n }\n }\n return null\n}\n\nfunction posix(p: string): string {\n return p.replace(/\\\\/g, '/')\n}\n","import { createInterface } from 'node:readline/promises'\nimport type { RenameCandidates, RenameHints } from '../diff/engine'\n\n/**\n * Parse `--rename-table old=new` / `--rename-column table.old=new` values.\n * A column's table is everything before its last dot, so a schema-qualified\n * table (`billing.invoices.total=amount`) works.\n */\nexport function parseRenameFlags(tables: string[] = [], columns: string[] = []): RenameHints {\n const pairs = (values: string[], flag: string) =>\n values.map((v) => {\n const eq = v.indexOf('=')\n if (eq <= 0 || eq === v.length - 1) {\n throw new Error(`kickjs-db: ${flag} expects old=new, got '${v}'`)\n }\n return [v.slice(0, eq), v.slice(eq + 1)] as const\n })\n for (const [from] of pairs(columns, '--rename-column')) {\n if (!from.includes('.')) {\n throw new Error(`kickjs-db: --rename-column expects table.old=new, got '${from}'`)\n }\n }\n return {\n tables: Object.fromEntries(pairs(tables, '--rename-table')),\n columns: Object.fromEntries(pairs(columns, '--rename-column')),\n }\n}\n\n/**\n * Ask in the terminal which drops are renames. Each candidate lists what it\n * could have become; the default (Enter) is to drop it — nothing is renamed\n * that someone didn't pick.\n */\nexport async function askRenamesInTerminal(\n candidates: RenameCandidates,\n io: { input: NodeJS.ReadableStream; output: NodeJS.WritableStream } = {\n input: process.stdin,\n output: process.stdout,\n },\n): Promise<RenameHints> {\n const rl = createInterface({ input: io.input, output: io.output })\n const hints: Required<RenameHints> = { tables: {}, columns: {} }\n try {\n const ask = async (what: string, options: string[]): Promise<string | undefined> => {\n const free = options.filter(\n (o) =>\n !Object.values(hints.tables).includes(o) && !Object.values(hints.columns).includes(o),\n )\n if (free.length === 0) return undefined\n const list = free.map((o, i) => ` ${i + 1}) renamed to ${o}`).join('\\n')\n for (;;) {\n const answer = (\n await rl.question(`${what} is gone. Was it renamed?\\n 0) no, drop it\\n${list}\\n> `)\n ).trim()\n const n = answer === '' ? 0 : Number(answer)\n if (Number.isInteger(n) && n >= 0 && n <= free.length)\n return n === 0 ? undefined : free[n - 1]\n }\n }\n for (const c of candidates.tables) {\n const to = await ask(`Table ${c.from}`, c.to)\n if (to) hints.tables[c.from] = to\n }\n for (const c of candidates.columns) {\n const to = await ask(`Column ${c.table}.${c.from}`, c.to)\n if (to) hints.columns[`${c.table}.${c.from}`] = to\n }\n } finally {\n rl.close()\n }\n return hints\n}\n\n/** Ask a yes/no question in the terminal; anything but y/yes is no. */\nexport async function confirmInTerminal(\n question: string,\n io: { input: NodeJS.ReadableStream; output: NodeJS.WritableStream } = {\n input: process.stdin,\n output: process.stdout,\n },\n): Promise<boolean> {\n const rl = createInterface({ input: io.input, output: io.output })\n try {\n return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim())\n } finally {\n rl.close()\n }\n}\n","/**\n * The host a connection string points at, when it is not this machine or a\n * neighbouring container — or `undefined` for a local target or one push\n * can't see (a `db.adapter()` factory with no connection string). `kick db\n * push` asks before changing a remote database.\n */\nexport function remoteHost(connectionString: string | undefined): string | undefined {\n // Parsed by hand: a libpq host list (`h1:5432,h2:5433`) isn't a valid WHATWG\n // URL, and that's exactly a case to catch.\n const match = /^[a-z][\\w+.-]*:\\/\\/(?:[^@/?#]*@)?([^/?#]*)[^?#]*(?:\\?([^#]*))?/i.exec(\n connectionString ?? '',\n )\n if (!match) return undefined // not a URL (a key=value DSN, a file path): don't guess\n // Postgres takes `?host=` over the URL's own host, and a URL may list several\n // hosts. Check every host the driver may connect to.\n const hostParam = new URLSearchParams(match[2] ?? '').get('host')\n const hosts = (hostParam ?? decodeURIComponent(match[1] ?? ''))\n .split(',')\n .map((h) => stripPort(h.trim()).toLowerCase())\n .filter((h) => h && !h.startsWith('/')) // empty, or a Unix socket directory\n return hosts.find((host) => !isLocal(host))\n}\n\n/** `[::1]:5432` → `::1`, `db:5432` → `db`, `db` → `db`. */\nfunction stripPort(entry: string): string {\n if (entry.startsWith('[')) return entry.slice(1, entry.indexOf(']'))\n return entry.replace(/:\\d+$/, '')\n}\n\nfunction isLocal(host: string): boolean {\n return (\n host === 'localhost' ||\n host === '::1' ||\n host === '0.0.0.0' ||\n host.startsWith('127.') ||\n host.endsWith('.localhost') ||\n host.endsWith('.local') ||\n !host.includes('.') // a compose service name: `db`, `postgres`\n )\n}\n","/**\n * `@forinda/kickjs-db/cli` — the database command tree as a mountable CLI\n * plugin + the building blocks for a standalone `kickjs-db` bin.\n *\n * Two ways to use it:\n * 1. **As a kickjs-cli plugin** — add `dbCliPlugin` to `kick.config.ts`\n * `plugins: []`. The host CLI calls `register(program, ctx)` and the\n * db config is read from `ctx.config.db` (already loaded — no re-parse).\n * 2. **Standalone** — the `kickjs-db` bin builds a commander program,\n * resolves config from `kickjs-db.config.ts` (or a `kick.config.ts`\n * `db` block), and calls {@link registerDbCommands} directly. Lets\n * `npx kickjs-db migrate latest` work without installing kickjs-cli.\n *\n * @module @forinda/kickjs-db/cli\n */\n\nimport { existsSync } from 'node:fs'\nimport { writeFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport type { Command } from 'commander'\n\nimport { defineCliPlugin, type KickCliPlugin } from '@forinda/kickjs-cli-kit'\nimport { kickDbTypegen } from './cli-typegen'\nimport { checkMigrations } from './cli/check'\nimport { runSeeds } from './cli/seed'\nimport { removeCasing } from './snapshot/casing'\nimport { askRenamesInTerminal, confirmInTerminal, parseRenameFlags } from './cli/renames'\nimport { remoteHost } from './cli/push-target'\nimport { loadModule } from './cli/load-module'\n\n/** Every folder the runner reads: `migrationsDir`, then `migrationsDirs`. */\nfunction runDirs(config: DbConfig): string | string[] {\n return config.migrationsDirs?.length\n ? [config.migrationsDir, ...config.migrationsDirs]\n : config.migrationsDir\n}\n\n/** The folder holding a migration, among every folder the runner reads. */\nfunction folderOf(config: DbConfig, id: string): string {\n const dirs = [config.migrationsDir, ...(config.migrationsDirs ?? [])]\n return dirs.find((d) => existsSync(path.join(d, id))) ?? config.migrationsDir\n}\n\ninterface GenerateFlags {\n empty?: boolean\n ts?: boolean\n renameTable?: string[]\n renameColumn?: string[]\n interactive?: boolean\n}\n\nexport { kickDbTypegen } from './cli-typegen'\n\nimport {\n detectCompositeReferences,\n generate,\n migrateLatest,\n migrateTenants,\n migrateUp,\n migrateDown,\n migrateRollback,\n migrateStatus,\n pushSchema,\n reviewMigration,\n renderSchemaSource,\n type CompositeQueryRunner,\n type DbConfig,\n type MigrationAdapter,\n} from './index'\nimport type { Dialect } from './snapshot/types'\nimport type { MigrationAdapterFactory } from './cli/config'\nimport type { DriftBehavior } from './migrate/drift'\n\n/**\n * Authoring shape for the db config — every field optional, defaults\n * applied by {@link resolveKickDbConfig}. This is the same shape as the\n * `db` block in `kick.config.ts`, so a config authored with\n * `defineKickDbConfig` drops straight into either place.\n */\nexport interface KickDbConfigInput {\n schemaPath?: string\n migrationsDir?: string\n /** Where `kick db seed` finds seed files. Default `db/seeds`. */\n seedsDir?: string\n dialect?: Dialect\n connectionString?: string\n adapter?: MigrationAdapterFactory\n /**\n * How `migrate` reacts to out-of-band schema (drift): `'error'`\n * (default), `'warn'`, or `'ignore'`. The check is dialect-normalised,\n * so SQLite/MySQL's lossy introspection doesn't false-positive.\n */\n driftCheck?: DriftBehavior\n /** `'snake_case'`: snake_case tables and columns under camelCase keys. Match the client's `casing`. */\n casing?: 'snake_case'\n /** The table migrations are recorded in. Default `kick_migrations`. */\n migrationsTable?: string\n /** Schema- or database-per-tenant: see `kick db migrate latest --tenants`. */\n tenants?: import('./cli/config').TenantsConfig\n /**\n * More migration folders, run with `migrationsDir` as one history ordered by\n * migration id — a package's own migrations, say. `generate` writes to\n * `migrationsDir`.\n */\n migrationsDirs?: string[]\n}\n\n/**\n * Identity helper for type inference — mirrors vite's `defineConfig`.\n * Use it in a standalone `kickjs-db.config.ts` (`export default\n * defineKickDbConfig({ ... })`) or as the value of `kick.config.ts`'s\n * `db` field. Both resolve through {@link resolveKickDbConfig}.\n */\nexport function defineKickDbConfig(cfg: KickDbConfigInput): KickDbConfigInput {\n return cfg\n}\n\n/**\n * Shallow-merge db configs, later wins (vite's `mergeConfig` spirit).\n * Lets a standalone `kickjs-db.config.ts` layer over a project's\n * `kick.config.ts` `db` block, or vice versa.\n */\nexport function mergeKickDbConfig(\n ...configs: (KickDbConfigInput | undefined)[]\n): KickDbConfigInput {\n return Object.assign({}, ...configs.filter(Boolean))\n}\n\n/** Apply defaults to a {@link KickDbConfigInput}, yielding a resolved {@link DbConfig}. */\nexport function resolveKickDbConfig(block: KickDbConfigInput | undefined): DbConfig {\n const db = block ?? {}\n return {\n schemaPath: db.schemaPath ?? 'src/db/schema.ts',\n migrationsDir: db.migrationsDir ?? 'db/migrations',\n seedsDir: db.seedsDir ?? 'db/seeds',\n dialect: db.dialect ?? 'postgres',\n connectionString: db.connectionString ?? process.env.DATABASE_URL,\n adapter: db.adapter,\n driftCheck: db.driftCheck,\n casing: db.casing,\n migrationsTable: db.migrationsTable,\n migrationsDirs: db.migrationsDirs,\n tenants: db.tenants,\n }\n}\n\n/**\n * Resolve a MigrationAdapter from config:\n * 1. config.adapter() — explicit factory wins.\n * 2. config.connectionString — built-in pgAdapter path; dynamically\n * imports `./pg` + `pg` so non-PG workflows don't pull pg.\n */\nasync function resolveAdapter(config: DbConfig): Promise<{\n adapter: MigrationAdapter\n cleanup: () => Promise<void>\n}> {\n if (config.adapter) {\n const adapter = await config.adapter()\n return { adapter, cleanup: async () => adapter.close() }\n }\n if (!config.connectionString) {\n throw new Error(\n 'kickjs-db: no adapter resolved — set db.connectionString (or DATABASE_URL), or supply a db.adapter() factory',\n )\n }\n const dialect = config.dialect ?? 'postgres'\n if (dialect !== 'postgres') {\n throw new Error(\n `kickjs-db: the built-in CLI adapter only supports postgres (dialect=${dialect}); supply a db.adapter() factory for other dialects`,\n )\n }\n // Dynamic import so we don't hard-require pg unless this path runs.\n const [{ pgAdapter }, pg] = await Promise.all([import('./pg'), import('pg')])\n const pool = new pg.default.Pool({ connectionString: config.connectionString })\n const adapter = pgAdapter({ pool, migrationsTable: config.migrationsTable })\n return {\n adapter,\n cleanup: async () => {\n await adapter.close()\n await pool.end()\n },\n }\n}\n\ninterface PgQueryRunnerProbe {\n runner: CompositeQueryRunner\n cleanup: () => Promise<void>\n}\n\n/**\n * Resolve a pg-protocol query runner for the composite-type check at\n * `generate` time. Only fires for the built-in pgAdapter path\n * (dialect=postgres + connection string, no custom adapter factory).\n */\nasync function tryResolvePgQueryRunner(config: DbConfig): Promise<PgQueryRunnerProbe | null> {\n if (config.adapter) return null\n if ((config.dialect ?? 'postgres') !== 'postgres') return null\n if (!config.connectionString) return null\n\n const pg = await import('pg')\n const pool = new pg.default.Pool({ connectionString: config.connectionString })\n return { runner: pool, cleanup: async () => void (await pool.end()) }\n}\n\nfunction printStatusTable(status: Awaited<ReturnType<typeof migrateStatus>>): void {\n if (status.length === 0) {\n console.log('No migrations.')\n return\n }\n console.table(\n status.map((s) => ({\n id: s.id,\n state: s.state,\n batch: s.batch ?? '-',\n reviewed: s.reviewed,\n applied: s.appliedAt ?? '-',\n })),\n )\n}\n\n/** A config source — resolved lazily so each command reads fresh config. */\nexport type DbConfigResolver = () => DbConfig | Promise<DbConfig>\n\n/**\n * Attach the db commands (`generate`, `migrate *`, `introspect`) onto a\n * commander command. `parent` is the command they hang off — the plugin\n * passes a `db` subcommand (so `kick db generate`), the standalone bin\n * passes the root program (so `kickjs-db generate`). `getConfig` supplies\n * the resolved {@link DbConfig} — under kickjs-cli from `ctx.config.db`,\n * standalone from `kickjs-db.config.ts`.\n */\nexport function registerDbCommands(parent: Command, getConfig: DbConfigResolver): void {\n parent\n .command('generate <name>')\n .description('Generate a new migration from schema diff')\n .option(\n '-e, --empty',\n 'Skip schema diff and create an empty migration shell (data migration, seed, freeform SQL)',\n )\n .option(\n '--rename-table <old=new>',\n 'Treat a dropped table as renamed (repeatable)',\n (v: string, all: string[] = []) => [...all, v],\n )\n .option(\n '--rename-column <table.old=new>',\n 'Treat a dropped column as renamed (repeatable)',\n (v: string, all: string[] = []) => [...all, v],\n )\n .option('--no-interactive', \"Don't ask which drops are renames, even in a terminal\")\n .option(\n '--ts',\n 'Write the migration in TypeScript — a migration.ts with up(db) / down(db) — for data changes that need code',\n )\n .action(async (name: string, opts: GenerateFlags) => {\n const cwd = process.cwd()\n const config = await getConfig()\n\n const probe = await tryResolvePgQueryRunner(config)\n const detectCompositeRefs = probe\n ? (enumName: string) => detectCompositeReferences(probe.runner, enumName)\n : undefined\n\n try {\n const renames = parseRenameFlags(opts.renameTable, opts.renameColumn)\n // Asked only in a terminal; in CI, name renames with the flags.\n const askRenames =\n opts.interactive !== false && process.stdin.isTTY ? askRenamesInTerminal : undefined\n const result = await generate({\n name,\n config,\n cwd,\n empty: opts.empty,\n typescript: opts.ts,\n detectCompositeRefs,\n renames,\n askRenames,\n onPossibleRename: askRenames\n ? undefined\n : (drop) =>\n console.warn(\n `Warning: ${drop.what} will be dropped. If it was renamed, generate again with ` +\n `${drop.flag} — the data goes with a drop.`,\n ),\n })\n if (result.status === 'no-changes') {\n console.log('No schema changes detected.')\n return\n }\n if (result.empty) {\n console.log(\n opts.ts\n ? `Created migration ${result.migrationDir} (write up() and down() in migration.ts).`\n : `Created empty migration ${result.migrationDir} (author up.sql + down.sql).`,\n )\n return\n }\n const plural = result.changeCount === 1 ? '' : 's'\n console.log(\n `Created migration ${result.migrationDir} (${result.changeCount} change${plural}).`,\n )\n } finally {\n await probe?.cleanup()\n }\n })\n\n parent\n .command('check')\n .description(\n 'Fail if the schema has changes no migration covers, or a migration is unreviewed or edited (no database needed — for CI)',\n )\n .action(async () => {\n const config = await getConfig()\n const r = await checkMigrations({ config, cwd: process.cwd() })\n if (r.unmigratedChanges > 0) {\n const plural = r.unmigratedChanges === 1 ? '' : 's'\n console.error(\n `The schema has ${r.unmigratedChanges} change${plural} no migration covers — run \\`kick db generate <name>\\`.`,\n )\n }\n for (const id of r.unreviewed) {\n console.error(`${id} is not reviewed — read it, then \\`kick db migrate review ${id}\\`.`)\n }\n for (const id of r.modified) {\n console.error(\n `${id} was edited after it was reviewed — review it again, or revert the edit.`,\n )\n }\n if (r.ok) console.log('Migrations are in step with the schema.')\n else process.exitCode = 1\n })\n\n parent\n .command('push')\n .description(\n 'Make the database match the schema with no migration file — for prototyping; refused on a database with migrations applied',\n )\n .option(\n '--rename-table <old=new>',\n 'Treat a dropped table as renamed (repeatable)',\n (v: string, all: string[] = []) => [...all, v],\n )\n .option(\n '--rename-column <table.old=new>',\n 'Treat a dropped column as renamed (repeatable)',\n (v: string, all: string[] = []) => [...all, v],\n )\n .option('--no-interactive', \"Don't ask about renames or data loss, even in a terminal\")\n .option('--accept-data-loss', 'Apply changes that drop tables, columns or enum values')\n .option('-y, --yes', 'Push to a remote database without asking')\n .action(\n async (\n opts: Omit<GenerateFlags, 'empty' | 'ts'> & { acceptDataLoss?: boolean; yes?: boolean },\n ) => {\n const config = await getConfig()\n const interactive = opts.interactive !== false && process.stdin.isTTY\n // Push is for a prototyping database. A remote host is a hint it isn't one\n // (NODE_ENV is often unset in a shell, so it can't be the only guard).\n const remote = remoteHost(config.connectionString)\n if (remote && !opts.yes) {\n const ok = interactive\n ? await confirmInTerminal(\n `Push changes the database at ${remote} without a migration file. Continue?`,\n )\n : false\n if (!ok) {\n throw new Error(\n `kickjs-db: refusing to push to ${remote} — push is for a local prototyping database. Pass --yes if this is one.`,\n )\n }\n }\n const schema = await loadModule(path.resolve(process.cwd(), config.schemaPath), {\n fresh: true,\n })\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await pushSchema({\n adapter,\n schema,\n casing: config.casing,\n renames: parseRenameFlags(opts.renameTable, opts.renameColumn),\n askRenames: interactive ? askRenamesInTerminal : undefined,\n confirmDataLoss: opts.acceptDataLoss\n ? async () => true\n : interactive\n ? (losses) =>\n confirmInTerminal(\n `This loses data:\\n${losses.map((l) => ` - ${l}`).join('\\n')}\\nApply it?`,\n )\n : undefined,\n })\n const plural = r.changeCount === 1 ? '' : 's'\n console.log(\n r.status === 'no-changes'\n ? 'The database already matches the schema.'\n : `Pushed ${r.changeCount} change${plural}.`,\n )\n } finally {\n await cleanup()\n }\n },\n )\n\n parent\n .command('seed [names...]')\n .description(\n 'Run the seed files in db/seeds (or only those named), in name order — no migration tracking, so make them safe to re-run',\n )\n .action(async (names: string[]) => {\n const config = await getConfig()\n const dir = path.resolve(process.cwd(), config.seedsDir ?? 'db/seeds')\n try {\n const { ran } = await runSeeds({ dir, names })\n console.log(\n ran.length === 0 ? `No seeds in ${dir}.` : `Ran ${ran.length} seed(s): ${ran.join(', ')}`,\n )\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err))\n process.exitCode = 1\n }\n // A seed imports the app's own client, whose pool would keep the\n // command alive; it's done, so exit once output is flushed.\n process.stderr.write('', () =>\n process.stdout.write('', () => process.exit(process.exitCode ?? 0)),\n )\n })\n\n // ── migrate runner subcommands ─────────────────────────────────────────\n const migrate = parent.command('migrate').description('Migration runner subcommands')\n\n migrate\n .command('latest')\n .description('Apply all pending migrations in a new batch')\n .option(\n '--confirm-enum-drop',\n 'Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply',\n false,\n )\n .option('--tenants', \"Migrate every tenant's schema or database (db.tenants in kick.config)\")\n .action(async (opts: { confirmEnumDrop?: boolean; tenants?: boolean }) => {\n const config = await getConfig()\n if (opts.tenants) {\n if (!config.tenants) {\n throw new Error(\n 'kick db migrate latest --tenants needs a `tenants: { list, adapter }` db config',\n )\n }\n const r = await migrateTenants({\n tenants: config.tenants.list,\n adapterFor: config.tenants.adapter,\n concurrency: config.tenants.concurrency,\n migrationsDir: runDirs(config),\n driftCheck: config.driftCheck,\n confirmEnumDrop: opts.confirmEnumDrop,\n onTenant: (t) =>\n console.log(\n t.error\n ? `✗ ${t.tenant}: ${t.error instanceof Error ? t.error.message : String(t.error)}`\n : `✓ ${t.tenant}: ${t.summary!.applied.length === 0 ? 'up to date' : t.summary!.applied.join(', ')}`,\n ),\n })\n console.log(`${r.results.length - r.failed.length} migrated, ${r.failed.length} failed`)\n if (r.failed.length > 0) process.exitCode = 1\n return\n }\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateLatest({\n adapter,\n migrationsDir: runDirs(config),\n driftCheck: config.driftCheck,\n confirmEnumDrop: opts.confirmEnumDrop,\n })\n console.log(\n r.applied.length === 0\n ? 'No pending migrations.'\n : `Applied batch ${r.batch}: ${r.applied.join(', ')}`,\n )\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('up')\n .description('Apply the next single pending migration, or every one up to --to')\n .option(\n '--to <migration>',\n 'Apply pending migrations up to and including this one (id or name)',\n )\n .option(\n '--confirm-enum-drop',\n 'Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply',\n false,\n )\n .action(async (opts: { confirmEnumDrop?: boolean; to?: string }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateUp({\n adapter,\n migrationsDir: runDirs(config),\n driftCheck: config.driftCheck,\n confirmEnumDrop: opts.confirmEnumDrop,\n to: opts.to,\n })\n console.log(\n r.applied.length === 0\n ? 'No pending migrations.'\n : `Applied ${r.applied.join(', ')} (batch ${r.batch})`,\n )\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('down')\n .description('Reverse the most recent applied migration, or every one after --to')\n .option(\n '--to <migration>',\n 'Reverse every migration applied after this one (id or name), which stays',\n )\n .action(async (opts: { to?: string }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateDown({\n adapter,\n migrationsDir: runDirs(config),\n driftCheck: config.driftCheck,\n to: opts.to,\n })\n console.log(\n r.reversedAll.length > 0\n ? `Reversed ${r.reversedAll.join(', ')}.`\n : 'Nothing to reverse.',\n )\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('rollback')\n .description('Reverse the entire last batch as a single unit, or with --all every migration')\n .option('--all', 'Reverse every applied migration, newest first')\n .action(async (opts: { all?: boolean }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateRollback({\n adapter,\n migrationsDir: runDirs(config),\n driftCheck: config.driftCheck,\n all: opts.all,\n })\n console.log(\n r.reversed.length === 0\n ? 'Nothing to roll back.'\n : opts.all\n ? `Rolled back every migration: ${r.reversed.join(', ')}`\n : `Rolled back batch ${r.batch}: ${r.reversed.join(', ')}`,\n )\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('status')\n .description('Print applied + pending migrations')\n .action(async () => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n printStatusTable(await migrateStatus({ adapter, migrationsDir: runDirs(config) }))\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('unlock')\n .description(\n 'Release the migration lock left by a run that was killed mid-migration (make sure none is running)',\n )\n .action(async () => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n await adapter.releaseLock()\n console.log('Released the migration lock.')\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('review <id>')\n .description('Mark a migration reviewed (flips meta.json; migrates legacy -- REVIEWED markers)')\n .action(async (id: string) => {\n // No adapter/DB needed — review only touches the migration files.\n const config = await getConfig()\n const r = await reviewMigration(folderOf(config, id), id)\n console.log(\n r.alreadyReviewed\n ? `${r.id} was already reviewed — recorded its current contents as reviewed.`\n : `Reviewed ${r.id} — it can now be applied.`,\n )\n })\n\n // ── kick db introspect ─────────────────────────────────────────────────\n parent\n .command('introspect')\n .description('Generate a TypeScript schema file from a live database')\n .option('--out <path>', 'Output file (defaults to db.schemaPath from config)')\n .option('--json', 'Print the raw SchemaSnapshot JSON to stdout instead of writing TS source')\n .action(async (opts: { out?: string; json?: boolean }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const snapshot = await adapter.introspect()\n if (opts.json) {\n console.log(JSON.stringify(snapshot, null, 2))\n return\n }\n const out = opts.out ?? config.schemaPath\n // With casing, the database's snake_case names become camelCase keys.\n const source = config.casing === 'snake_case' ? removeCasing(snapshot) : snapshot\n await writeFile(out, renderSchemaSource(source), 'utf8')\n const n = Object.keys(snapshot.tables).length\n console.log(`Wrote ${out} (${n} table${n === 1 ? '' : 's'}).`)\n } finally {\n await cleanup()\n }\n })\n}\n\n/**\n * Read the `db` block off a host CLI config object. The kit types\n * `ctx.config` as `unknown`; the db block is structurally a\n * {@link KickDbConfigInput}.\n */\nfunction dbBlockOf(config: unknown): KickDbConfigInput | undefined {\n return (config as { db?: KickDbConfigInput } | null)?.db\n}\n\n/**\n * The database CLI plugin. Mount it in `kick.config.ts`:\n *\n * ```ts\n * import { defineConfig } from '@forinda/kickjs-cli'\n * import { dbCliPlugin } from '@forinda/kickjs-db/cli'\n *\n * export default defineConfig({ plugins: [dbCliPlugin] })\n * ```\n *\n * `kick db generate|migrate|introspect` then read config from the\n * `db` block of the same `kick.config.ts`.\n */\nexport const dbCliPlugin: KickCliPlugin = defineCliPlugin({\n name: 'kick/db',\n register(program, ctx) {\n const db = program.command('db').description('Database commands (kickjs-db)')\n registerDbCommands(db, () => resolveKickDbConfig(dbBlockOf(ctx.config)))\n },\n // Mounting the plugin also wires `.kickjs/types/kick__db.d.ts` generation\n // into `kick typegen` — db commands + db types from one opt-in plugin.\n typegens: [kickDbTypegen()],\n})\n"],"mappings":";;;;;;;;;;sjBAsBA,MAAM,qBAAuB,CAC3B,mBACA,yBACA,eACF,EAEa,mBAAmC,CAC9C,GAAI,UACJ,OAAQ,CAAC,mBAAoB,uBAAuB,EACpD,MAAM,SAAS,IAAiE,CAM9E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