@forinda/kickjs-db 7.2.1 → 7.4.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.
Files changed (40) hide show
  1. package/dist/cli.d.mts +10 -10
  2. package/dist/cli.d.mts.map +1 -1
  3. package/dist/cli.mjs +3 -3
  4. package/dist/cli.mjs.map +1 -1
  5. package/dist/custom-type-j8k__3sL.mjs +12 -0
  6. package/dist/custom-type-j8k__3sL.mjs.map +1 -0
  7. package/dist/devtools-events.d.mts +2 -1
  8. package/dist/devtools-events.mjs +1 -1
  9. package/dist/{index-Ci5DXgUh.d.mts → index-DF69HndC.d.mts} +39 -312
  10. package/dist/index-DF69HndC.d.mts.map +1 -0
  11. package/dist/index.d.mts +4 -3
  12. package/dist/index.mjs +2 -2
  13. package/dist/mysql.d.mts +11 -12
  14. package/dist/mysql.d.mts.map +1 -1
  15. package/dist/mysql.mjs +2 -2
  16. package/dist/mysql.mjs.map +1 -1
  17. package/dist/pg-BJmYKLhI.mjs +12 -0
  18. package/dist/pg-BJmYKLhI.mjs.map +1 -0
  19. package/dist/pg.d.mts +21 -21
  20. package/dist/pg.d.mts.map +1 -1
  21. package/dist/pg.mjs +2 -2
  22. package/dist/pg.mjs.map +1 -1
  23. package/dist/schema.d.mts +88 -0
  24. package/dist/schema.d.mts.map +1 -0
  25. package/dist/schema.mjs +12 -0
  26. package/dist/schema.mjs.map +1 -0
  27. package/dist/sqlite.d.mts +7 -8
  28. package/dist/sqlite.d.mts.map +1 -1
  29. package/dist/sqlite.mjs +2 -2
  30. package/dist/src-BnHTLx5l.mjs +166 -0
  31. package/dist/src-BnHTLx5l.mjs.map +1 -0
  32. package/dist/table-Bl5SbKRg.d.mts +309 -0
  33. package/dist/table-Bl5SbKRg.d.mts.map +1 -0
  34. package/dist/{types-NkfgZHEN.d.mts → types-DtvYnaXL.d.mts} +3 -4
  35. package/dist/types-DtvYnaXL.d.mts.map +1 -0
  36. package/package.json +14 -9
  37. package/dist/index-Ci5DXgUh.d.mts.map +0 -1
  38. package/dist/src-BLr8KOo1.mjs +0 -156
  39. package/dist/src-BLr8KOo1.mjs.map +0 -1
  40. package/dist/types-NkfgZHEN.d.mts.map +0 -1
package/dist/cli.d.mts CHANGED
@@ -1,9 +1,10 @@
1
1
 
2
- import { Kt as DriftBehavior, ir as Dialect, nt as DbConfig, rt as MigrationAdapterFactory } from "./index-Ci5DXgUh.mjs";
2
+ import { y as Dialect } from "./table-Bl5SbKRg.mjs";
3
+ import { At as DriftBehavior, nt as DbConfig, rt as MigrationAdapterFactory } from "./index-DF69HndC.mjs";
3
4
  import { CliTypegen, KickCliPlugin } from "@forinda/kickjs-cli-kit";
4
5
  import { Command } from "commander";
5
6
  //#region src/cli-typegen.d.ts
6
- declare const kickDbTypegen: () => CliTypegen;
7
+ export declare const kickDbTypegen: () => CliTypegen;
7
8
  //#endregion
8
9
  //#region src/cli.d.ts
9
10
  /**
@@ -12,7 +13,7 @@ declare const kickDbTypegen: () => CliTypegen;
12
13
  * `db` block in `kick.config.ts`, so a config authored with
13
14
  * `defineKickDbConfig` drops straight into either place.
14
15
  */
15
- interface KickDbConfigInput {
16
+ export interface KickDbConfigInput {
16
17
  schemaPath?: string;
17
18
  migrationsDir?: string;
18
19
  dialect?: Dialect;
@@ -31,17 +32,17 @@ interface KickDbConfigInput {
31
32
  * defineKickDbConfig({ ... })`) or as the value of `kick.config.ts`'s
32
33
  * `db` field. Both resolve through {@link resolveKickDbConfig}.
33
34
  */
34
- declare function defineKickDbConfig(cfg: KickDbConfigInput): KickDbConfigInput;
35
+ export declare function defineKickDbConfig(cfg: KickDbConfigInput): KickDbConfigInput;
35
36
  /**
36
37
  * Shallow-merge db configs, later wins (vite's `mergeConfig` spirit).
37
38
  * Lets a standalone `kickjs-db.config.ts` layer over a project's
38
39
  * `kick.config.ts` `db` block, or vice versa.
39
40
  */
40
- declare function mergeKickDbConfig(...configs: (KickDbConfigInput | undefined)[]): KickDbConfigInput;
41
+ export declare function mergeKickDbConfig(...configs: (KickDbConfigInput | undefined)[]): KickDbConfigInput;
41
42
  /** Apply defaults to a {@link KickDbConfigInput}, yielding a resolved {@link DbConfig}. */
42
- declare function resolveKickDbConfig(block: KickDbConfigInput | undefined): DbConfig;
43
+ export declare function resolveKickDbConfig(block: KickDbConfigInput | undefined): DbConfig;
43
44
  /** A config source — resolved lazily so each command reads fresh config. */
44
- type DbConfigResolver = () => DbConfig | Promise<DbConfig>;
45
+ export type DbConfigResolver = () => DbConfig | Promise<DbConfig>;
45
46
  /**
46
47
  * Attach the db commands (`generate`, `migrate *`, `introspect`) onto a
47
48
  * commander command. `parent` is the command they hang off — the plugin
@@ -50,7 +51,7 @@ type DbConfigResolver = () => DbConfig | Promise<DbConfig>;
50
51
  * the resolved {@link DbConfig} — under kickjs-cli from `ctx.config.db`,
51
52
  * standalone from `kickjs-db.config.ts`.
52
53
  */
53
- declare function registerDbCommands(parent: Command, getConfig: DbConfigResolver): void;
54
+ export declare function registerDbCommands(parent: Command, getConfig: DbConfigResolver): void;
54
55
  /**
55
56
  * The database CLI plugin. Mount it in `kick.config.ts`:
56
57
  *
@@ -64,7 +65,6 @@ declare function registerDbCommands(parent: Command, getConfig: DbConfigResolver
64
65
  * `kick db generate|migrate|introspect` then read config from the
65
66
  * `db` block of the same `kick.config.ts`.
66
67
  */
67
- declare const dbCliPlugin: KickCliPlugin;
68
+ export declare const dbCliPlugin: KickCliPlugin;
68
69
  //#endregion
69
- export { DbConfigResolver, KickDbConfigInput, dbCliPlugin, defineKickDbConfig, kickDbTypegen, mergeKickDbConfig, registerDbCommands, resolveKickDbConfig };
70
70
  //# sourceMappingURL=cli.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.mts","names":[],"sources":["../src/cli-typegen.ts","../src/cli.ts"],"mappings":";;;;;cA4Ba,qBAAoB;;;;;;;;;UCoBhB;EACf;EACA;EACA,UAAU;EACV;EACA,UAAU;;;;;;EAMV,aAAa;;;;;;;;iBASC,mBAAmB,KAAK,oBAAoB;;;;;;iBAS5C,qBACX,UAAU,mCACZ;;iBAKa,oBAAoB,OAAO,gCAAgC;;KAuF/D,yBAAyB,WAAW,QAAQ;;;;;;;;;iBAUxC,mBAAmB,QAAQ,SAAS,WAAW;;;;;;;;;;;;;;cAiNlD,aAAa"}
1
+ {"version":3,"file":"cli.d.mts","names":[],"sources":["../src/cli-typegen.ts","../src/cli.ts"],"mappings":";;;;;;qBA4Ba,qBAAoB;;;;;;;;;iBCoBhB;EACf;EACA;EACA,UAAU;EACV;EACA,UAAU;;;;;;EAMV,aAAa;;;;;;;;wBASC,mBAAmB,KAAK,oBAAoB;;;;;;wBAS5C,qBACX,UAAU,mCACZ;;wBAKa,oBAAoB,OAAO,gCAAgC;;YAuF/D,yBAAyB,WAAW,QAAQ;;;;;;;;;wBAUxC,mBAAmB,QAAQ,SAAS,WAAW;;;;;;;;;;;;;;qBAiNlD,aAAa"}
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-db v7.2.1
2
+ * @forinda/kickjs-db v7.4.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,6 +8,6 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{$ as migrateUp,At as renderSchemaSource,Et as detectCompositeReferences,N as reviewMigration,Q as migrateStatus,X as migrateLatest,Y as migrateDown,Z as migrateRollback,j as generate}from"./src-BLr8KOo1.mjs";import{writeFile}from"node:fs/promises";import{existsSync}from"node:fs";import path from"node:path";import{defineCliPlugin}from"@forinda/kickjs-cli-kit";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
- `)}});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 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`,dialect:db.dialect??`postgres`,connectionString:db.connectionString??process.env.DATABASE_URL,adapter:db.adapter,driftCheck:db.driftCheck}}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});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){if(status.length===0){console.log(`No migrations.`);return}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)`).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 result=await generate({name,config,cwd,empty:opts.empty,detectCompositeRefs});if(result.status===`no-changes`){console.log(`No schema changes detected.`);return}if(result.empty){console.log(`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()}});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).action(async opts=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateLatest({adapter,migrationsDir:config.migrationsDir,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`).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:config.migrationsDir,driftCheck:config.driftCheck,confirmEnumDrop:opts.confirmEnumDrop});console.log(r.applied.length===0?`No pending migrations.`:`Applied ${r.applied[0]} (batch ${r.batch})`)}finally{await cleanup()}}),migrate.command(`down`).description(`Reverse the most recent applied migration`).action(async()=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateDown({adapter,migrationsDir:config.migrationsDir,driftCheck:config.driftCheck});console.log(r.reversed?`Reversed ${r.reversed}.`:`Nothing to reverse.`)}finally{await cleanup()}}),migrate.command(`rollback`).description(`Reverse the entire last batch as a single unit`).action(async()=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateRollback({adapter,migrationsDir:config.migrationsDir,driftCheck:config.driftCheck});console.log(r.reversed.length===0?`Nothing to roll back.`:`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:config.migrationsDir}))}finally{await cleanup()}}),migrate.command(`review <id>`).description(`Mark a migration reviewed (flips meta.json; migrates legacy -- REVIEWED markers)`).action(async id=>{let r=await reviewMigration((await getConfig()).migrationsDir,id);console.log(r.alreadyReviewed?`${r.id} was already 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;await writeFile(out,renderSchemaSource(snapshot),`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};
11
+ import{G as migrateLatest,J as migrateUp,K as migrateRollback,N as reviewMigration,Tt as renderSchemaSource,W as migrateDown,j as generate,q as migrateStatus,xt as detectCompositeReferences}from"./src-BnHTLx5l.mjs";import{writeFile}from"node:fs/promises";import{existsSync}from"node:fs";import path from"node:path";import{defineCliPlugin}from"@forinda/kickjs-cli-kit";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
+ `)}});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 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`,dialect:db.dialect??`postgres`,connectionString:db.connectionString??process.env.DATABASE_URL,adapter:db.adapter,driftCheck:db.driftCheck}}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});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){if(status.length===0){console.log(`No migrations.`);return}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)`).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 result=await generate({name,config,cwd,empty:opts.empty,detectCompositeRefs});if(result.status===`no-changes`){console.log(`No schema changes detected.`);return}if(result.empty){console.log(`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()}});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).action(async opts=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateLatest({adapter,migrationsDir:config.migrationsDir,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`).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:config.migrationsDir,driftCheck:config.driftCheck,confirmEnumDrop:opts.confirmEnumDrop});console.log(r.applied.length===0?`No pending migrations.`:`Applied ${r.applied[0]} (batch ${r.batch})`)}finally{await cleanup()}}),migrate.command(`down`).description(`Reverse the most recent applied migration`).action(async()=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateDown({adapter,migrationsDir:config.migrationsDir,driftCheck:config.driftCheck});console.log(r.reversed?`Reversed ${r.reversed}.`:`Nothing to reverse.`)}finally{await cleanup()}}),migrate.command(`rollback`).description(`Reverse the entire last batch as a single unit`).action(async()=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateRollback({adapter,migrationsDir:config.migrationsDir,driftCheck:config.driftCheck});console.log(r.reversed.length===0?`Nothing to roll back.`:`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:config.migrationsDir}))}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(config.migrationsDir,id);console.log(r.alreadyReviewed?`${r.id} was already 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;await writeFile(out,renderSchemaSource(snapshot),`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};
13
13
  //# 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.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","/**\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 { writeFile } from 'node:fs/promises'\nimport type { Command } from 'commander'\n\nimport { defineCliPlugin, type KickCliPlugin } from '@forinda/kickjs-cli-kit'\nimport { kickDbTypegen } from './cli-typegen'\n\nexport { kickDbTypegen } from './cli-typegen'\n\nimport {\n detectCompositeReferences,\n generate,\n migrateLatest,\n migrateUp,\n migrateDown,\n migrateRollback,\n migrateStatus,\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 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}\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 dialect: db.dialect ?? 'postgres',\n connectionString: db.connectionString ?? process.env.DATABASE_URL,\n adapter: db.adapter,\n driftCheck: db.driftCheck,\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 })\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 .action(async (name: string, opts: { empty?: boolean }) => {\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 result = await generate({ name, config, cwd, empty: opts.empty, detectCompositeRefs })\n if (result.status === 'no-changes') {\n console.log('No schema changes detected.')\n return\n }\n if (result.empty) {\n console.log(`Created empty migration ${result.migrationDir} (author up.sql + down.sql).`)\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 // ── 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 .action(async (opts: { confirmEnumDrop?: boolean }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateLatest({\n adapter,\n migrationsDir: config.migrationsDir,\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')\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 }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateUp({\n adapter,\n migrationsDir: config.migrationsDir,\n driftCheck: config.driftCheck,\n confirmEnumDrop: opts.confirmEnumDrop,\n })\n console.log(\n r.applied.length === 0\n ? 'No pending migrations.'\n : `Applied ${r.applied[0]} (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')\n .action(async () => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateDown({\n adapter,\n migrationsDir: config.migrationsDir,\n driftCheck: config.driftCheck,\n })\n console.log(r.reversed ? `Reversed ${r.reversed}.` : 'Nothing to reverse.')\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('rollback')\n .description('Reverse the entire last batch as a single unit')\n .action(async () => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateRollback({\n adapter,\n migrationsDir: config.migrationsDir,\n driftCheck: config.driftCheck,\n })\n console.log(\n r.reversed.length === 0\n ? 'Nothing to roll back.'\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: config.migrationsDir }))\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(config.migrationsDir, id)\n console.log(\n r.alreadyReviewed\n ? `${r.id} was already 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 await writeFile(out, renderSchemaSource(snapshot), '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":";;;;;;;;;;gXAsBA,MAAM,qBAAuB,CAC3B,mBACA,yBACA,eACF,EAEa,mBAAmC,CAC9C,G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,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.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","/**\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 { writeFile } from 'node:fs/promises'\nimport type { Command } from 'commander'\n\nimport { defineCliPlugin, type KickCliPlugin } from '@forinda/kickjs-cli-kit'\nimport { kickDbTypegen } from './cli-typegen'\n\nexport { kickDbTypegen } from './cli-typegen'\n\nimport {\n detectCompositeReferences,\n generate,\n migrateLatest,\n migrateUp,\n migrateDown,\n migrateRollback,\n migrateStatus,\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 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}\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 dialect: db.dialect ?? 'postgres',\n connectionString: db.connectionString ?? process.env.DATABASE_URL,\n adapter: db.adapter,\n driftCheck: db.driftCheck,\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 })\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 .action(async (name: string, opts: { empty?: boolean }) => {\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 result = await generate({ name, config, cwd, empty: opts.empty, detectCompositeRefs })\n if (result.status === 'no-changes') {\n console.log('No schema changes detected.')\n return\n }\n if (result.empty) {\n console.log(`Created empty migration ${result.migrationDir} (author up.sql + down.sql).`)\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 // ── 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 .action(async (opts: { confirmEnumDrop?: boolean }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateLatest({\n adapter,\n migrationsDir: config.migrationsDir,\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')\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 }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateUp({\n adapter,\n migrationsDir: config.migrationsDir,\n driftCheck: config.driftCheck,\n confirmEnumDrop: opts.confirmEnumDrop,\n })\n console.log(\n r.applied.length === 0\n ? 'No pending migrations.'\n : `Applied ${r.applied[0]} (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')\n .action(async () => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateDown({\n adapter,\n migrationsDir: config.migrationsDir,\n driftCheck: config.driftCheck,\n })\n console.log(r.reversed ? `Reversed ${r.reversed}.` : 'Nothing to reverse.')\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('rollback')\n .description('Reverse the entire last batch as a single unit')\n .action(async () => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateRollback({\n adapter,\n migrationsDir: config.migrationsDir,\n driftCheck: config.driftCheck,\n })\n console.log(\n r.reversed.length === 0\n ? 'Nothing to roll back.'\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: config.migrationsDir }))\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(config.migrationsDir, id)\n console.log(\n r.alreadyReviewed\n ? `${r.id} was already 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 await writeFile(out, renderSchemaSource(snapshot), '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":";;;;;;;;;;gXAsBA,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,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M,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,WAC/B,MAAM,UAAU,IAAK,mBAAmB,QAAQ,EAAG,MAAM,EACzD,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"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @forinda/kickjs-db v7.4.0
3
+ *
4
+ * Copyright (c) Felix Orinda
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ const KICK_GENERATED=Symbol.for(`@forinda/kickjs-db/Generated`),KICK_NOT_NULL=Symbol.for(`@forinda/kickjs-db/NotNull`);var ColumnBuilder=class{state;constructor(type,defaults={}){this.state={type,nullable:defaults.nullable??!0,default:defaults.default??null,primaryKey:defaults.primaryKey??!1,unique:defaults.unique??!1,references:defaults.references??null}}notNull(){return this.state.nullable=!1,this}primaryKey(){return this.state.primaryKey=!0,this.state.nullable=!1,this}unique(){return this.state.unique=!0,this}array(){return this.state.type=`${this.state.type}[]`,this}references(target,opts={}){return this.state.references={thunk:target,onDelete:opts.onDelete??`no_action`,onUpdate:opts.onUpdate??`no_action`,...opts.name===void 0?{}:{name:opts.name}},this}default(value){return this.state.default=typeof value==`string`?value:String(value),this}toJSON(name){return{name,type:this.state.type,nullable:this.state.nullable,default:this.state.default,primaryKey:this.state.primaryKey}}__state(){return this.state}},CustomColumnBuilder=class extends ColumnBuilder{toDriver;fromDriver;constructor(opts){super(opts.dataType()),this.toDriver=opts.toDriver,this.fromDriver=opts.fromDriver}};function customType(opts){return()=>new CustomColumnBuilder(opts)}export{KICK_NOT_NULL as a,KICK_GENERATED as i,customType as n,ColumnBuilder as r,CustomColumnBuilder as t};
12
+ //# sourceMappingURL=custom-type-j8k__3sL.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"custom-type-j8k__3sL.mjs","names":[],"sources":["../src/dsl/columns/types.ts","../src/custom-type.ts"],"sourcesContent":["import type { ColumnSnapshot, FkAction } from '../../snapshot/types'\n\n/**\n * Runtime + type representation of a column reference (e.g. `users.id`).\n * Carries the parent table name, the column's own name, plus runtime\n * accessors used by FK thunks and constraint builders.\n *\n * Exported so adopters can annotate self-referencing thunks without\n * spelling the shape inline:\n *\n * parentId: uuid().references((): ColumnRef => categories.id)\n *\n * Without the annotation the initializer of a self-referencing const\n * trips TS7022 — TS needs to infer the const while the initializer\n * already references it.\n */\nexport interface ColumnRef {\n __tableName: string\n __name: string\n __builder: ColumnBuilder\n __state: () => ReturnType<ColumnBuilder['__state']>\n}\n\n/**\n * Resolved FK spec — `table` / `column` are pulled by invoking `thunk()`\n * lazily. The thunk pattern lets self-referencing tables work:\n *\n * const categories = table('categories', {\n * id: uuid().primaryKey().defaultRandom(),\n * parentId: uuid().references((): ColumnRef => categories.id),\n * })\n *\n * If we resolved at `.references()` call time, `categories` would TDZ-fail\n * inside its own initializer. Storing the thunk and resolving on read\n * (extract / render / emit) defers until after the const binding lands.\n */\nexport interface FkSpec {\n thunk: () => ColumnRef\n onDelete: FkAction\n onUpdate: FkAction\n /**\n * The constraint's name in the database.\n *\n * Omitted for schemas written by hand — the name is then derived as\n * `<table>_<column>_fk`. It is set when the schema was generated by\n * `kick db introspect`, because a database names its constraints itself:\n * Postgres' own default is `<table>_<column>_fkey`, and a DBA may have\n * chosen anything. Dropping the real name would make the next diff want to\n * rename every foreign key in the schema.\n */\n name?: string\n}\n\nexport interface ColumnState {\n type: string\n nullable: boolean\n default: string | null\n primaryKey: boolean\n unique: boolean\n references: FkSpec | null\n}\n\n/**\n * Type-only brand attached to a column when it's auto-assigned by the\n * database (serial / bigserial / smallserial), has a runtime default\n * (`.default(...)`), or carries an expression default\n * (`uuid().defaultRandom()`, `timestamp().defaultNow()`). `SchemaToTypes<S>`\n * reads this marker and wraps the column type in Kysely's `Generated<T>` so\n * adopters can omit the column on insert.\n *\n * Runtime is a no-op — the symbol never reaches a value.\n */\nexport const KICK_GENERATED = Symbol.for('@forinda/kickjs-db/Generated')\nexport type GeneratedBrand = { readonly [KICK_GENERATED]?: true }\n\n/**\n * Type-only brand attached to a column when `.notNull()` or `.primaryKey()`\n * is called. `SchemaToTypes<S>` reads this brand to decide whether the\n * column type is `T` (NOT NULL) or `T | null` (default nullable).\n *\n * Why a brand instead of a class generic: chained methods (notNull,\n * primaryKey) can return `this & NotNullBrand` to narrow nullability while\n * preserving the subclass identity — so `uuid().primaryKey().defaultRandom()`\n * still resolves `defaultRandom()` on `UuidBuilder`. A class generic\n * `<TNullable>` would collapse the subclass back to the parent.\n */\nexport const KICK_NOT_NULL = Symbol.for('@forinda/kickjs-db/NotNull')\nexport type NotNullBrand = { readonly [KICK_NOT_NULL]?: true }\n\n/**\n * Re-attach the nullability / generated brands after a transform that\n * must return a *new* builder type (e.g. `.array()` widening `T` to\n * `T[]`). Without this, `integer().notNull().array()` silently dropped\n * `NotNullBrand` and the row type regressed to `number[] | null`.\n *\n * Uses the same `extends` checks as `SchemaToTypes` (client/schema-types.ts)\n * so detection stays consistent in both directions.\n */\nexport type PreserveBrands<Self, Out> = Out &\n (Self extends NotNullBrand ? NotNullBrand : unknown) &\n (Self extends GeneratedBrand ? GeneratedBrand : unknown)\n\n/**\n * Phantom-typed column builder. The `T` generic carries the column's TS\n * value type (number / string / Date / etc.); nullability is tracked via\n * the `NotNullBrand` intersection rather than a class generic so chain\n * methods preserve subclass identity.\n *\n * Both `T` and the brand are erased at runtime; they exist purely so\n * `SchemaToTypes<S>` can pull them out per column.\n */\nexport class ColumnBuilder<T = unknown> {\n // Phantom param shows up in the public surface so the type system sees\n // it. Reading it at runtime is intentionally not supported.\n declare readonly __t?: T\n\n protected state: ColumnState\n\n constructor(type: string, defaults: Partial<ColumnState> = {}) {\n this.state = {\n type,\n nullable: defaults.nullable ?? true,\n default: defaults.default ?? null,\n primaryKey: defaults.primaryKey ?? false,\n unique: defaults.unique ?? false,\n references: defaults.references ?? null,\n }\n }\n\n notNull(): this & NotNullBrand {\n this.state.nullable = false\n return this as this & NotNullBrand\n }\n\n primaryKey(): this & NotNullBrand {\n this.state.primaryKey = true\n this.state.nullable = false\n return this as this & NotNullBrand\n }\n\n unique(): this {\n this.state.unique = true\n return this\n }\n\n array(): PreserveBrands<this, ColumnBuilder<T[]>> {\n this.state.type = `${this.state.type}[]`\n return this as unknown as PreserveBrands<this, ColumnBuilder<T[]>>\n }\n\n references(\n target: () => ColumnRef,\n opts: { onDelete?: FkAction; onUpdate?: FkAction; name?: string } = {},\n ): this {\n // Store the thunk — do NOT invoke it here. Self-referencing tables\n // pass `() => self.id` whose binding does not exist yet.\n this.state.references = {\n thunk: target,\n onDelete: opts.onDelete ?? 'no_action',\n onUpdate: opts.onUpdate ?? 'no_action',\n // Only carried when given: an absent name means \"derive it\", and\n // storing the derived value here would make it indistinguishable from\n // an explicit one that happens to match.\n ...(opts.name === undefined ? {} : { name: opts.name }),\n }\n return this\n }\n\n /**\n * Mark the column as having a runtime / DB-assigned default. The\n * `GeneratedBrand` flows into `SchemaToTypes<S>` so the column wraps\n * in `Generated<T>` — adopters can `INSERT` without specifying it.\n *\n * Accepts the natural literal for the column type — `boolean().default(false)`,\n * `integer().default(0)`, `varchar().default('active')`. Non-string\n * literals are normalised to their SQL-literal text so the snapshot\n * (`ColumnSnapshot.default: string | null`) and migration emitter stay\n * string-only. For a quoted string default the text is the value\n * itself (`'active'`); booleans/numbers emit bare (`false`, `0`).\n */\n default(value: string | number | boolean): this & GeneratedBrand {\n this.state.default = typeof value === 'string' ? value : String(value)\n return this as this & GeneratedBrand\n }\n\n toJSON(name: string): ColumnSnapshot {\n return {\n name,\n type: this.state.type,\n nullable: this.state.nullable,\n default: this.state.default,\n primaryKey: this.state.primaryKey,\n }\n }\n\n // Internal accessor for table()/diff to read full state including unique/references.\n __state(): Readonly<ColumnState> {\n return this.state\n }\n}\n","// customType<T>() — adopter-defined column type with optional driver\n// codecs. Lets a project introduce a typed column that doesn't ship\n// in the built-in DSL (encrypted strings, custom JSON shapes, citext,\n// PostGIS geometry, etc.) without forking the package.\n//\n// Schema usage:\n//\n// const encrypted = customType<EncryptedString>({\n// dataType: () => 'text',\n// toDriver: (s) => encrypt(s),\n// fromDriver: (raw) => decrypt(String(raw)),\n// })\n//\n// export const secrets = table('secrets', {\n// id: serial().primaryKey(),\n// value: encrypted().notNull(),\n// })\n//\n// `SchemaToTypes<typeof schema>` reads the phantom T from the\n// CustomColumnBuilder so `db.selectFrom('secrets').select('value')`\n// types `value: EncryptedString` (not `string`). Driver codecs flow\n// through the lifecycle plugin landing in M2.F-T19; until then they\n// are stored on the builder for the runtime hookup to pick up.\n\nimport { ColumnBuilder } from './dsl/columns/types'\n\nexport interface CustomTypeOptions<TJs, TDriver = unknown> {\n /**\n * SQL data type as it would appear in `CREATE TABLE` — `'text'`,\n * `'jsonb'`, `'citext'`, `'geometry(Point, 4326)'`, etc. Returned\n * via a thunk so adopters can compute the type from runtime config\n * (e.g. dialect-specific overrides).\n */\n dataType: () => string\n /** Optional encode hook applied at insert / update time. */\n toDriver?: (value: TJs) => TDriver\n /** Optional decode hook applied to selected rows. */\n fromDriver?: (driver: TDriver) => TJs\n}\n\n/**\n * ColumnBuilder subclass produced by `customType()`. Carries the\n * driver codecs so the (future) hooks pipeline can wire them through\n * a Kysely plugin without each consumer re-declaring its mapping.\n *\n * The phantom `T` flows through `SchemaToTypes<S>` exactly like any\n * other ColumnBuilder<T>, so adopters get full row-shape inference\n * for free.\n */\nexport class CustomColumnBuilder<TJs> extends ColumnBuilder<TJs> {\n /** Encode hook — run on values heading into the database. */\n readonly toDriver?: (value: TJs) => unknown\n /** Decode hook — run on row values coming out of the database. */\n readonly fromDriver?: (driver: unknown) => TJs\n\n constructor(opts: CustomTypeOptions<TJs>) {\n super(opts.dataType())\n this.toDriver = opts.toDriver as never\n this.fromDriver = opts.fromDriver as never\n }\n}\n\n/**\n * Build a reusable column factory for a custom type. The returned\n * function is what callers use inside `table('foo', { col: factory() })`\n * — same shape as the built-in `varchar()`, `text()`, etc.\n *\n * @example\n * ```ts\n * const ulid = customType<string>({\n * dataType: () => 'char(26)',\n * toDriver: (s) => s,\n * fromDriver: (raw) => String(raw),\n * })\n *\n * const events = table('events', {\n * id: ulid().primaryKey(),\n * ts: timestamp().notNull().defaultNow(),\n * })\n * ```\n */\nexport function customType<TJs>(opts: CustomTypeOptions<TJs>): () => CustomColumnBuilder<TJs> {\n return () => new CustomColumnBuilder<TJs>(opts)\n}\n"],"mappings":";;;;;;;;;;AAwEA,MAAa,eAAiB,OAAO,IAAI,8BAA8B,EAc1D,cAAgB,OAAO,IAAI,4BAA4B,EAyBpE,IAAa,cAAb,KAAwC,CAKtC,MAEA,YAAY,KAAc,SAAiC,CAAC,EAAG,CAC7D,KAAK,MAAQ,CACX,KACA,SAAU,SAAS,UAAY,GAC/B,QAAS,SAAS,SAAW,KAC7B,WAAY,SAAS,YAAc,GACnC,OAAQ,SAAS,QAAU,GAC3B,WAAY,SAAS,YAAc,IACrC,CACF,CAEA,SAA+B,CAE7B,MADA,MAAK,MAAM,SAAW,GACf,IACT,CAEA,YAAkC,CAGhC,MAFA,MAAK,MAAM,WAAa,GACxB,KAAK,MAAM,SAAW,GACf,IACT,CAEA,QAAe,CAEb,MADA,MAAK,MAAM,OAAS,GACb,IACT,CAEA,OAAkD,CAEhD,MADA,MAAK,MAAM,KAAO,GAAG,KAAK,MAAM,KAAK,IAC9B,IACT,CAEA,WACE,OACA,KAAoE,CAAC,EAC/D,CAYN,MATA,MAAK,MAAM,WAAa,CACtB,MAAO,OACP,SAAU,KAAK,UAAY,YAC3B,SAAU,KAAK,UAAY,YAI3B,GAAI,KAAK,OAAS,IAAA,GAAY,CAAC,EAAI,CAAE,KAAM,KAAK,IAAK,CACvD,EACO,IACT,CAcA,QAAQ,MAAyD,CAE/D,MADA,MAAK,MAAM,QAAU,OAAO,OAAU,SAAW,MAAQ,OAAO,KAAK,EAC9D,IACT,CAEA,OAAO,KAA8B,CACnC,MAAO,CACL,KACA,KAAM,KAAK,MAAM,KACjB,SAAU,KAAK,MAAM,SACrB,QAAS,KAAK,MAAM,QACpB,WAAY,KAAK,MAAM,UACzB,CACF,CAGA,SAAiC,CAC/B,OAAO,KAAK,KACd,CACF,ECtJa,oBAAb,cAA8C,aAAmB,CAE/D,SAEA,WAEA,YAAY,KAA8B,CACxC,MAAM,KAAK,SAAS,CAAC,EACrB,KAAK,SAAW,KAAK,SACrB,KAAK,WAAa,KAAK,UACzB,CACF,EAqBA,SAAgB,WAAgB,KAA8D,CAC5F,UAAa,IAAI,oBAAyB,IAAI,CAChD"}
@@ -1,5 +1,5 @@
1
1
 
2
- import { a as QueryErrorEvent, o as QueryEvent, s as SlowQueryEvent } from "./types-NkfgZHEN.mjs";
2
+ import { a as QueryErrorEvent, o as QueryEvent, s as SlowQueryEvent } from "./types-DtvYnaXL.mjs";
3
3
  //#region src/devtools-events.d.ts
4
4
  declare module '@forinda/kickjs-devtools-kit/bus' {
5
5
  interface KickDevtoolsEventRegistry {
@@ -26,4 +26,5 @@ declare module '@forinda/kickjs-devtools-kit/bus' {
26
26
  };
27
27
  }
28
28
  }
29
+ //#endregion
29
30
  //# sourceMappingURL=devtools-events.d.mts.map
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-db v7.2.1
2
+ * @forinda/kickjs-db v7.4.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *