@kysera/migrations 0.8.6 → 0.8.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -97,8 +97,13 @@ interface MigrationResult {
97
97
  /** Whether the run was in dry-run mode */
98
98
  dryRun: boolean;
99
99
  }
100
- /** Error codes for migration operations */
101
- type MigrationErrorCode = 'MIGRATION_UP_FAILED' | 'MIGRATION_DOWN_FAILED' | 'MIGRATION_VALIDATION_FAILED';
100
+ /** Error codes for migration operations — references unified codes from @kysera/core */
101
+ declare const MigrationErrorCodes: {
102
+ readonly UP_FAILED: "MIGRATION_UP_FAILED";
103
+ readonly DOWN_FAILED: "MIGRATION_DOWN_FAILED";
104
+ readonly VALIDATION_FAILED: "MIGRATION_VALIDATION_FAILED";
105
+ };
106
+ type MigrationErrorCode = (typeof MigrationErrorCodes)[keyof typeof MigrationErrorCodes];
102
107
  /**
103
108
  * Migration-specific error extending DatabaseError from @kysera/core
104
109
  * Provides structured error information with code, migration context, and cause tracking
@@ -127,7 +132,12 @@ declare class MigrationRunner<DB = unknown> {
127
132
  };
128
133
  protected db: Kysely<DB>;
129
134
  protected migrations: Migration<DB>[];
135
+ private setupDone;
130
136
  constructor(db: Kysely<DB>, migrations: Migration<DB>[], options?: MigrationRunnerOptions);
137
+ /**
138
+ * Ensure migrations table exists (idempotent, cached after first call)
139
+ */
140
+ protected ensureSetup(): Promise<void>;
131
141
  /**
132
142
  * Get list of executed migrations from database
133
143
  * Note: Uses type assertions for migrations table as it's not part of the user schema
@@ -155,10 +165,28 @@ declare class MigrationRunner<DB = unknown> {
155
165
  * Run all pending migrations
156
166
  */
157
167
  up(): Promise<MigrationResult>;
168
+ /**
169
+ * Core up logic — used by up(), upTo(), and overridden by MigrationRunnerWithPlugins.
170
+ * Protected to allow hook injection by subclasses.
171
+ */
172
+ protected runUp(migrationsToConsider: Migration<DB>[], hooks?: {
173
+ before?: (migration: Migration<DB>) => Promise<void>;
174
+ after?: (migration: Migration<DB>, duration: number) => Promise<void>;
175
+ onError?: (migration: Migration<DB>, error: unknown) => Promise<void>;
176
+ }): Promise<MigrationResult>;
158
177
  /**
159
178
  * Rollback last N migrations
160
179
  */
161
180
  down(steps?: number): Promise<MigrationResult>;
181
+ /**
182
+ * Core down logic — used by down() and overridden by MigrationRunnerWithPlugins.
183
+ * Protected to allow hook injection by subclasses.
184
+ */
185
+ protected runDown(steps: number, hooks?: {
186
+ before?: (migration: Migration<DB>) => Promise<void>;
187
+ after?: (migration: Migration<DB>, duration: number) => Promise<void>;
188
+ onError?: (migration: Migration<DB>, error: unknown) => Promise<void>;
189
+ }): Promise<MigrationResult>;
162
190
  /**
163
191
  * Show migration status
164
192
  */
@@ -290,13 +318,13 @@ declare class MigrationRunnerWithPlugins<DB = unknown> extends MigrationRunner<D
290
318
  */
291
319
  getPlugins(): MigrationPlugin<DB>[];
292
320
  /**
293
- * Run all pending migrations with plugin hooks
294
- * Overrides parent to call beforeMigration/afterMigration/onMigrationError hooks
321
+ * Run all pending migrations with plugin hooks.
322
+ * Delegates to parent's runUp with plugin lifecycle hooks.
295
323
  */
296
324
  up(): Promise<MigrationResult>;
297
325
  /**
298
- * Rollback last N migrations with plugin hooks
299
- * Overrides parent to call beforeMigration/afterMigration/onMigrationError hooks
326
+ * Rollback last N migrations with plugin hooks.
327
+ * Delegates to parent's runDown with plugin lifecycle hooks.
300
328
  */
301
329
  down(steps?: number): Promise<MigrationResult>;
302
330
  }
@@ -320,4 +348,4 @@ declare function createMetricsPlugin<DB = unknown>(): MigrationPlugin<DB> & {
320
348
  };
321
349
  };
322
350
 
323
- export { type Migration, type MigrationDefinition, type MigrationDefinitions, MigrationError, type MigrationErrorCode, type MigrationPlugin, type MigrationResult, MigrationRunner, type MigrationRunnerOptions, MigrationRunnerWithPlugins, type MigrationRunnerWithPluginsOptions, type MigrationStatus, type MigrationWithMeta, createLoggingPlugin, createMetricsPlugin, createMigration, createMigrationRunner, createMigrationRunnerWithPlugins, createMigrationWithMeta, defineMigrations, getMigrationStatus, rollbackMigrations, runMigrations, setupMigrations };
351
+ export { type Migration, type MigrationDefinition, type MigrationDefinitions, MigrationError, type MigrationErrorCode, MigrationErrorCodes, type MigrationPlugin, type MigrationResult, MigrationRunner, type MigrationRunnerOptions, MigrationRunnerWithPlugins, type MigrationRunnerWithPluginsOptions, type MigrationStatus, type MigrationWithMeta, createLoggingPlugin, createMetricsPlugin, createMigration, createMigrationRunner, createMigrationRunnerWithPlugins, createMigrationWithMeta, defineMigrations, getMigrationStatus, rollbackMigrations, runMigrations, setupMigrations };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import {sql}from'kysely';import {silentLogger,DatabaseError,BadRequestError,NotFoundError}from'@kysera/core';export{BadRequestError,DatabaseError,NotFoundError,silentLogger}from'@kysera/core';import {z}from'zod';var R="__VERSION__",h=R.startsWith("__")?"0.0.0-dev":R;var x=z.object({trace:z.function(),debug:z.function(),info:z.function(),warn:z.function(),error:z.function(),fatal:z.function()}).passthrough(),f=z.object({dryRun:z.boolean().default(false),logger:x.optional(),useTransactions:z.boolean().default(false),stopOnError:z.boolean().default(true),verbose:z.boolean().default(true)}),M=z.object({name:z.string().min(1,"Migration name is required"),description:z.string().optional(),breaking:z.boolean().default(false),tags:z.array(z.string()).default([]),estimatedDuration:z.string().optional()}),B=z.object({logger:x.optional()}),b=z.object({name:z.string().min(1,"Plugin name is required"),version:z.string().min(1,"Plugin version is required"),onInit:z.function().optional(),beforeMigration:z.function().optional(),afterMigration:z.function().optional(),onMigrationError:z.function().optional()}),P=z.object({executed:z.array(z.string()),pending:z.array(z.string()),total:z.number().int().nonnegative()}),E=z.object({executed:z.array(z.string()),skipped:z.array(z.string()),failed:z.array(z.string()),duration:z.number().nonnegative(),dryRun:z.boolean()}),$=f.extend({plugins:z.array(b).optional()});function v(o){return f.parse(o)}function S(o){return f.safeParse(o)}function I(o){return M.parse(o)}function N(o){return M.safeParse(o)}var p=class extends DatabaseError{migrationName;operation;constructor(i,n,t,r){let e=t==="up"?"MIGRATION_UP_FAILED":"MIGRATION_DOWN_FAILED";super(i,e,n),this.name="MigrationError",this.migrationName=n,this.operation=t,r&&(this.cause=r);}toJSON(){let i=this.cause instanceof Error?this.cause:void 0;return {...super.toJSON(),migrationName:this.migrationName,operation:this.operation,cause:i?.message}}};async function c(o){await o.schema.createTable("migrations").ifNotExists().addColumn("name","varchar(255)",i=>i.primaryKey()).addColumn("executed_at","timestamp",i=>i.notNull().defaultTo(sql`CURRENT_TIMESTAMP`)).execute();try{await o.schema.createIndex("idx_migrations_name").on("migrations").column("name").execute();}catch{}}function y(o){return "description"in o||"breaking"in o||"tags"in o}function m(o){return o instanceof Error?o.message:String(o)}function W(o){let i=new Set;for(let n of o){if(i.has(n.name))throw new BadRequestError(`Duplicate migration name: ${n.name}`);i.add(n.name);}}var l=class{logger;runnerOptions;db;migrations;constructor(i,n,t={}){let r=f.safeParse(t);if(!r.success)throw new BadRequestError(`Invalid migration runner options: ${r.error.message}`);this.db=i,this.migrations=n,this.logger=t.logger??silentLogger,this.runnerOptions={dryRun:r.data.dryRun,logger:this.logger,useTransactions:r.data.useTransactions,stopOnError:r.data.stopOnError,verbose:r.data.verbose},W(n);}async getExecutedMigrations(){return await c(this.db),(await this.db.selectFrom("migrations").select("name").orderBy("executed_at","asc").execute()).map(n=>n.name)}async markAsExecuted(i){await this.db.insertInto("migrations").values({name:i}).execute();}async markAsRolledBack(i){await this.db.deleteFrom("migrations").where("name","=",i).execute();}logMigrationMeta(i){if(!this.runnerOptions.verbose||!y(i))return;let n=i;if(n.description&&this.logger.info(` Description: ${n.description}`),n.breaking&&this.logger.warn(" BREAKING CHANGE - Review carefully before proceeding"),n.tags&&n.tags.length>0&&this.logger.info(` Tags: ${n.tags.join(", ")}`),n.estimatedDuration){let t=(n.estimatedDuration/1e3).toFixed(1);this.logger.info(` Estimated: ${t}s`);}}async executeMigration(i,n){let t=n==="up"?i.up:i.down;t&&(this.runnerOptions.useTransactions?await this.db.transaction().execute(async r=>{await t(r);}):await t(this.db));}async up(){let i=Date.now(),n={executed:[],skipped:[],failed:[],duration:0,dryRun:this.runnerOptions.dryRun};await c(this.db);let t=await this.getExecutedMigrations();if(this.migrations.filter(e=>!t.includes(e.name)).length===0)return this.logger.info("No pending migrations"),n.skipped=t,n.duration=Date.now()-i,n;this.runnerOptions.dryRun&&this.logger.info("DRY RUN - No changes will be made");for(let e of this.migrations){if(t.includes(e.name)){this.logger.info(`${e.name} (already executed)`),n.skipped.push(e.name);continue}try{this.logger.info(`Running ${e.name}...`),this.logMigrationMeta(e),this.runnerOptions.dryRun||(await this.executeMigration(e,"up"),await this.markAsExecuted(e.name)),this.logger.info(`${e.name} completed`),n.executed.push(e.name);}catch(g){let s=m(g);if(this.logger.error(`${e.name} failed: ${s}`),n.failed.push(e.name),this.runnerOptions.stopOnError)throw new p(`Migration ${e.name} failed: ${s}`,e.name,"up",g instanceof Error?g:void 0)}}return this.runnerOptions.dryRun?this.logger.info("Dry run completed - no changes made"):this.logger.info("All migrations completed successfully"),n.duration=Date.now()-i,n}async down(i=1){let n=Date.now(),t={executed:[],skipped:[],failed:[],duration:0,dryRun:this.runnerOptions.dryRun};await c(this.db);let r=await this.getExecutedMigrations();if(r.length===0)return this.logger.warn("No executed migrations to rollback"),t.duration=Date.now()-n,t;let e=r.slice(-i).reverse();this.runnerOptions.dryRun&&this.logger.info("DRY RUN - No changes will be made");for(let g of e){let s=this.migrations.find(u=>u.name===g);if(!s){this.logger.warn(`Migration ${g} not found in codebase`),t.skipped.push(g);continue}if(!s.down){this.logger.warn(`Migration ${g} has no down method - skipping`),t.skipped.push(g);continue}try{this.logger.info(`Rolling back ${g}...`),this.logMigrationMeta(s),this.runnerOptions.dryRun||(await this.executeMigration(s,"down"),await this.markAsRolledBack(g)),this.logger.info(`${g} rolled back`),t.executed.push(g);}catch(u){let d=m(u);if(this.logger.error(`${g} rollback failed: ${d}`),t.failed.push(g),this.runnerOptions.stopOnError)throw new p(`Rollback of ${g} failed: ${d}`,g,"down",u instanceof Error?u:void 0)}}return this.runnerOptions.dryRun?this.logger.info("Dry run completed - no changes made"):this.logger.info("Rollback completed successfully"),t.duration=Date.now()-n,t}async status(){await c(this.db);let i=await this.getExecutedMigrations(),n=this.migrations.filter(t=>!i.includes(t.name)).map(t=>t.name);if(this.logger.info("Migration Status:"),this.logger.info(` Executed: ${i.length}`),this.logger.info(` Pending: ${n.length}`),this.logger.info(` Total: ${this.migrations.length}`),i.length>0){this.logger.info("Executed migrations:");for(let t of i){let r=this.migrations.find(e=>e.name===t);r&&y(r)&&r.description?this.logger.info(` ${t} - ${r.description}`):this.logger.info(` ${t}`);}}if(n.length>0){this.logger.info("Pending migrations:");for(let t of n){let r=this.migrations.find(e=>e.name===t);if(r&&y(r)){let e=r,g=e.breaking?" BREAKING":"",s=e.description?` - ${e.description}`:"";this.logger.info(` ${t}${s}${g}`);}else this.logger.info(` ${t}`);}}return {executed:i,pending:n,total:this.migrations.length}}async reset(){let i=Date.now();await c(this.db);let n=await this.getExecutedMigrations();if(n.length===0)return this.logger.warn("No migrations to reset"),{executed:[],skipped:[],failed:[],duration:Date.now()-i,dryRun:this.runnerOptions.dryRun};if(this.logger.warn(`Resetting ${n.length} migrations...`),this.runnerOptions.dryRun){this.logger.info("DRY RUN - Would rollback the following migrations:");for(let r of [...n].reverse())this.migrations.find(g=>g.name===r)?.down?this.logger.info(` ${r}`):this.logger.warn(` ${r} (no down method - would be skipped)`);return this.logger.info("Dry run completed - no changes made"),{executed:[],skipped:n,failed:[],duration:Date.now()-i,dryRun:true}}let t=await this.down(n.length);return this.logger.info("All migrations reset"),t}async upTo(i){let n=Date.now(),t={executed:[],skipped:[],failed:[],duration:0,dryRun:this.runnerOptions.dryRun};await c(this.db);let r=await this.getExecutedMigrations(),e=this.migrations.findIndex(s=>s.name===i);if(e===-1)throw new NotFoundError("Migration",{name:i});let g=this.migrations.slice(0,e+1);this.runnerOptions.dryRun&&this.logger.info("DRY RUN - No changes will be made");for(let s of g){if(r.includes(s.name)){this.logger.info(`${s.name} (already executed)`),t.skipped.push(s.name);continue}try{this.logger.info(`Running ${s.name}...`),this.logMigrationMeta(s),this.runnerOptions.dryRun||(await this.executeMigration(s,"up"),await this.markAsExecuted(s.name)),this.logger.info(`${s.name} completed`),t.executed.push(s.name);}catch(u){let d=m(u);throw this.logger.error(`${s.name} failed: ${d}`),t.failed.push(s.name),new p(`Migration ${s.name} failed: ${d}`,s.name,"up",u instanceof Error?u:void 0)}}return this.runnerOptions.dryRun?this.logger.info(`Dry run completed - would migrate up to ${i}`):this.logger.info(`Migrated up to ${i}`),t.duration=Date.now()-n,t}};function G(o,i,n){return new l(o,i,n)}function q(o,i,n){let t={name:o,up:i};return n!==void 0&&(t.down=n),t}function C(o,i){let n={name:o,up:i.up};return i.down!==void 0&&(n.down=i.down),i.description!==void 0&&(n.description=i.description),i.breaking!==void 0&&(n.breaking=i.breaking),i.estimatedDuration!==void 0&&(n.estimatedDuration=i.estimatedDuration),i.tags!==void 0&&(n.tags=i.tags),n}function Y(o){return Object.entries(o).map(([i,n])=>{let t={name:i,up:n.up};return n.down!==void 0&&(t.down=n.down),n.description!==void 0&&(t.description=n.description),n.breaking!==void 0&&(t.breaking=n.breaking),n.estimatedDuration!==void 0&&(t.estimatedDuration=n.estimatedDuration),n.tags!==void 0&&(t.tags=n.tags),t})}async function V(o,i,n){return await new l(o,i,n).up()}async function J(o,i,n=1,t){return await new l(o,i,t).down(n)}async function Q(o,i,n){return await new l(o,i,n).status()}async function X(o,i,n){let t=new w(o,i,n);if(n?.plugins){for(let r of n.plugins)if(r.onInit){let e=r.onInit(t);e instanceof Promise&&await e;}}return t}var w=class extends l{plugins;constructor(i,n,t={}){super(i,n,t),this.plugins=t.plugins??[];}async runBeforeHooks(i,n){for(let t of this.plugins)t.beforeMigration&&await t.beforeMigration(i,n);}async runAfterHooks(i,n,t){for(let r of this.plugins)r.afterMigration&&await r.afterMigration(i,n,t);}async runErrorHooks(i,n,t){for(let r of this.plugins)r.onMigrationError&&await r.onMigrationError(i,n,t);}getPlugins(){return [...this.plugins]}async up(){let i=Date.now(),n={executed:[],skipped:[],failed:[],duration:0,dryRun:this.runnerOptions.dryRun};await c(this.db);let t=await this.getExecutedMigrations();if(this.migrations.filter(e=>!t.includes(e.name)).length===0)return this.logger.info("No pending migrations"),n.skipped=t,n.duration=Date.now()-i,n;this.runnerOptions.dryRun&&this.logger.info("DRY RUN - No changes will be made");for(let e of this.migrations){if(t.includes(e.name)){this.logger.info(`${e.name} (already executed)`),n.skipped.push(e.name);continue}let g=Date.now();try{await this.runBeforeHooks(e,"up"),this.logger.info(`Running ${e.name}...`),this.logMigrationMeta(e),this.runnerOptions.dryRun||(await this.executeMigration(e,"up"),await this.markAsExecuted(e.name));let s=Date.now()-g;await this.runAfterHooks(e,"up",s),this.logger.info(`${e.name} completed`),n.executed.push(e.name);}catch(s){await this.runErrorHooks(e,"up",s);let u=m(s);if(this.logger.error(`${e.name} failed: ${u}`),n.failed.push(e.name),this.runnerOptions.stopOnError)throw new p(`Migration ${e.name} failed: ${u}`,e.name,"up",s instanceof Error?s:void 0)}}return this.runnerOptions.dryRun?this.logger.info("Dry run completed - no changes made"):this.logger.info("All migrations completed successfully"),n.duration=Date.now()-i,n}async down(i=1){let n=Date.now(),t={executed:[],skipped:[],failed:[],duration:0,dryRun:this.runnerOptions.dryRun};await c(this.db);let r=await this.getExecutedMigrations();if(r.length===0)return this.logger.warn("No executed migrations to rollback"),t.duration=Date.now()-n,t;let e=r.slice(-i).reverse();this.runnerOptions.dryRun&&this.logger.info("DRY RUN - No changes will be made");for(let g of e){let s=this.migrations.find(d=>d.name===g);if(!s){this.logger.warn(`Migration ${g} not found in codebase`),t.skipped.push(g);continue}if(!s.down){this.logger.warn(`Migration ${g} has no down method - skipping`),t.skipped.push(g);continue}let u=Date.now();try{await this.runBeforeHooks(s,"down"),this.logger.info(`Rolling back ${g}...`),this.logMigrationMeta(s),this.runnerOptions.dryRun||(await this.executeMigration(s,"down"),await this.markAsRolledBack(g));let d=Date.now()-u;await this.runAfterHooks(s,"down",d),this.logger.info(`${g} rolled back`),t.executed.push(g);}catch(d){await this.runErrorHooks(s,"down",d);let D=m(d);if(this.logger.error(`${g} rollback failed: ${D}`),t.failed.push(g),this.runnerOptions.stopOnError)throw new p(`Rollback of ${g} failed: ${D}`,g,"down",d instanceof Error?d:void 0)}}return this.runnerOptions.dryRun?this.logger.info("Dry run completed - no changes made"):this.logger.info("Rollback completed successfully"),t.duration=Date.now()-n,t}};function Z(o=silentLogger){return {name:"@kysera/migrations/logging",version:h,beforeMigration(i,n){o.info(`Starting ${n} for ${i.name}`);},afterMigration(i,n,t){o.info(`Completed ${n} for ${i.name} in ${t}ms`);},onMigrationError(i,n,t){let r=t instanceof Error?t.message:String(t);o.error(`Error during ${n} for ${i.name}: ${r}`);}}}function nn(){let o=[];return {name:"@kysera/migrations/metrics",version:h,afterMigration(i,n,t){o.push({name:i.name,operation:n,duration:t,success:true});},onMigrationError(i,n){o.push({name:i.name,operation:n,duration:0,success:false});},getMetrics(){return {migrations:[...o]}}}}export{M as MigrationDefinitionSchema,p as MigrationError,B as MigrationPluginOptionsSchema,b as MigrationPluginSchema,E as MigrationResultSchema,l as MigrationRunner,f as MigrationRunnerOptionsSchema,w as MigrationRunnerWithPlugins,$ as MigrationRunnerWithPluginsOptionsSchema,P as MigrationStatusSchema,Z as createLoggingPlugin,nn as createMetricsPlugin,q as createMigration,G as createMigrationRunner,X as createMigrationRunnerWithPlugins,C as createMigrationWithMeta,Y as defineMigrations,Q as getMigrationStatus,I as parseMigrationDefinition,v as parseMigrationRunnerOptions,J as rollbackMigrations,V as runMigrations,N as safeParseMigrationDefinition,S as safeParseMigrationRunnerOptions,c as setupMigrations};//# sourceMappingURL=index.js.map
1
+ import {sql}from'kysely';import {ErrorCodes,silentLogger,DatabaseError,BadRequestError,NotFoundError}from'@kysera/core';export{BadRequestError,DatabaseError,NotFoundError,silentLogger}from'@kysera/core';import {z as z$1}from'zod';var R="__VERSION__",h=R.startsWith("__")?"0.0.0-dev":R;var b=z$1.object({trace:z$1.function(),debug:z$1.function(),info:z$1.function(),warn:z$1.function(),error:z$1.function(),fatal:z$1.function()}).passthrough(),d=z$1.object({dryRun:z$1.boolean().default(false),logger:b.optional(),useTransactions:z$1.boolean().default(false),stopOnError:z$1.boolean().default(true),verbose:z$1.boolean().default(true)}),M=z$1.object({name:z$1.string().min(1,"Migration name is required"),description:z$1.string().optional(),breaking:z$1.boolean().default(false),tags:z$1.array(z$1.string()).default([]),estimatedDuration:z$1.string().optional()}),E=z$1.object({logger:b.optional()}),x=z$1.object({name:z$1.string().min(1,"Plugin name is required"),version:z$1.string().min(1,"Plugin version is required"),onInit:z$1.function().optional(),beforeMigration:z$1.function().optional(),afterMigration:z$1.function().optional(),onMigrationError:z$1.function().optional()}),S=z$1.object({executed:z$1.array(z$1.string()),pending:z$1.array(z$1.string()),total:z$1.number().int().nonnegative()}),v=z$1.object({executed:z$1.array(z$1.string()),skipped:z$1.array(z$1.string()),failed:z$1.array(z$1.string()),duration:z$1.number().nonnegative(),dryRun:z$1.boolean()}),$=d.extend({plugins:z$1.array(x).optional()});function I(r){return d.parse(r)}function N(r){return d.safeParse(r)}function A(r){return M.parse(r)}function W(r){return M.safeParse(r)}var P={UP_FAILED:ErrorCodes.MIGRATION_UP_FAILED,DOWN_FAILED:ErrorCodes.MIGRATION_DOWN_FAILED,VALIDATION_FAILED:ErrorCodes.MIGRATION_VALIDATION_FAILED},f=class extends DatabaseError{migrationName;operation;constructor(i,n,t,e){let s=t==="up"?P.UP_FAILED:P.DOWN_FAILED;super(i,s,n),this.name="MigrationError",this.migrationName=n,this.operation=t,e&&(this.cause=e);}toJSON(){let i=this.cause instanceof Error?this.cause:void 0;return {...super.toJSON(),migrationName:this.migrationName,operation:this.operation,cause:i?.message}}};async function L(r){await r.schema.createTable("migrations").ifNotExists().addColumn("name","varchar(255)",i=>i.primaryKey()).addColumn("executed_at","timestamp",i=>i.notNull().defaultTo(sql`CURRENT_TIMESTAMP`)).execute();try{await r.schema.createIndex("idx_migrations_name").on("migrations").column("name").execute();}catch{}}function w(r){return "description"in r||"breaking"in r||"tags"in r}function B(r){return r instanceof Error?r.message:String(r)}function z(r){let i=new Set;for(let n of r){if(i.has(n.name))throw new BadRequestError(`Duplicate migration name: ${n.name}`);i.add(n.name);}}var c=class{logger;runnerOptions;db;migrations;setupDone=false;constructor(i,n,t={}){let e=d.safeParse(t);if(!e.success)throw new BadRequestError(`Invalid migration runner options: ${e.error.message}`);this.db=i,this.migrations=n,this.logger=t.logger??silentLogger,this.runnerOptions={dryRun:e.data.dryRun,logger:this.logger,useTransactions:e.data.useTransactions,stopOnError:e.data.stopOnError,verbose:e.data.verbose},z(n);}async ensureSetup(){this.setupDone||(await L(this.db),this.setupDone=true);}async getExecutedMigrations(){return await this.ensureSetup(),(await this.db.selectFrom("migrations").select("name").orderBy("executed_at","asc").execute()).map(n=>n.name)}async markAsExecuted(i){await this.db.insertInto("migrations").values({name:i}).execute();}async markAsRolledBack(i){await this.db.deleteFrom("migrations").where("name","=",i).execute();}logMigrationMeta(i){if(!this.runnerOptions.verbose||!w(i))return;let n=i;if(n.description&&this.logger.info(` Description: ${n.description}`),n.breaking&&this.logger.warn(" BREAKING CHANGE - Review carefully before proceeding"),n.tags&&n.tags.length>0&&this.logger.info(` Tags: ${n.tags.join(", ")}`),n.estimatedDuration){let t=(n.estimatedDuration/1e3).toFixed(1);this.logger.info(` Estimated: ${t}s`);}}async executeMigration(i,n){let t=n==="up"?i.up:i.down;t&&(this.runnerOptions.useTransactions?await this.db.transaction().execute(async e=>{await t(e);}):await t(this.db));}async up(){return this.runUp(this.migrations)}async runUp(i,n){let t=Date.now(),e={executed:[],skipped:[],failed:[],duration:0,dryRun:this.runnerOptions.dryRun},s=await this.getExecutedMigrations(),p=new Set(s);if(i.filter(a=>!p.has(a.name)).length===0)return this.logger.info("No pending migrations"),e.skipped=s,e.duration=Date.now()-t,e;this.runnerOptions.dryRun&&this.logger.info("DRY RUN - No changes will be made");for(let a of i){if(p.has(a.name)){this.logger.info(`${a.name} (already executed)`),e.skipped.push(a.name);continue}let m=Date.now();try{await n?.before?.(a),this.logger.info(`Running ${a.name}...`),this.logMigrationMeta(a),this.runnerOptions.dryRun||(await this.executeMigration(a,"up"),await this.markAsExecuted(a.name)),await n?.after?.(a,Date.now()-m),this.logger.info(`${a.name} completed`),e.executed.push(a.name);}catch(u){await n?.onError?.(a,u);let l=B(u);if(this.logger.error(`${a.name} failed: ${l}`),e.failed.push(a.name),this.runnerOptions.stopOnError)throw new f(`Migration ${a.name} failed: ${l}`,a.name,"up",u instanceof Error?u:void 0)}}return this.runnerOptions.dryRun?this.logger.info("Dry run completed - no changes made"):e.failed.length>0?this.logger.warn(`Migrations completed with ${String(e.failed.length)} failure(s)`):this.logger.info("All migrations completed successfully"),e.duration=Date.now()-t,e}async down(i=1){return this.runDown(i)}async runDown(i,n){let t=Date.now(),e={executed:[],skipped:[],failed:[],duration:0,dryRun:this.runnerOptions.dryRun},s=await this.getExecutedMigrations();if(s.length===0)return this.logger.warn("No executed migrations to rollback"),e.duration=Date.now()-t,e;let p=s.slice(-i).reverse();this.runnerOptions.dryRun&&this.logger.info("DRY RUN - No changes will be made");for(let g of p){let a=this.migrations.find(u=>u.name===g);if(!a){this.logger.warn(`Migration ${g} not found in codebase`),e.skipped.push(g);continue}if(!a.down){this.logger.warn(`Migration ${g} has no down method - skipping`),e.skipped.push(g);continue}let m=Date.now();try{await n?.before?.(a),this.logger.info(`Rolling back ${g}...`),this.logMigrationMeta(a),this.runnerOptions.dryRun||(await this.executeMigration(a,"down"),await this.markAsRolledBack(g)),await n?.after?.(a,Date.now()-m),this.logger.info(`${g} rolled back`),e.executed.push(g);}catch(u){await n?.onError?.(a,u);let l=B(u);if(this.logger.error(`${g} rollback failed: ${l}`),e.failed.push(g),this.runnerOptions.stopOnError)throw new f(`Rollback of ${g} failed: ${l}`,g,"down",u instanceof Error?u:void 0)}}return this.runnerOptions.dryRun?this.logger.info("Dry run completed - no changes made"):e.failed.length>0?this.logger.warn(`Rollback completed with ${String(e.failed.length)} failure(s)`):this.logger.info("Rollback completed successfully"),e.duration=Date.now()-t,e}async status(){await this.ensureSetup();let i=await this.getExecutedMigrations(),n=this.migrations.filter(t=>!i.includes(t.name)).map(t=>t.name);if(this.logger.info("Migration Status:"),this.logger.info(` Executed: ${i.length}`),this.logger.info(` Pending: ${n.length}`),this.logger.info(` Total: ${this.migrations.length}`),i.length>0){this.logger.info("Executed migrations:");for(let t of i){let e=this.migrations.find(s=>s.name===t);e&&w(e)&&e.description?this.logger.info(` ${t} - ${e.description}`):this.logger.info(` ${t}`);}}if(n.length>0){this.logger.info("Pending migrations:");for(let t of n){let e=this.migrations.find(s=>s.name===t);if(e&&w(e)){let s=e,p=s.breaking?" BREAKING":"",g=s.description?` - ${s.description}`:"";this.logger.info(` ${t}${g}${p}`);}else this.logger.info(` ${t}`);}}return {executed:i,pending:n,total:this.migrations.length}}async reset(){let i=Date.now();await this.ensureSetup();let n=await this.getExecutedMigrations();if(n.length===0)return this.logger.warn("No migrations to reset"),{executed:[],skipped:[],failed:[],duration:Date.now()-i,dryRun:this.runnerOptions.dryRun};if(this.logger.warn(`Resetting ${n.length} migrations...`),this.runnerOptions.dryRun){this.logger.info("DRY RUN - Would rollback the following migrations:");for(let e of [...n].reverse())this.migrations.find(p=>p.name===e)?.down?this.logger.info(` ${e}`):this.logger.warn(` ${e} (no down method - would be skipped)`);return this.logger.info("Dry run completed - no changes made"),{executed:[],skipped:n,failed:[],duration:Date.now()-i,dryRun:true}}let t=await this.down(n.length);return this.logger.info("All migrations reset"),t}async upTo(i){let n=this.migrations.findIndex(s=>s.name===i);if(n===-1)throw new NotFoundError("Migration",{name:i});let t=this.migrations.slice(0,n+1),e=await this.runUp(t);return !this.runnerOptions.dryRun&&e.failed.length===0&&this.logger.info(`Migrated up to ${i}`),e}};function V(r,i,n){return new c(r,i,n)}function Y(r,i,n){let t={name:r,up:i};return n!==void 0&&(t.down=n),t}function J(r,i){let n={name:r,up:i.up};return i.down!==void 0&&(n.down=i.down),i.description!==void 0&&(n.description=i.description),i.breaking!==void 0&&(n.breaking=i.breaking),i.estimatedDuration!==void 0&&(n.estimatedDuration=i.estimatedDuration),i.tags!==void 0&&(n.tags=i.tags),n}function Q(r){return Object.entries(r).map(([i,n])=>{let t={name:i,up:n.up};return n.down!==void 0&&(t.down=n.down),n.description!==void 0&&(t.description=n.description),n.breaking!==void 0&&(t.breaking=n.breaking),n.estimatedDuration!==void 0&&(t.estimatedDuration=n.estimatedDuration),n.tags!==void 0&&(t.tags=n.tags),t})}async function X(r,i,n){return await new c(r,i,n).up()}async function Z(r,i,n=1,t){return await new c(r,i,t).down(n)}async function nn(r,i,n){return await new c(r,i,n).status()}async function tn(r,i,n){let t=new D(r,i,n);if(n?.plugins){for(let e of n.plugins)if(e.onInit){let s=e.onInit(t);s instanceof Promise&&await s;}}return t}var D=class extends c{plugins;constructor(i,n,t={}){super(i,n,t),this.plugins=t.plugins??[];}async runBeforeHooks(i,n){for(let t of this.plugins)t.beforeMigration&&await t.beforeMigration(i,n);}async runAfterHooks(i,n,t){for(let e of this.plugins)e.afterMigration&&await e.afterMigration(i,n,t);}async runErrorHooks(i,n,t){for(let e of this.plugins)e.onMigrationError&&await e.onMigrationError(i,n,t);}getPlugins(){return [...this.plugins]}async up(){return this.runUp(this.migrations,{before:async i=>{await this.runBeforeHooks(i,"up");},after:async(i,n)=>{await this.runAfterHooks(i,"up",n);},onError:async(i,n)=>{await this.runErrorHooks(i,"up",n);}})}async down(i=1){return this.runDown(i,{before:async n=>{await this.runBeforeHooks(n,"down");},after:async(n,t)=>{await this.runAfterHooks(n,"down",t);},onError:async(n,t)=>{await this.runErrorHooks(n,"down",t);}})}};function en(r=silentLogger){return {name:"@kysera/migrations/logging",version:h,beforeMigration(i,n){r.info(`Starting ${n} for ${i.name}`);},afterMigration(i,n,t){r.info(`Completed ${n} for ${i.name} in ${t}ms`);},onMigrationError(i,n,t){let e=t instanceof Error?t.message:String(t);r.error(`Error during ${n} for ${i.name}: ${e}`);}}}function rn(){let r=[];return {name:"@kysera/migrations/metrics",version:h,afterMigration(i,n,t){r.push({name:i.name,operation:n,duration:t,success:true});},onMigrationError(i,n){r.push({name:i.name,operation:n,duration:0,success:false});},getMetrics(){return {migrations:[...r]}}}}export{M as MigrationDefinitionSchema,f as MigrationError,P as MigrationErrorCodes,E as MigrationPluginOptionsSchema,x as MigrationPluginSchema,v as MigrationResultSchema,c as MigrationRunner,d as MigrationRunnerOptionsSchema,D as MigrationRunnerWithPlugins,$ as MigrationRunnerWithPluginsOptionsSchema,S as MigrationStatusSchema,en as createLoggingPlugin,rn as createMetricsPlugin,Y as createMigration,V as createMigrationRunner,tn as createMigrationRunnerWithPlugins,J as createMigrationWithMeta,Q as defineMigrations,nn as getMigrationStatus,A as parseMigrationDefinition,I as parseMigrationRunnerOptions,Z as rollbackMigrations,X as runMigrations,W as safeParseMigrationDefinition,N as safeParseMigrationRunnerOptions,L as setupMigrations};//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/version.ts","../src/schemas.ts","../src/index.ts"],"names":["RAW_VERSION","VERSION","LoggerSchema","z","MigrationRunnerOptionsSchema","MigrationDefinitionSchema","MigrationPluginOptionsSchema","MigrationPluginSchema","MigrationStatusSchema","MigrationResultSchema","MigrationRunnerWithPluginsOptionsSchema","parseMigrationRunnerOptions","options","safeParseMigrationRunnerOptions","parseMigrationDefinition","definition","safeParseMigrationDefinition","MigrationError","DatabaseError","message","migrationName","operation","cause","code","causeError","setupMigrations","db","col","sql","hasMeta","migration","formatError","error","validateMigrations","migrations","names","BadRequestError","MigrationRunner","parsed","silentLogger","r","name","meta","seconds","fn","trx","startTime","result","executed","m","errorMsg","steps","toRollback","pending","suffix","desc","targetName","targetIndex","NotFoundError","migrationsToRun","createMigrationRunner","createMigration","up","down","createMigrationWithMeta","defineMigrations","definitions","def","runMigrations","rollbackMigrations","getMigrationStatus","createMigrationRunnerWithPlugins","runner","MigrationRunnerWithPlugins","plugin","duration","migrationStartTime","migrationDuration","createLoggingPlugin","logger","createMetricsPlugin","metrics"],"mappings":"oNAKA,IAAMA,CAAAA,CAAc,aAAA,CACPC,EAAUD,CAAAA,CAAY,UAAA,CAAW,IAAI,CAAA,CAAI,YAAcA,CAAAA,CCIpE,IAAME,CAAAA,CAAeC,CAAAA,CAClB,MAAA,CAAO,CACN,KAAA,CAAOA,CAAAA,CAAE,UAAS,CAClB,KAAA,CAAOA,EAAE,QAAA,EAAS,CAClB,IAAA,CAAMA,CAAAA,CAAE,UAAS,CACjB,IAAA,CAAMA,CAAAA,CAAE,QAAA,GACR,KAAA,CAAOA,CAAAA,CAAE,QAAA,EAAS,CAClB,MAAOA,CAAAA,CAAE,QAAA,EACX,CAAC,CAAA,CACA,aAAY,CAMFC,CAAAA,CAA+BD,CAAAA,CAAE,MAAA,CAAO,CAEnD,MAAA,CAAQA,CAAAA,CAAE,OAAA,EAAQ,CAAE,QAAQ,KAAK,CAAA,CAEjC,MAAA,CAAQD,CAAAA,CAAa,UAAS,CAE9B,eAAA,CAAiBC,EAAE,OAAA,EAAQ,CAAE,QAAQ,KAAK,CAAA,CAE1C,WAAA,CAAaA,CAAAA,CAAE,SAAQ,CAAE,OAAA,CAAQ,IAAI,CAAA,CAErC,QAASA,CAAAA,CAAE,OAAA,EAAQ,CAAE,OAAA,CAAQ,IAAI,CACnC,CAAC,EAUYE,CAAAA,CAA4BF,CAAAA,CAAE,OAAO,CAEhD,IAAA,CAAMA,CAAAA,CAAE,MAAA,GAAS,GAAA,CAAI,CAAA,CAAG,4BAA4B,CAAA,CAEpD,YAAaA,CAAAA,CAAE,MAAA,EAAO,CAAE,QAAA,GAExB,QAAA,CAAUA,CAAAA,CAAE,SAAQ,CAAE,OAAA,CAAQ,KAAK,CAAA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Q,CAAA,EAAA,CAAI,EAC7E,EACA,gBAAA,CAAiB7C,CAAAA,CAAWT,EAAWW,CAAAA,CAAO,CAC5C,IAAMb,CAAAA,CAAUa,CAAAA,YAAiB,KAAA,CAAQA,CAAAA,CAAM,QAAU,MAAA,CAAOA,CAAK,CAAA,CACrE+C,CAAAA,CAAO,MAAM,CAAA,aAAA,EAAgB1D,CAAS,CAAA,KAAA,EAAQS,CAAAA,CAAU,IAAI,CAAA,EAAA,EAAKX,CAAO,EAAE,EAC5E,CACF,CACF,CAMO,SAAS6D,EAAAA,EAId,CACA,IAAMC,CAAAA,CAAqF,EAAC,CAE5F,OAAO,CACL,IAAA,CAAM,4BAAA,CACN,OAAA,CAAShF,CAAAA,CACT,eAAe6B,CAAAA,CAAWT,CAAAA,CAAWsD,EAAU,CAC7CM,CAAAA,CAAQ,KAAK,CAAE,IAAA,CAAMnD,CAAAA,CAAU,IAAA,CAAM,UAAAT,CAAAA,CAAW,QAAA,CAAAsD,CAAAA,CAAU,OAAA,CAAS,IAAK,CAAC,EAC3E,CAAA,CACA,gBAAA,CAAiB7C,EAAWT,CAAAA,CAAW,CACrC4D,EAAQ,IAAA,CAAK,CAAE,KAAMnD,CAAAA,CAAU,IAAA,CAAM,SAAA,CAAAT,CAAAA,CAAW,SAAU,CAAA,CAAG,OAAA,CAAS,KAAM,CAAC,EAC/E,EACA,UAAA,EAAa,CACX,OAAO,CAAE,WAAY,CAAC,GAAG4D,CAAO,CAAE,CACpC,CACF,CACF","file":"index.js","sourcesContent":["/**\n * Package version - injected at build time by tsup\n * Falls back to '0.0.0-dev' if placeholder is not replaced\n * @internal\n */\nconst RAW_VERSION = '__VERSION__'\nexport const VERSION = RAW_VERSION.startsWith('__') ? '0.0.0-dev' : RAW_VERSION\n","import { z } from 'zod'\n\n// ============================================================================\n// Migration Runner Options Schema\n// ============================================================================\n\n/**\n * Schema for KyseraLogger interface.\n * Validates that an object has the required logger methods.\n */\nconst LoggerSchema = z\n .object({\n trace: z.function(),\n debug: z.function(),\n info: z.function(),\n warn: z.function(),\n error: z.function(),\n fatal: z.function()\n })\n .passthrough() // Allow additional properties\n\n/**\n * Schema for MigrationRunnerOptions\n * Validates configuration options for the migration runner\n */\nexport const MigrationRunnerOptionsSchema = z.object({\n /** Enable dry run mode (preview only, no changes) */\n dryRun: z.boolean().default(false),\n /** Logger implementing KyseraLogger interface from @kysera/core */\n logger: LoggerSchema.optional(),\n /** Wrap each migration in a transaction */\n useTransactions: z.boolean().default(false),\n /** Stop on first error */\n stopOnError: z.boolean().default(true),\n /** Show detailed metadata in logs */\n verbose: z.boolean().default(true)\n})\n\n// ============================================================================\n// Migration Definition Schema\n// ============================================================================\n\n/**\n * Schema for MigrationDefinition\n * Validates migration definition objects used with defineMigrations()\n */\nexport const MigrationDefinitionSchema = z.object({\n /** Migration name - must be non-empty */\n name: z.string().min(1, 'Migration name is required'),\n /** Human-readable description shown during migration */\n description: z.string().optional(),\n /** Whether this is a breaking change - shows warning before execution */\n breaking: z.boolean().default(false),\n /** Tags for categorization (e.g., ['schema', 'data', 'index']) */\n tags: z.array(z.string()).default([]),\n /** Estimated duration as human-readable string (e.g., '30s', '2m') */\n estimatedDuration: z.string().optional()\n})\n\n// ============================================================================\n// Migration Plugin Options Schema\n// ============================================================================\n\n/**\n * Schema for MigrationPluginOptions\n * Validates options passed to migration plugins\n */\nexport const MigrationPluginOptionsSchema = z.object({\n /** Optional logger for the plugin */\n logger: LoggerSchema.optional()\n})\n\n// ============================================================================\n// Migration Plugin Schema\n// ============================================================================\n\n/**\n * Schema for MigrationPlugin\n * Validates migration plugin structure.\n *\n * Note: Lifecycle hooks are validated as functions. Full type safety for\n * generic parameters (Migration<DB>) is provided by TypeScript interfaces.\n */\nexport const MigrationPluginSchema = z.object({\n /** Plugin name */\n name: z.string().min(1, 'Plugin name is required'),\n /** Plugin version */\n version: z.string().min(1, 'Plugin version is required'),\n /** Called once when the runner is initialized */\n onInit: z.function().optional(),\n /** Called before migration execution */\n beforeMigration: z.function().optional(),\n /** Called after successful migration execution */\n afterMigration: z.function().optional(),\n /** Called on migration error */\n onMigrationError: z.function().optional()\n})\n\n// ============================================================================\n// Migration Status Schema\n// ============================================================================\n\n/**\n * Schema for MigrationStatus\n * Validates migration status results\n */\nexport const MigrationStatusSchema = z.object({\n /** List of executed migration names */\n executed: z.array(z.string()),\n /** List of pending migration names */\n pending: z.array(z.string()),\n /** Total migration count */\n total: z.number().int().nonnegative()\n})\n\n// ============================================================================\n// Migration Result Schema\n// ============================================================================\n\n/**\n * Schema for MigrationResult\n * Validates results from migration runs\n */\nexport const MigrationResultSchema = z.object({\n /** Successfully executed migrations */\n executed: z.array(z.string()),\n /** Migrations that were skipped (already executed) */\n skipped: z.array(z.string()),\n /** Migrations that failed */\n failed: z.array(z.string()),\n /** Total duration in milliseconds */\n duration: z.number().nonnegative(),\n /** Whether the run was in dry-run mode */\n dryRun: z.boolean()\n})\n\n// ============================================================================\n// Extended Runner Options Schema (with plugins)\n// ============================================================================\n\n/**\n * Schema for MigrationRunnerWithPluginsOptions\n * Extends MigrationRunnerOptionsSchema with plugin support\n */\nexport const MigrationRunnerWithPluginsOptionsSchema = MigrationRunnerOptionsSchema.extend({\n /** Plugins to apply */\n plugins: z.array(MigrationPluginSchema).optional()\n})\n\n// ============================================================================\n// Type Exports\n// ============================================================================\n\n/** Input type for MigrationRunnerOptions - before defaults are applied */\nexport type MigrationRunnerOptionsInput = z.input<typeof MigrationRunnerOptionsSchema>\n\n/** Output type for MigrationRunnerOptions - after defaults are applied */\nexport type MigrationRunnerOptionsOutput = z.output<typeof MigrationRunnerOptionsSchema>\n\n/** Input type for MigrationDefinition - before defaults are applied */\nexport type MigrationDefinitionInput = z.input<typeof MigrationDefinitionSchema>\n\n/** Output type for MigrationDefinition - after defaults are applied */\nexport type MigrationDefinitionOutput = z.output<typeof MigrationDefinitionSchema>\n\n/** Input type for MigrationPluginOptions */\nexport type MigrationPluginOptionsInput = z.input<typeof MigrationPluginOptionsSchema>\n\n/** Output type for MigrationPluginOptions */\nexport type MigrationPluginOptionsOutput = z.output<typeof MigrationPluginOptionsSchema>\n\n/** Input type for MigrationPlugin */\nexport type MigrationPluginInput = z.input<typeof MigrationPluginSchema>\n\n/** Output type for MigrationPlugin */\nexport type MigrationPluginOutput = z.output<typeof MigrationPluginSchema>\n\n/** Type for MigrationStatus */\nexport type MigrationStatusType = z.infer<typeof MigrationStatusSchema>\n\n/** Type for MigrationResult */\nexport type MigrationResultType = z.infer<typeof MigrationResultSchema>\n\n/** Input type for MigrationRunnerWithPluginsOptions */\nexport type MigrationRunnerWithPluginsOptionsInput = z.input<\n typeof MigrationRunnerWithPluginsOptionsSchema\n>\n\n/** Output type for MigrationRunnerWithPluginsOptions */\nexport type MigrationRunnerWithPluginsOptionsOutput = z.output<\n typeof MigrationRunnerWithPluginsOptionsSchema\n>\n\n// ============================================================================\n// Validation Helpers\n// ============================================================================\n\n/**\n * Validate and parse MigrationRunnerOptions with defaults\n */\nexport function parseMigrationRunnerOptions(options: unknown): MigrationRunnerOptionsOutput {\n return MigrationRunnerOptionsSchema.parse(options)\n}\n\n/**\n * Safely validate MigrationRunnerOptions without throwing\n * Returns result with success boolean and either data or error\n */\nexport function safeParseMigrationRunnerOptions(options: unknown) {\n return MigrationRunnerOptionsSchema.safeParse(options)\n}\n\n/**\n * Validate and parse MigrationDefinition with defaults\n */\nexport function parseMigrationDefinition(definition: unknown): MigrationDefinitionOutput {\n return MigrationDefinitionSchema.parse(definition)\n}\n\n/**\n * Safely validate MigrationDefinition without throwing\n * Returns result with success boolean and either data or error\n */\nexport function safeParseMigrationDefinition(definition: unknown) {\n return MigrationDefinitionSchema.safeParse(definition)\n}\n","import type { Kysely } from 'kysely'\nimport { sql } from 'kysely'\nimport type { KyseraLogger } from '@kysera/core'\nimport { DatabaseError, NotFoundError, BadRequestError, silentLogger } from '@kysera/core'\nimport { VERSION } from './version.js'\n\n// ============================================================================\n// Schema Exports\n// ============================================================================\n\nexport {\n // Schemas\n MigrationRunnerOptionsSchema,\n MigrationDefinitionSchema,\n MigrationPluginOptionsSchema,\n MigrationPluginSchema,\n MigrationStatusSchema,\n MigrationResultSchema,\n MigrationRunnerWithPluginsOptionsSchema,\n // Type exports\n type MigrationRunnerOptionsInput,\n type MigrationRunnerOptionsOutput,\n type MigrationDefinitionInput,\n type MigrationDefinitionOutput,\n type MigrationPluginOptionsInput,\n type MigrationPluginOptionsOutput,\n type MigrationPluginInput,\n type MigrationPluginOutput,\n type MigrationStatusType,\n type MigrationResultType,\n type MigrationRunnerWithPluginsOptionsInput,\n type MigrationRunnerWithPluginsOptionsOutput,\n // Validation helpers\n parseMigrationRunnerOptions,\n safeParseMigrationRunnerOptions,\n parseMigrationDefinition,\n safeParseMigrationDefinition\n} from './schemas.js'\n\nimport { MigrationRunnerOptionsSchema } from './schemas.js'\n\n// ============================================================================\n// Types and Interfaces\n// ============================================================================\n\n/**\n * Migration interface - the core building block\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport interface Migration<DB = unknown> {\n /** Unique migration name (e.g., '001_create_users') */\n name: string\n /** Migration up function - creates/modifies schema */\n up: (db: Kysely<DB>) => Promise<void>\n /** Optional migration down function - reverts changes */\n down?: (db: Kysely<DB>) => Promise<void>\n}\n\n/**\n * Migration with metadata for enhanced logging and tracking\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport interface MigrationWithMeta<DB = unknown> extends Migration<DB> {\n /** Human-readable description shown during migration */\n description?: string\n /** Whether this is a breaking change - shows warning before execution */\n breaking?: boolean\n /** Estimated duration in milliseconds for progress indication */\n estimatedDuration?: number\n /** Tags for categorization (e.g., ['schema', 'data', 'index']) */\n tags?: string[]\n}\n\n/**\n * Migration status result\n */\nexport interface MigrationStatus {\n /** List of executed migration names */\n executed: string[]\n /** List of pending migration names */\n pending: string[]\n /** Total migration count */\n total: number\n}\n\n/**\n * Migration runner options\n */\nexport interface MigrationRunnerOptions {\n /** Enable dry run mode (preview only, no changes) */\n dryRun?: boolean\n /**\n * Logger for migration operations.\n * Uses KyseraLogger interface from @kysera/core.\n *\n * @default silentLogger (no output)\n */\n logger?: KyseraLogger\n /** Wrap each migration in a transaction (default: false) */\n useTransactions?: boolean\n /** Stop on first error (default: true) */\n stopOnError?: boolean\n /** Show detailed metadata in logs (default: true) */\n verbose?: boolean\n}\n\n/**\n * Object-based migration definition for Level 2 DX\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport interface MigrationDefinition<DB = unknown> {\n up: (db: Kysely<DB>) => Promise<void>\n down?: (db: Kysely<DB>) => Promise<void>\n description?: string\n breaking?: boolean\n estimatedDuration?: number\n tags?: string[]\n}\n\n/**\n * Migration definitions map for defineMigrations()\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport type MigrationDefinitions<DB = unknown> = Record<string, MigrationDefinition<DB>>\n\n/**\n * Result of a migration run\n */\nexport interface MigrationResult {\n /** Successfully executed migrations */\n executed: string[]\n /** Migrations that were skipped (already executed) */\n skipped: string[]\n /** Migrations that failed */\n failed: string[]\n /** Total duration in milliseconds */\n duration: number\n /** Whether the run was in dry-run mode */\n dryRun: boolean\n}\n\n// ============================================================================\n// Error Classes (extending @kysera/core)\n// ============================================================================\n\n/** Error codes for migration operations */\nexport type MigrationErrorCode =\n | 'MIGRATION_UP_FAILED'\n | 'MIGRATION_DOWN_FAILED'\n | 'MIGRATION_VALIDATION_FAILED'\n\n/**\n * Migration-specific error extending DatabaseError from @kysera/core\n * Provides structured error information with code, migration context, and cause tracking\n */\nexport class MigrationError extends DatabaseError {\n public readonly migrationName: string\n public readonly operation: 'up' | 'down'\n\n constructor(message: string, migrationName: string, operation: 'up' | 'down', cause?: Error) {\n const code: MigrationErrorCode =\n operation === 'up' ? 'MIGRATION_UP_FAILED' : 'MIGRATION_DOWN_FAILED'\n super(message, code, migrationName)\n this.name = 'MigrationError'\n this.migrationName = migrationName\n this.operation = operation\n if (cause) {\n this.cause = cause\n }\n }\n\n override toJSON(): Record<string, unknown> {\n const causeError = this.cause instanceof Error ? this.cause : undefined\n return {\n ...super.toJSON(),\n migrationName: this.migrationName,\n operation: this.operation,\n cause: causeError?.message\n }\n }\n}\n\n// ============================================================================\n// Setup Functions\n// ============================================================================\n\n/**\n * Setup migrations table in database\n * Idempotent - safe to run multiple times\n * Uses Kysely<unknown> as migrations work with any database schema\n */\nexport async function setupMigrations(db: Kysely<unknown>): Promise<void> {\n await db.schema\n .createTable('migrations')\n .ifNotExists()\n .addColumn('name', 'varchar(255)', col => col.primaryKey())\n .addColumn('executed_at', 'timestamp', col => col.notNull().defaultTo(sql`CURRENT_TIMESTAMP`))\n .execute()\n\n // Create index on name column for faster lookups\n // Using IF NOT EXISTS equivalent: ignore errors if index already exists\n try {\n await db.schema.createIndex('idx_migrations_name').on('migrations').column('name').execute()\n } catch (error) {\n // Index already exists or table doesn't support concurrent index creation\n // Safe to ignore as primary key provides index functionality\n }\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Check if migration has metadata\n * Type guard to narrow Migration<DB> to MigrationWithMeta<DB>\n */\nfunction hasMeta<DB>(migration: Migration<DB>): migration is MigrationWithMeta<DB> {\n return 'description' in migration || 'breaking' in migration || 'tags' in migration\n}\n\n/**\n * Format error message for logging\n */\nfunction formatError(error: unknown): string {\n if (error instanceof Error) {\n return error.message\n }\n return String(error)\n}\n\n/**\n * Validate migrations for duplicate names\n * @throws {BadRequestError} When duplicate migration names are found\n */\nfunction validateMigrations<DB>(migrations: Migration<DB>[]): void {\n const names = new Set<string>()\n for (const migration of migrations) {\n if (names.has(migration.name)) {\n throw new BadRequestError(`Duplicate migration name: ${migration.name}`)\n }\n names.add(migration.name)\n }\n}\n\n// ============================================================================\n// Migration Runner Class\n// ============================================================================\n\n/**\n * Migration runner with state tracking and metadata support\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport class MigrationRunner<DB = unknown> {\n protected logger: KyseraLogger\n protected runnerOptions: Required<Omit<MigrationRunnerOptions, 'logger'>> & {\n logger: KyseraLogger\n }\n protected db: Kysely<DB>\n protected migrations: Migration<DB>[]\n\n constructor(db: Kysely<DB>, migrations: Migration<DB>[], options: MigrationRunnerOptions = {}) {\n // Validate and apply defaults using Zod schema\n const parsed = MigrationRunnerOptionsSchema.safeParse(options)\n if (!parsed.success) {\n throw new BadRequestError(`Invalid migration runner options: ${parsed.error.message}`)\n }\n\n this.db = db\n this.migrations = migrations\n this.logger = options.logger ?? silentLogger\n this.runnerOptions = {\n dryRun: parsed.data.dryRun,\n logger: this.logger,\n useTransactions: parsed.data.useTransactions,\n stopOnError: parsed.data.stopOnError,\n verbose: parsed.data.verbose\n }\n\n // Validate migrations on construction\n validateMigrations(migrations)\n }\n\n /**\n * Get list of executed migrations from database\n * Note: Uses type assertions for migrations table as it's not part of the user schema\n */\n async getExecutedMigrations(): Promise<string[]> {\n // Cast to any for migrations table operations - it's internal and not part of user schema\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await setupMigrations(this.db as any)\n\n // The migrations table is internal and not part of the generic DB schema\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const rows = (await (this.db as any)\n .selectFrom('migrations')\n .select('name')\n .orderBy('executed_at', 'asc')\n .execute()) as { name: string }[]\n\n return rows.map(r => r.name)\n }\n\n /**\n * Mark a migration as executed\n * Note: Uses type assertions for migrations table as it's not part of the user schema\n */\n async markAsExecuted(name: string): Promise<void> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await (this.db as any).insertInto('migrations').values({ name }).execute()\n }\n\n /**\n * Mark a migration as rolled back (remove from executed list)\n * Note: Uses type assertions for migrations table as it's not part of the user schema\n */\n async markAsRolledBack(name: string): Promise<void> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await (this.db as any).deleteFrom('migrations').where('name', '=', name).execute()\n }\n\n /**\n * Log migration metadata if available\n */\n protected logMigrationMeta(migration: Migration<DB>): void {\n if (!this.runnerOptions.verbose || !hasMeta(migration)) return\n\n const meta = migration\n\n if (meta.description) {\n this.logger.info(` Description: ${meta.description}`)\n }\n\n if (meta.breaking) {\n this.logger.warn(` BREAKING CHANGE - Review carefully before proceeding`)\n }\n\n if (meta.tags && meta.tags.length > 0) {\n this.logger.info(` Tags: ${meta.tags.join(', ')}`)\n }\n\n if (meta.estimatedDuration) {\n const seconds = (meta.estimatedDuration / 1000).toFixed(1)\n this.logger.info(` Estimated: ${seconds}s`)\n }\n }\n\n /**\n * Execute a single migration with optional transaction wrapping\n */\n protected async executeMigration(\n migration: Migration<DB>,\n operation: 'up' | 'down'\n ): Promise<void> {\n const fn = operation === 'up' ? migration.up : migration.down\n if (!fn) return\n\n if (this.runnerOptions.useTransactions) {\n await this.db.transaction().execute(async trx => {\n await fn(trx)\n })\n } else {\n await fn(this.db)\n }\n }\n\n /**\n * Run all pending migrations\n */\n async up(): Promise<MigrationResult> {\n const startTime = Date.now()\n const result: MigrationResult = {\n executed: [],\n skipped: [],\n failed: [],\n duration: 0,\n dryRun: this.runnerOptions.dryRun\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await setupMigrations(this.db as any)\n const executed = await this.getExecutedMigrations()\n\n const pending = this.migrations.filter(m => !executed.includes(m.name))\n\n if (pending.length === 0) {\n this.logger.info('No pending migrations')\n result.skipped = executed\n result.duration = Date.now() - startTime\n return result\n }\n\n if (this.runnerOptions.dryRun) {\n this.logger.info('DRY RUN - No changes will be made')\n }\n\n for (const migration of this.migrations) {\n if (executed.includes(migration.name)) {\n this.logger.info(`${migration.name} (already executed)`)\n result.skipped.push(migration.name)\n continue\n }\n\n try {\n this.logger.info(`Running ${migration.name}...`)\n this.logMigrationMeta(migration)\n\n if (!this.runnerOptions.dryRun) {\n await this.executeMigration(migration, 'up')\n await this.markAsExecuted(migration.name)\n }\n\n this.logger.info(`${migration.name} completed`)\n result.executed.push(migration.name)\n } catch (error) {\n const errorMsg = formatError(error)\n this.logger.error(`${migration.name} failed: ${errorMsg}`)\n result.failed.push(migration.name)\n\n if (this.runnerOptions.stopOnError) {\n throw new MigrationError(\n `Migration ${migration.name} failed: ${errorMsg}`,\n migration.name,\n 'up',\n error instanceof Error ? error : undefined\n )\n }\n }\n }\n\n if (!this.runnerOptions.dryRun) {\n this.logger.info('All migrations completed successfully')\n } else {\n this.logger.info('Dry run completed - no changes made')\n }\n\n result.duration = Date.now() - startTime\n return result\n }\n\n /**\n * Rollback last N migrations\n */\n async down(steps = 1): Promise<MigrationResult> {\n const startTime = Date.now()\n const result: MigrationResult = {\n executed: [],\n skipped: [],\n failed: [],\n duration: 0,\n dryRun: this.runnerOptions.dryRun\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await setupMigrations(this.db as any)\n const executed = await this.getExecutedMigrations()\n\n if (executed.length === 0) {\n this.logger.warn('No executed migrations to rollback')\n result.duration = Date.now() - startTime\n return result\n }\n\n const toRollback = executed.slice(-steps).reverse()\n\n if (this.runnerOptions.dryRun) {\n this.logger.info('DRY RUN - No changes will be made')\n }\n\n for (const name of toRollback) {\n const migration = this.migrations.find(m => m.name === name)\n\n if (!migration) {\n this.logger.warn(`Migration ${name} not found in codebase`)\n result.skipped.push(name)\n continue\n }\n\n if (!migration.down) {\n this.logger.warn(`Migration ${name} has no down method - skipping`)\n result.skipped.push(name)\n continue\n }\n\n try {\n this.logger.info(`Rolling back ${name}...`)\n this.logMigrationMeta(migration)\n\n if (!this.runnerOptions.dryRun) {\n await this.executeMigration(migration, 'down')\n await this.markAsRolledBack(name)\n }\n\n this.logger.info(`${name} rolled back`)\n result.executed.push(name)\n } catch (error) {\n const errorMsg = formatError(error)\n this.logger.error(`${name} rollback failed: ${errorMsg}`)\n result.failed.push(name)\n\n if (this.runnerOptions.stopOnError) {\n throw new MigrationError(\n `Rollback of ${name} failed: ${errorMsg}`,\n name,\n 'down',\n error instanceof Error ? error : undefined\n )\n }\n }\n }\n\n if (!this.runnerOptions.dryRun) {\n this.logger.info('Rollback completed successfully')\n } else {\n this.logger.info('Dry run completed - no changes made')\n }\n\n result.duration = Date.now() - startTime\n return result\n }\n\n /**\n * Show migration status\n */\n async status(): Promise<MigrationStatus> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await setupMigrations(this.db as any)\n const executed = await this.getExecutedMigrations()\n const pending = this.migrations.filter(m => !executed.includes(m.name)).map(m => m.name)\n\n this.logger.info('Migration Status:')\n this.logger.info(` Executed: ${executed.length}`)\n this.logger.info(` Pending: ${pending.length}`)\n this.logger.info(` Total: ${this.migrations.length}`)\n\n if (executed.length > 0) {\n this.logger.info('Executed migrations:')\n for (const name of executed) {\n const migration = this.migrations.find(m => m.name === name)\n if (migration && hasMeta(migration) && (migration as MigrationWithMeta).description) {\n this.logger.info(` ${name} - ${(migration as MigrationWithMeta).description}`)\n } else {\n this.logger.info(` ${name}`)\n }\n }\n }\n\n if (pending.length > 0) {\n this.logger.info('Pending migrations:')\n for (const name of pending) {\n const migration = this.migrations.find(m => m.name === name)\n if (migration && hasMeta(migration)) {\n const meta = migration as MigrationWithMeta\n const suffix = meta.breaking ? ' BREAKING' : ''\n const desc = meta.description ? ` - ${meta.description}` : ''\n this.logger.info(` ${name}${desc}${suffix}`)\n } else {\n this.logger.info(` ${name}`)\n }\n }\n }\n\n return { executed, pending, total: this.migrations.length }\n }\n\n /**\n * Reset all migrations (dangerous!)\n * In dry run mode, shows what would be rolled back\n */\n async reset(): Promise<MigrationResult> {\n const startTime = Date.now()\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await setupMigrations(this.db as any)\n const executed = await this.getExecutedMigrations()\n\n if (executed.length === 0) {\n this.logger.warn('No migrations to reset')\n return {\n executed: [],\n skipped: [],\n failed: [],\n duration: Date.now() - startTime,\n dryRun: this.runnerOptions.dryRun\n }\n }\n\n this.logger.warn(`Resetting ${executed.length} migrations...`)\n\n if (this.runnerOptions.dryRun) {\n this.logger.info('DRY RUN - Would rollback the following migrations:')\n for (const name of [...executed].reverse()) {\n const migration = this.migrations.find(m => m.name === name)\n if (!migration?.down) {\n this.logger.warn(` ${name} (no down method - would be skipped)`)\n } else {\n this.logger.info(` ${name}`)\n }\n }\n this.logger.info('Dry run completed - no changes made')\n return {\n executed: [],\n skipped: executed,\n failed: [],\n duration: Date.now() - startTime,\n dryRun: true\n }\n }\n\n const result = await this.down(executed.length)\n this.logger.info('All migrations reset')\n return result\n }\n\n /**\n * Run migrations up to a specific migration (inclusive)\n */\n async upTo(targetName: string): Promise<MigrationResult> {\n const startTime = Date.now()\n const result: MigrationResult = {\n executed: [],\n skipped: [],\n failed: [],\n duration: 0,\n dryRun: this.runnerOptions.dryRun\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await setupMigrations(this.db as any)\n const executed = await this.getExecutedMigrations()\n\n const targetIndex = this.migrations.findIndex(m => m.name === targetName)\n if (targetIndex === -1) {\n throw new NotFoundError('Migration', { name: targetName })\n }\n\n const migrationsToRun = this.migrations.slice(0, targetIndex + 1)\n\n if (this.runnerOptions.dryRun) {\n this.logger.info('DRY RUN - No changes will be made')\n }\n\n for (const migration of migrationsToRun) {\n if (executed.includes(migration.name)) {\n this.logger.info(`${migration.name} (already executed)`)\n result.skipped.push(migration.name)\n continue\n }\n\n try {\n this.logger.info(`Running ${migration.name}...`)\n this.logMigrationMeta(migration)\n\n if (!this.runnerOptions.dryRun) {\n await this.executeMigration(migration, 'up')\n await this.markAsExecuted(migration.name)\n }\n\n this.logger.info(`${migration.name} completed`)\n result.executed.push(migration.name)\n } catch (error) {\n const errorMsg = formatError(error)\n this.logger.error(`${migration.name} failed: ${errorMsg}`)\n result.failed.push(migration.name)\n\n throw new MigrationError(\n `Migration ${migration.name} failed: ${errorMsg}`,\n migration.name,\n 'up',\n error instanceof Error ? error : undefined\n )\n }\n }\n\n if (!this.runnerOptions.dryRun) {\n this.logger.info(`Migrated up to ${targetName}`)\n } else {\n this.logger.info(`Dry run completed - would migrate up to ${targetName}`)\n }\n\n result.duration = Date.now() - startTime\n return result\n }\n}\n\n// ============================================================================\n// Factory Functions\n// ============================================================================\n\n/**\n * Create a migration runner instance\n * Options are validated using Zod schema\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport function createMigrationRunner<DB = unknown>(\n db: Kysely<DB>,\n migrations: Migration<DB>[],\n options?: MigrationRunnerOptions\n): MigrationRunner<DB> {\n return new MigrationRunner(db, migrations, options)\n}\n\n/**\n * Helper to create a simple migration\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport function createMigration<DB = unknown>(\n name: string,\n up: (db: Kysely<DB>) => Promise<void>,\n down?: (db: Kysely<DB>) => Promise<void>\n): Migration<DB> {\n const migration: Migration<DB> = { name, up }\n if (down !== undefined) {\n migration.down = down\n }\n return migration\n}\n\n/**\n * Helper to create a migration with metadata\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport function createMigrationWithMeta<DB = unknown>(\n name: string,\n options: {\n up: (db: Kysely<DB>) => Promise<void>\n down?: (db: Kysely<DB>) => Promise<void>\n description?: string\n breaking?: boolean\n estimatedDuration?: number\n tags?: string[]\n }\n): MigrationWithMeta<DB> {\n const migration: MigrationWithMeta<DB> = {\n name,\n up: options.up\n }\n if (options.down !== undefined) {\n migration.down = options.down\n }\n if (options.description !== undefined) {\n migration.description = options.description\n }\n if (options.breaking !== undefined) {\n migration.breaking = options.breaking\n }\n if (options.estimatedDuration !== undefined) {\n migration.estimatedDuration = options.estimatedDuration\n }\n if (options.tags !== undefined) {\n migration.tags = options.tags\n }\n return migration\n}\n\n// ============================================================================\n// Level 2: Developer Experience APIs\n// ============================================================================\n\n/**\n * Define migrations using an object-based syntax for cleaner code\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport function defineMigrations<DB = unknown>(\n definitions: MigrationDefinitions<DB>\n): MigrationWithMeta<DB>[] {\n return Object.entries(definitions).map(([name, def]) => {\n const migration: MigrationWithMeta<DB> = {\n name,\n up: def.up\n }\n if (def.down !== undefined) {\n migration.down = def.down\n }\n if (def.description !== undefined) {\n migration.description = def.description\n }\n if (def.breaking !== undefined) {\n migration.breaking = def.breaking\n }\n if (def.estimatedDuration !== undefined) {\n migration.estimatedDuration = def.estimatedDuration\n }\n if (def.tags !== undefined) {\n migration.tags = def.tags\n }\n return migration\n })\n}\n\n/**\n * Run all pending migrations - one-liner convenience function\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport async function runMigrations<DB = unknown>(\n db: Kysely<DB>,\n migrations: Migration<DB>[],\n options?: MigrationRunnerOptions\n): Promise<MigrationResult> {\n const runner = new MigrationRunner(db, migrations, options)\n return await runner.up()\n}\n\n/**\n * Rollback migrations - one-liner convenience function\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport async function rollbackMigrations<DB = unknown>(\n db: Kysely<DB>,\n migrations: Migration<DB>[],\n steps = 1,\n options?: MigrationRunnerOptions\n): Promise<MigrationResult> {\n const runner = new MigrationRunner(db, migrations, options)\n return await runner.down(steps)\n}\n\n/**\n * Get migration status - one-liner convenience function\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport async function getMigrationStatus<DB = unknown>(\n db: Kysely<DB>,\n migrations: Migration<DB>[],\n options?: Pick<MigrationRunnerOptions, 'logger' | 'verbose'>\n): Promise<MigrationStatus> {\n const runner = new MigrationRunner(db, migrations, options)\n return await runner.status()\n}\n\n// ============================================================================\n// Level 3: Ecosystem Integration\n// ============================================================================\n\n/**\n * Migration plugin interface - consistent with @kysera/repository Plugin\n * Provides lifecycle hooks for migration execution\n * Generic DB type allows type-safe plugins when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport interface MigrationPlugin<DB = unknown> {\n /** Plugin name */\n name: string\n /** Plugin version */\n version: string\n /** Called once when the runner is initialized (consistent with repository Plugin.onInit) */\n onInit?(runner: MigrationRunner<DB>): Promise<void> | void\n /** Called before migration execution */\n beforeMigration?(migration: Migration<DB>, operation: 'up' | 'down'): Promise<void> | void\n /** Called after successful migration execution */\n afterMigration?(\n migration: Migration<DB>,\n operation: 'up' | 'down',\n duration: number\n ): Promise<void> | void\n /** Called on migration error (unknown type for consistency with repository Plugin.onError) */\n onMigrationError?(\n migration: Migration<DB>,\n operation: 'up' | 'down',\n error: unknown\n ): Promise<void> | void\n}\n\n/**\n * Extended migration runner options with plugin support\n * Generic DB type allows type-safe plugins when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport interface MigrationRunnerWithPluginsOptions<DB = unknown> extends MigrationRunnerOptions {\n /** Plugins to apply */\n plugins?: MigrationPlugin<DB>[]\n}\n\n/**\n * Create a migration runner with plugin support\n * Async factory to properly initialize plugins (consistent with @kysera/repository createORM)\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport async function createMigrationRunnerWithPlugins<DB = unknown>(\n db: Kysely<DB>,\n migrations: Migration<DB>[],\n options?: MigrationRunnerWithPluginsOptions<DB>\n): Promise<MigrationRunnerWithPlugins<DB>> {\n const runner = new MigrationRunnerWithPlugins(db, migrations, options)\n\n // Initialize plugins (consistent with repository Plugin.onInit pattern)\n if (options?.plugins) {\n for (const plugin of options.plugins) {\n if (plugin.onInit) {\n const result = plugin.onInit(runner)\n if (result instanceof Promise) {\n await result\n }\n }\n }\n }\n\n return runner\n}\n\n/**\n * Extended migration runner with plugin support\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n *\n * This class overrides up() and down() to call plugin lifecycle hooks\n * (beforeMigration, afterMigration, onMigrationError) around each migration execution.\n */\nexport class MigrationRunnerWithPlugins<DB = unknown> extends MigrationRunner<DB> {\n private plugins: MigrationPlugin<DB>[]\n\n constructor(\n db: Kysely<DB>,\n migrations: Migration<DB>[],\n options: MigrationRunnerWithPluginsOptions<DB> = {}\n ) {\n super(db, migrations, options)\n this.plugins = options.plugins ?? []\n }\n\n /**\n * Execute plugin hooks before migration\n * Can be called by consumers extending this class\n */\n protected async runBeforeHooks(\n migration: Migration<DB>,\n operation: 'up' | 'down'\n ): Promise<void> {\n for (const plugin of this.plugins) {\n if (plugin.beforeMigration) {\n await plugin.beforeMigration(migration, operation)\n }\n }\n }\n\n /**\n * Execute plugin hooks after migration\n * Can be called by consumers extending this class\n */\n protected async runAfterHooks(\n migration: Migration<DB>,\n operation: 'up' | 'down',\n duration: number\n ): Promise<void> {\n for (const plugin of this.plugins) {\n if (plugin.afterMigration) {\n await plugin.afterMigration(migration, operation, duration)\n }\n }\n }\n\n /**\n * Execute plugin hooks on error\n * Can be called by consumers extending this class\n */\n protected async runErrorHooks(\n migration: Migration<DB>,\n operation: 'up' | 'down',\n error: unknown\n ): Promise<void> {\n for (const plugin of this.plugins) {\n if (plugin.onMigrationError) {\n await plugin.onMigrationError(migration, operation, error)\n }\n }\n }\n\n /**\n * Get the list of registered plugins\n */\n getPlugins(): MigrationPlugin<DB>[] {\n return [...this.plugins]\n }\n\n /**\n * Run all pending migrations with plugin hooks\n * Overrides parent to call beforeMigration/afterMigration/onMigrationError hooks\n */\n override async up(): Promise<MigrationResult> {\n const startTime = Date.now()\n const result: MigrationResult = {\n executed: [],\n skipped: [],\n failed: [],\n duration: 0,\n dryRun: this.runnerOptions.dryRun\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await setupMigrations(this.db as any)\n const executed = await this.getExecutedMigrations()\n\n const pending = this.migrations.filter(m => !executed.includes(m.name))\n\n if (pending.length === 0) {\n this.logger.info('No pending migrations')\n result.skipped = executed\n result.duration = Date.now() - startTime\n return result\n }\n\n if (this.runnerOptions.dryRun) {\n this.logger.info('DRY RUN - No changes will be made')\n }\n\n for (const migration of this.migrations) {\n if (executed.includes(migration.name)) {\n this.logger.info(`${migration.name} (already executed)`)\n result.skipped.push(migration.name)\n continue\n }\n\n const migrationStartTime = Date.now()\n\n try {\n // Call beforeMigration hooks\n await this.runBeforeHooks(migration, 'up')\n\n this.logger.info(`Running ${migration.name}...`)\n this.logMigrationMeta(migration)\n\n if (!this.runnerOptions.dryRun) {\n await this.executeMigration(migration, 'up')\n await this.markAsExecuted(migration.name)\n }\n\n const migrationDuration = Date.now() - migrationStartTime\n\n // Call afterMigration hooks\n await this.runAfterHooks(migration, 'up', migrationDuration)\n\n this.logger.info(`${migration.name} completed`)\n result.executed.push(migration.name)\n } catch (error) {\n // Call onMigrationError hooks\n await this.runErrorHooks(migration, 'up', error)\n\n const errorMsg = formatError(error)\n this.logger.error(`${migration.name} failed: ${errorMsg}`)\n result.failed.push(migration.name)\n\n if (this.runnerOptions.stopOnError) {\n throw new MigrationError(\n `Migration ${migration.name} failed: ${errorMsg}`,\n migration.name,\n 'up',\n error instanceof Error ? error : undefined\n )\n }\n }\n }\n\n if (!this.runnerOptions.dryRun) {\n this.logger.info('All migrations completed successfully')\n } else {\n this.logger.info('Dry run completed - no changes made')\n }\n\n result.duration = Date.now() - startTime\n return result\n }\n\n /**\n * Rollback last N migrations with plugin hooks\n * Overrides parent to call beforeMigration/afterMigration/onMigrationError hooks\n */\n override async down(steps = 1): Promise<MigrationResult> {\n const startTime = Date.now()\n const result: MigrationResult = {\n executed: [],\n skipped: [],\n failed: [],\n duration: 0,\n dryRun: this.runnerOptions.dryRun\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await setupMigrations(this.db as any)\n const executed = await this.getExecutedMigrations()\n\n if (executed.length === 0) {\n this.logger.warn('No executed migrations to rollback')\n result.duration = Date.now() - startTime\n return result\n }\n\n const toRollback = executed.slice(-steps).reverse()\n\n if (this.runnerOptions.dryRun) {\n this.logger.info('DRY RUN - No changes will be made')\n }\n\n for (const name of toRollback) {\n const migration = this.migrations.find(m => m.name === name)\n\n if (!migration) {\n this.logger.warn(`Migration ${name} not found in codebase`)\n result.skipped.push(name)\n continue\n }\n\n if (!migration.down) {\n this.logger.warn(`Migration ${name} has no down method - skipping`)\n result.skipped.push(name)\n continue\n }\n\n const migrationStartTime = Date.now()\n\n try {\n // Call beforeMigration hooks\n await this.runBeforeHooks(migration, 'down')\n\n this.logger.info(`Rolling back ${name}...`)\n this.logMigrationMeta(migration)\n\n if (!this.runnerOptions.dryRun) {\n await this.executeMigration(migration, 'down')\n await this.markAsRolledBack(name)\n }\n\n const migrationDuration = Date.now() - migrationStartTime\n\n // Call afterMigration hooks\n await this.runAfterHooks(migration, 'down', migrationDuration)\n\n this.logger.info(`${name} rolled back`)\n result.executed.push(name)\n } catch (error) {\n // Call onMigrationError hooks\n await this.runErrorHooks(migration, 'down', error)\n\n const errorMsg = formatError(error)\n this.logger.error(`${name} rollback failed: ${errorMsg}`)\n result.failed.push(name)\n\n if (this.runnerOptions.stopOnError) {\n throw new MigrationError(\n `Rollback of ${name} failed: ${errorMsg}`,\n name,\n 'down',\n error instanceof Error ? error : undefined\n )\n }\n }\n }\n\n if (!this.runnerOptions.dryRun) {\n this.logger.info('Rollback completed successfully')\n } else {\n this.logger.info('Dry run completed - no changes made')\n }\n\n result.duration = Date.now() - startTime\n return result\n }\n}\n\n// ============================================================================\n// Built-in Plugins\n// ============================================================================\n\n/**\n * Logging plugin - logs migration events with timing\n * Works with any DB type (generic plugin)\n */\nexport function createLoggingPlugin<DB = unknown>(\n logger: KyseraLogger = silentLogger\n): MigrationPlugin<DB> {\n return {\n name: '@kysera/migrations/logging',\n version: VERSION,\n beforeMigration(migration, operation) {\n logger.info(`Starting ${operation} for ${migration.name}`)\n },\n afterMigration(migration, operation, duration) {\n logger.info(`Completed ${operation} for ${migration.name} in ${duration}ms`)\n },\n onMigrationError(migration, operation, error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.error(`Error during ${operation} for ${migration.name}: ${message}`)\n }\n }\n}\n\n/**\n * Metrics plugin - collects migration metrics\n * Works with any DB type (generic plugin)\n */\nexport function createMetricsPlugin<DB = unknown>(): MigrationPlugin<DB> & {\n getMetrics(): {\n migrations: { name: string; operation: string; duration: number; success: boolean }[]\n }\n} {\n const metrics: { name: string; operation: string; duration: number; success: boolean }[] = []\n\n return {\n name: '@kysera/migrations/metrics',\n version: VERSION,\n afterMigration(migration, operation, duration) {\n metrics.push({ name: migration.name, operation, duration, success: true })\n },\n onMigrationError(migration, operation) {\n metrics.push({ name: migration.name, operation, duration: 0, success: false })\n },\n getMetrics() {\n return { migrations: [...metrics] }\n }\n }\n}\n\n// ============================================================================\n// Re-exports from @kysera/core for convenience\n// ============================================================================\n\nexport { DatabaseError, NotFoundError, BadRequestError, silentLogger } from '@kysera/core'\nexport type { KyseraLogger } from '@kysera/core'\n"]}
1
+ {"version":3,"sources":["../src/version.ts","../src/schemas.ts","../src/index.ts"],"names":["RAW_VERSION","VERSION","LoggerSchema","z","MigrationRunnerOptionsSchema","MigrationDefinitionSchema","MigrationPluginOptionsSchema","MigrationPluginSchema","MigrationStatusSchema","MigrationResultSchema","MigrationRunnerWithPluginsOptionsSchema","parseMigrationRunnerOptions","options","safeParseMigrationRunnerOptions","parseMigrationDefinition","definition","safeParseMigrationDefinition","MigrationErrorCodes","ErrorCodes","MigrationError","DatabaseError","message","migrationName","operation","cause","code","causeError","setupMigrations","db","col","sql","hasMeta","migration","formatError","error","validateMigrations","migrations","names","BadRequestError","MigrationRunner","parsed","silentLogger","r","name","meta","seconds","fn","trx","migrationsToConsider","hooks","startTime","result","executedList","executedSet","m","migrationStart","errorMsg","steps","executed","toRollback","pending","suffix","desc","targetName","targetIndex","NotFoundError","migrationsToRun","createMigrationRunner","createMigration","up","down","createMigrationWithMeta","defineMigrations","definitions","def","runMigrations","rollbackMigrations","getMigrationStatus","createMigrationRunnerWithPlugins","runner","MigrationRunnerWithPlugins","plugin","duration","createLoggingPlugin","logger","createMetricsPlugin","metrics"],"mappings":"sOAKA,IAAMA,CAAAA,CAAc,aAAA,CACPC,CAAAA,CAAUD,CAAAA,CAAY,UAAA,CAAW,IAAI,CAAA,CAAI,WAAA,CAAcA,CAAAA,CCIp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CAAE,IAAA,CAAMtD,CAAAA,CAAU,IAAA,CAAM,SAAA,CAAAT,EAAW,QAAA,CAAU,CAAA,CAAG,OAAA,CAAS,KAAM,CAAC,EAC/E,CAAA,CACA,UAAA,EAAa,CACX,OAAO,CAAE,UAAA,CAAY,CAAC,GAAG+D,CAAO,CAAE,CACpC,CACF,CACF","file":"index.js","sourcesContent":["/**\n * Package version - injected at build time by tsup\n * Falls back to '0.0.0-dev' if placeholder is not replaced\n * @internal\n */\nconst RAW_VERSION = '__VERSION__'\nexport const VERSION = RAW_VERSION.startsWith('__') ? '0.0.0-dev' : RAW_VERSION\n","import { z } from 'zod'\n\n// ============================================================================\n// Migration Runner Options Schema\n// ============================================================================\n\n/**\n * Schema for KyseraLogger interface.\n * Validates that an object has the required logger methods.\n */\nconst LoggerSchema = z\n .object({\n trace: z.function(),\n debug: z.function(),\n info: z.function(),\n warn: z.function(),\n error: z.function(),\n fatal: z.function()\n })\n .passthrough() // Allow additional properties\n\n/**\n * Schema for MigrationRunnerOptions\n * Validates configuration options for the migration runner\n */\nexport const MigrationRunnerOptionsSchema = z.object({\n /** Enable dry run mode (preview only, no changes) */\n dryRun: z.boolean().default(false),\n /** Logger implementing KyseraLogger interface from @kysera/core */\n logger: LoggerSchema.optional(),\n /** Wrap each migration in a transaction */\n useTransactions: z.boolean().default(false),\n /** Stop on first error */\n stopOnError: z.boolean().default(true),\n /** Show detailed metadata in logs */\n verbose: z.boolean().default(true)\n})\n\n// ============================================================================\n// Migration Definition Schema\n// ============================================================================\n\n/**\n * Schema for MigrationDefinition\n * Validates migration definition objects used with defineMigrations()\n */\nexport const MigrationDefinitionSchema = z.object({\n /** Migration name - must be non-empty */\n name: z.string().min(1, 'Migration name is required'),\n /** Human-readable description shown during migration */\n description: z.string().optional(),\n /** Whether this is a breaking change - shows warning before execution */\n breaking: z.boolean().default(false),\n /** Tags for categorization (e.g., ['schema', 'data', 'index']) */\n tags: z.array(z.string()).default([]),\n /** Estimated duration as human-readable string (e.g., '30s', '2m') */\n estimatedDuration: z.string().optional()\n})\n\n// ============================================================================\n// Migration Plugin Options Schema\n// ============================================================================\n\n/**\n * Schema for MigrationPluginOptions\n * Validates options passed to migration plugins\n */\nexport const MigrationPluginOptionsSchema = z.object({\n /** Optional logger for the plugin */\n logger: LoggerSchema.optional()\n})\n\n// ============================================================================\n// Migration Plugin Schema\n// ============================================================================\n\n/**\n * Schema for MigrationPlugin\n * Validates migration plugin structure.\n *\n * Note: Lifecycle hooks are validated as functions. Full type safety for\n * generic parameters (Migration<DB>) is provided by TypeScript interfaces.\n */\nexport const MigrationPluginSchema = z.object({\n /** Plugin name */\n name: z.string().min(1, 'Plugin name is required'),\n /** Plugin version */\n version: z.string().min(1, 'Plugin version is required'),\n /** Called once when the runner is initialized */\n onInit: z.function().optional(),\n /** Called before migration execution */\n beforeMigration: z.function().optional(),\n /** Called after successful migration execution */\n afterMigration: z.function().optional(),\n /** Called on migration error */\n onMigrationError: z.function().optional()\n})\n\n// ============================================================================\n// Migration Status Schema\n// ============================================================================\n\n/**\n * Schema for MigrationStatus\n * Validates migration status results\n */\nexport const MigrationStatusSchema = z.object({\n /** List of executed migration names */\n executed: z.array(z.string()),\n /** List of pending migration names */\n pending: z.array(z.string()),\n /** Total migration count */\n total: z.number().int().nonnegative()\n})\n\n// ============================================================================\n// Migration Result Schema\n// ============================================================================\n\n/**\n * Schema for MigrationResult\n * Validates results from migration runs\n */\nexport const MigrationResultSchema = z.object({\n /** Successfully executed migrations */\n executed: z.array(z.string()),\n /** Migrations that were skipped (already executed) */\n skipped: z.array(z.string()),\n /** Migrations that failed */\n failed: z.array(z.string()),\n /** Total duration in milliseconds */\n duration: z.number().nonnegative(),\n /** Whether the run was in dry-run mode */\n dryRun: z.boolean()\n})\n\n// ============================================================================\n// Extended Runner Options Schema (with plugins)\n// ============================================================================\n\n/**\n * Schema for MigrationRunnerWithPluginsOptions\n * Extends MigrationRunnerOptionsSchema with plugin support\n */\nexport const MigrationRunnerWithPluginsOptionsSchema = MigrationRunnerOptionsSchema.extend({\n /** Plugins to apply */\n plugins: z.array(MigrationPluginSchema).optional()\n})\n\n// ============================================================================\n// Type Exports\n// ============================================================================\n\n/** Input type for MigrationRunnerOptions - before defaults are applied */\nexport type MigrationRunnerOptionsInput = z.input<typeof MigrationRunnerOptionsSchema>\n\n/** Output type for MigrationRunnerOptions - after defaults are applied */\nexport type MigrationRunnerOptionsOutput = z.output<typeof MigrationRunnerOptionsSchema>\n\n/** Input type for MigrationDefinition - before defaults are applied */\nexport type MigrationDefinitionInput = z.input<typeof MigrationDefinitionSchema>\n\n/** Output type for MigrationDefinition - after defaults are applied */\nexport type MigrationDefinitionOutput = z.output<typeof MigrationDefinitionSchema>\n\n/** Input type for MigrationPluginOptions */\nexport type MigrationPluginOptionsInput = z.input<typeof MigrationPluginOptionsSchema>\n\n/** Output type for MigrationPluginOptions */\nexport type MigrationPluginOptionsOutput = z.output<typeof MigrationPluginOptionsSchema>\n\n/** Input type for MigrationPlugin */\nexport type MigrationPluginInput = z.input<typeof MigrationPluginSchema>\n\n/** Output type for MigrationPlugin */\nexport type MigrationPluginOutput = z.output<typeof MigrationPluginSchema>\n\n/** Type for MigrationStatus */\nexport type MigrationStatusType = z.infer<typeof MigrationStatusSchema>\n\n/** Type for MigrationResult */\nexport type MigrationResultType = z.infer<typeof MigrationResultSchema>\n\n/** Input type for MigrationRunnerWithPluginsOptions */\nexport type MigrationRunnerWithPluginsOptionsInput = z.input<\n typeof MigrationRunnerWithPluginsOptionsSchema\n>\n\n/** Output type for MigrationRunnerWithPluginsOptions */\nexport type MigrationRunnerWithPluginsOptionsOutput = z.output<\n typeof MigrationRunnerWithPluginsOptionsSchema\n>\n\n// ============================================================================\n// Validation Helpers\n// ============================================================================\n\n/**\n * Validate and parse MigrationRunnerOptions with defaults\n */\nexport function parseMigrationRunnerOptions(options: unknown): MigrationRunnerOptionsOutput {\n return MigrationRunnerOptionsSchema.parse(options)\n}\n\n/**\n * Safely validate MigrationRunnerOptions without throwing\n * Returns result with success boolean and either data or error\n */\nexport function safeParseMigrationRunnerOptions(options: unknown) {\n return MigrationRunnerOptionsSchema.safeParse(options)\n}\n\n/**\n * Validate and parse MigrationDefinition with defaults\n */\nexport function parseMigrationDefinition(definition: unknown): MigrationDefinitionOutput {\n return MigrationDefinitionSchema.parse(definition)\n}\n\n/**\n * Safely validate MigrationDefinition without throwing\n * Returns result with success boolean and either data or error\n */\nexport function safeParseMigrationDefinition(definition: unknown) {\n return MigrationDefinitionSchema.safeParse(definition)\n}\n","import type { Kysely } from 'kysely'\nimport { sql } from 'kysely'\nimport type { KyseraLogger } from '@kysera/core'\nimport { DatabaseError, NotFoundError, BadRequestError, ErrorCodes, silentLogger } from '@kysera/core'\nimport { VERSION } from './version.js'\n\n// ============================================================================\n// Schema Exports\n// ============================================================================\n\nexport {\n // Schemas\n MigrationRunnerOptionsSchema,\n MigrationDefinitionSchema,\n MigrationPluginOptionsSchema,\n MigrationPluginSchema,\n MigrationStatusSchema,\n MigrationResultSchema,\n MigrationRunnerWithPluginsOptionsSchema,\n // Type exports\n type MigrationRunnerOptionsInput,\n type MigrationRunnerOptionsOutput,\n type MigrationDefinitionInput,\n type MigrationDefinitionOutput,\n type MigrationPluginOptionsInput,\n type MigrationPluginOptionsOutput,\n type MigrationPluginInput,\n type MigrationPluginOutput,\n type MigrationStatusType,\n type MigrationResultType,\n type MigrationRunnerWithPluginsOptionsInput,\n type MigrationRunnerWithPluginsOptionsOutput,\n // Validation helpers\n parseMigrationRunnerOptions,\n safeParseMigrationRunnerOptions,\n parseMigrationDefinition,\n safeParseMigrationDefinition\n} from './schemas.js'\n\nimport { MigrationRunnerOptionsSchema } from './schemas.js'\n\n// ============================================================================\n// Types and Interfaces\n// ============================================================================\n\n/**\n * Migration interface - the core building block\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport interface Migration<DB = unknown> {\n /** Unique migration name (e.g., '001_create_users') */\n name: string\n /** Migration up function - creates/modifies schema */\n up: (db: Kysely<DB>) => Promise<void>\n /** Optional migration down function - reverts changes */\n down?: (db: Kysely<DB>) => Promise<void>\n}\n\n/**\n * Migration with metadata for enhanced logging and tracking\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport interface MigrationWithMeta<DB = unknown> extends Migration<DB> {\n /** Human-readable description shown during migration */\n description?: string\n /** Whether this is a breaking change - shows warning before execution */\n breaking?: boolean\n /** Estimated duration in milliseconds for progress indication */\n estimatedDuration?: number\n /** Tags for categorization (e.g., ['schema', 'data', 'index']) */\n tags?: string[]\n}\n\n/**\n * Migration status result\n */\nexport interface MigrationStatus {\n /** List of executed migration names */\n executed: string[]\n /** List of pending migration names */\n pending: string[]\n /** Total migration count */\n total: number\n}\n\n/**\n * Migration runner options\n */\nexport interface MigrationRunnerOptions {\n /** Enable dry run mode (preview only, no changes) */\n dryRun?: boolean\n /**\n * Logger for migration operations.\n * Uses KyseraLogger interface from @kysera/core.\n *\n * @default silentLogger (no output)\n */\n logger?: KyseraLogger\n /** Wrap each migration in a transaction (default: false) */\n useTransactions?: boolean\n /** Stop on first error (default: true) */\n stopOnError?: boolean\n /** Show detailed metadata in logs (default: true) */\n verbose?: boolean\n}\n\n/**\n * Object-based migration definition for Level 2 DX\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport interface MigrationDefinition<DB = unknown> {\n up: (db: Kysely<DB>) => Promise<void>\n down?: (db: Kysely<DB>) => Promise<void>\n description?: string\n breaking?: boolean\n estimatedDuration?: number\n tags?: string[]\n}\n\n/**\n * Migration definitions map for defineMigrations()\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport type MigrationDefinitions<DB = unknown> = Record<string, MigrationDefinition<DB>>\n\n/**\n * Result of a migration run\n */\nexport interface MigrationResult {\n /** Successfully executed migrations */\n executed: string[]\n /** Migrations that were skipped (already executed) */\n skipped: string[]\n /** Migrations that failed */\n failed: string[]\n /** Total duration in milliseconds */\n duration: number\n /** Whether the run was in dry-run mode */\n dryRun: boolean\n}\n\n// ============================================================================\n// Error Classes (extending @kysera/core)\n// ============================================================================\n\n/** Error codes for migration operations — references unified codes from @kysera/core */\nexport const MigrationErrorCodes = {\n UP_FAILED: ErrorCodes.MIGRATION_UP_FAILED,\n DOWN_FAILED: ErrorCodes.MIGRATION_DOWN_FAILED,\n VALIDATION_FAILED: ErrorCodes.MIGRATION_VALIDATION_FAILED,\n} as const\n\nexport type MigrationErrorCode = (typeof MigrationErrorCodes)[keyof typeof MigrationErrorCodes]\n\n/**\n * Migration-specific error extending DatabaseError from @kysera/core\n * Provides structured error information with code, migration context, and cause tracking\n */\nexport class MigrationError extends DatabaseError {\n public readonly migrationName: string\n public readonly operation: 'up' | 'down'\n\n constructor(message: string, migrationName: string, operation: 'up' | 'down', cause?: Error) {\n const code = operation === 'up' ? MigrationErrorCodes.UP_FAILED : MigrationErrorCodes.DOWN_FAILED\n super(message, code, migrationName)\n this.name = 'MigrationError'\n this.migrationName = migrationName\n this.operation = operation\n if (cause) {\n this.cause = cause\n }\n }\n\n override toJSON(): Record<string, unknown> {\n const causeError = this.cause instanceof Error ? this.cause : undefined\n return {\n ...super.toJSON(),\n migrationName: this.migrationName,\n operation: this.operation,\n cause: causeError?.message\n }\n }\n}\n\n// ============================================================================\n// Setup Functions\n// ============================================================================\n\n/**\n * Setup migrations table in database\n * Idempotent - safe to run multiple times\n * Uses Kysely<unknown> as migrations work with any database schema\n */\nexport async function setupMigrations(db: Kysely<unknown>): Promise<void> {\n await db.schema\n .createTable('migrations')\n .ifNotExists()\n .addColumn('name', 'varchar(255)', col => col.primaryKey())\n .addColumn('executed_at', 'timestamp', col => col.notNull().defaultTo(sql`CURRENT_TIMESTAMP`))\n .execute()\n\n // Create index on name column for faster lookups\n // Using IF NOT EXISTS equivalent: ignore errors if index already exists\n try {\n await db.schema.createIndex('idx_migrations_name').on('migrations').column('name').execute()\n } catch (error) {\n // Index already exists or table doesn't support concurrent index creation\n // Safe to ignore as primary key provides index functionality\n }\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Check if migration has metadata\n * Type guard to narrow Migration<DB> to MigrationWithMeta<DB>\n */\nfunction hasMeta<DB>(migration: Migration<DB>): migration is MigrationWithMeta<DB> {\n return 'description' in migration || 'breaking' in migration || 'tags' in migration\n}\n\n/**\n * Format error message for logging\n */\nfunction formatError(error: unknown): string {\n if (error instanceof Error) {\n return error.message\n }\n return String(error)\n}\n\n/**\n * Validate migrations for duplicate names\n * @throws {BadRequestError} When duplicate migration names are found\n */\nfunction validateMigrations<DB>(migrations: Migration<DB>[]): void {\n const names = new Set<string>()\n for (const migration of migrations) {\n if (names.has(migration.name)) {\n throw new BadRequestError(`Duplicate migration name: ${migration.name}`)\n }\n names.add(migration.name)\n }\n}\n\n// ============================================================================\n// Migration Runner Class\n// ============================================================================\n\n/**\n * Migration runner with state tracking and metadata support\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport class MigrationRunner<DB = unknown> {\n protected logger: KyseraLogger\n protected runnerOptions: Required<Omit<MigrationRunnerOptions, 'logger'>> & {\n logger: KyseraLogger\n }\n protected db: Kysely<DB>\n protected migrations: Migration<DB>[]\n private setupDone = false\n\n constructor(db: Kysely<DB>, migrations: Migration<DB>[], options: MigrationRunnerOptions = {}) {\n // Validate and apply defaults using Zod schema\n const parsed = MigrationRunnerOptionsSchema.safeParse(options)\n if (!parsed.success) {\n throw new BadRequestError(`Invalid migration runner options: ${parsed.error.message}`)\n }\n\n this.db = db\n this.migrations = migrations\n this.logger = options.logger ?? silentLogger\n this.runnerOptions = {\n dryRun: parsed.data.dryRun,\n logger: this.logger,\n useTransactions: parsed.data.useTransactions,\n stopOnError: parsed.data.stopOnError,\n verbose: parsed.data.verbose\n }\n\n // Validate migrations on construction\n validateMigrations(migrations)\n }\n\n /**\n * Ensure migrations table exists (idempotent, cached after first call)\n */\n protected async ensureSetup(): Promise<void> {\n if (this.setupDone) return\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await setupMigrations(this.db as any)\n this.setupDone = true\n }\n\n /**\n * Get list of executed migrations from database\n * Note: Uses type assertions for migrations table as it's not part of the user schema\n */\n async getExecutedMigrations(): Promise<string[]> {\n await this.ensureSetup()\n\n // The migrations table is internal and not part of the generic DB schema\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const rows = (await (this.db as any)\n .selectFrom('migrations')\n .select('name')\n .orderBy('executed_at', 'asc')\n .execute()) as { name: string }[]\n\n return rows.map(r => r.name)\n }\n\n /**\n * Mark a migration as executed\n * Note: Uses type assertions for migrations table as it's not part of the user schema\n */\n async markAsExecuted(name: string): Promise<void> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await (this.db as any).insertInto('migrations').values({ name }).execute()\n }\n\n /**\n * Mark a migration as rolled back (remove from executed list)\n * Note: Uses type assertions for migrations table as it's not part of the user schema\n */\n async markAsRolledBack(name: string): Promise<void> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await (this.db as any).deleteFrom('migrations').where('name', '=', name).execute()\n }\n\n /**\n * Log migration metadata if available\n */\n protected logMigrationMeta(migration: Migration<DB>): void {\n if (!this.runnerOptions.verbose || !hasMeta(migration)) return\n\n const meta = migration\n\n if (meta.description) {\n this.logger.info(` Description: ${meta.description}`)\n }\n\n if (meta.breaking) {\n this.logger.warn(` BREAKING CHANGE - Review carefully before proceeding`)\n }\n\n if (meta.tags && meta.tags.length > 0) {\n this.logger.info(` Tags: ${meta.tags.join(', ')}`)\n }\n\n if (meta.estimatedDuration) {\n const seconds = (meta.estimatedDuration / 1000).toFixed(1)\n this.logger.info(` Estimated: ${seconds}s`)\n }\n }\n\n /**\n * Execute a single migration with optional transaction wrapping\n */\n protected async executeMigration(\n migration: Migration<DB>,\n operation: 'up' | 'down'\n ): Promise<void> {\n const fn = operation === 'up' ? migration.up : migration.down\n if (!fn) return\n\n if (this.runnerOptions.useTransactions) {\n await this.db.transaction().execute(async trx => {\n await fn(trx)\n })\n } else {\n await fn(this.db)\n }\n }\n\n /**\n * Run all pending migrations\n */\n async up(): Promise<MigrationResult> {\n return this.runUp(this.migrations)\n }\n\n /**\n * Core up logic — used by up(), upTo(), and overridden by MigrationRunnerWithPlugins.\n * Protected to allow hook injection by subclasses.\n */\n protected async runUp(\n migrationsToConsider: Migration<DB>[],\n hooks?: {\n before?: (migration: Migration<DB>) => Promise<void>\n after?: (migration: Migration<DB>, duration: number) => Promise<void>\n onError?: (migration: Migration<DB>, error: unknown) => Promise<void>\n }\n ): Promise<MigrationResult> {\n const startTime = Date.now()\n const result: MigrationResult = {\n executed: [],\n skipped: [],\n failed: [],\n duration: 0,\n dryRun: this.runnerOptions.dryRun\n }\n\n const executedList = await this.getExecutedMigrations()\n const executedSet = new Set(executedList)\n\n const pending = migrationsToConsider.filter(m => !executedSet.has(m.name))\n\n if (pending.length === 0) {\n this.logger.info('No pending migrations')\n result.skipped = executedList\n result.duration = Date.now() - startTime\n return result\n }\n\n if (this.runnerOptions.dryRun) {\n this.logger.info('DRY RUN - No changes will be made')\n }\n\n for (const migration of migrationsToConsider) {\n if (executedSet.has(migration.name)) {\n this.logger.info(`${migration.name} (already executed)`)\n result.skipped.push(migration.name)\n continue\n }\n\n const migrationStart = Date.now()\n\n try {\n await hooks?.before?.(migration)\n\n this.logger.info(`Running ${migration.name}...`)\n this.logMigrationMeta(migration)\n\n if (!this.runnerOptions.dryRun) {\n await this.executeMigration(migration, 'up')\n await this.markAsExecuted(migration.name)\n }\n\n await hooks?.after?.(migration, Date.now() - migrationStart)\n\n this.logger.info(`${migration.name} completed`)\n result.executed.push(migration.name)\n } catch (error) {\n await hooks?.onError?.(migration, error)\n\n const errorMsg = formatError(error)\n this.logger.error(`${migration.name} failed: ${errorMsg}`)\n result.failed.push(migration.name)\n\n if (this.runnerOptions.stopOnError) {\n throw new MigrationError(\n `Migration ${migration.name} failed: ${errorMsg}`,\n migration.name,\n 'up',\n error instanceof Error ? error : undefined\n )\n }\n }\n }\n\n if (!this.runnerOptions.dryRun) {\n if (result.failed.length > 0) {\n this.logger.warn(`Migrations completed with ${String(result.failed.length)} failure(s)`)\n } else {\n this.logger.info('All migrations completed successfully')\n }\n } else {\n this.logger.info('Dry run completed - no changes made')\n }\n\n result.duration = Date.now() - startTime\n return result\n }\n\n /**\n * Rollback last N migrations\n */\n async down(steps = 1): Promise<MigrationResult> {\n return this.runDown(steps)\n }\n\n /**\n * Core down logic — used by down() and overridden by MigrationRunnerWithPlugins.\n * Protected to allow hook injection by subclasses.\n */\n protected async runDown(\n steps: number,\n hooks?: {\n before?: (migration: Migration<DB>) => Promise<void>\n after?: (migration: Migration<DB>, duration: number) => Promise<void>\n onError?: (migration: Migration<DB>, error: unknown) => Promise<void>\n }\n ): Promise<MigrationResult> {\n const startTime = Date.now()\n const result: MigrationResult = {\n executed: [],\n skipped: [],\n failed: [],\n duration: 0,\n dryRun: this.runnerOptions.dryRun\n }\n\n const executed = await this.getExecutedMigrations()\n\n if (executed.length === 0) {\n this.logger.warn('No executed migrations to rollback')\n result.duration = Date.now() - startTime\n return result\n }\n\n const toRollback = executed.slice(-steps).reverse()\n\n if (this.runnerOptions.dryRun) {\n this.logger.info('DRY RUN - No changes will be made')\n }\n\n for (const name of toRollback) {\n const migration = this.migrations.find(m => m.name === name)\n\n if (!migration) {\n this.logger.warn(`Migration ${name} not found in codebase`)\n result.skipped.push(name)\n continue\n }\n\n if (!migration.down) {\n this.logger.warn(`Migration ${name} has no down method - skipping`)\n result.skipped.push(name)\n continue\n }\n\n const migrationStart = Date.now()\n\n try {\n await hooks?.before?.(migration)\n\n this.logger.info(`Rolling back ${name}...`)\n this.logMigrationMeta(migration)\n\n if (!this.runnerOptions.dryRun) {\n await this.executeMigration(migration, 'down')\n await this.markAsRolledBack(name)\n }\n\n await hooks?.after?.(migration, Date.now() - migrationStart)\n\n this.logger.info(`${name} rolled back`)\n result.executed.push(name)\n } catch (error) {\n await hooks?.onError?.(migration, error)\n\n const errorMsg = formatError(error)\n this.logger.error(`${name} rollback failed: ${errorMsg}`)\n result.failed.push(name)\n\n if (this.runnerOptions.stopOnError) {\n throw new MigrationError(\n `Rollback of ${name} failed: ${errorMsg}`,\n name,\n 'down',\n error instanceof Error ? error : undefined\n )\n }\n }\n }\n\n if (!this.runnerOptions.dryRun) {\n if (result.failed.length > 0) {\n this.logger.warn(`Rollback completed with ${String(result.failed.length)} failure(s)`)\n } else {\n this.logger.info('Rollback completed successfully')\n }\n } else {\n this.logger.info('Dry run completed - no changes made')\n }\n\n result.duration = Date.now() - startTime\n return result\n }\n\n /**\n * Show migration status\n */\n async status(): Promise<MigrationStatus> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await this.ensureSetup()\n const executed = await this.getExecutedMigrations()\n const pending = this.migrations.filter(m => !executed.includes(m.name)).map(m => m.name)\n\n this.logger.info('Migration Status:')\n this.logger.info(` Executed: ${executed.length}`)\n this.logger.info(` Pending: ${pending.length}`)\n this.logger.info(` Total: ${this.migrations.length}`)\n\n if (executed.length > 0) {\n this.logger.info('Executed migrations:')\n for (const name of executed) {\n const migration = this.migrations.find(m => m.name === name)\n if (migration && hasMeta(migration) && (migration as MigrationWithMeta).description) {\n this.logger.info(` ${name} - ${(migration as MigrationWithMeta).description}`)\n } else {\n this.logger.info(` ${name}`)\n }\n }\n }\n\n if (pending.length > 0) {\n this.logger.info('Pending migrations:')\n for (const name of pending) {\n const migration = this.migrations.find(m => m.name === name)\n if (migration && hasMeta(migration)) {\n const meta = migration as MigrationWithMeta\n const suffix = meta.breaking ? ' BREAKING' : ''\n const desc = meta.description ? ` - ${meta.description}` : ''\n this.logger.info(` ${name}${desc}${suffix}`)\n } else {\n this.logger.info(` ${name}`)\n }\n }\n }\n\n return { executed, pending, total: this.migrations.length }\n }\n\n /**\n * Reset all migrations (dangerous!)\n * In dry run mode, shows what would be rolled back\n */\n async reset(): Promise<MigrationResult> {\n const startTime = Date.now()\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await this.ensureSetup()\n const executed = await this.getExecutedMigrations()\n\n if (executed.length === 0) {\n this.logger.warn('No migrations to reset')\n return {\n executed: [],\n skipped: [],\n failed: [],\n duration: Date.now() - startTime,\n dryRun: this.runnerOptions.dryRun\n }\n }\n\n this.logger.warn(`Resetting ${executed.length} migrations...`)\n\n if (this.runnerOptions.dryRun) {\n this.logger.info('DRY RUN - Would rollback the following migrations:')\n for (const name of [...executed].reverse()) {\n const migration = this.migrations.find(m => m.name === name)\n if (!migration?.down) {\n this.logger.warn(` ${name} (no down method - would be skipped)`)\n } else {\n this.logger.info(` ${name}`)\n }\n }\n this.logger.info('Dry run completed - no changes made')\n return {\n executed: [],\n skipped: executed,\n failed: [],\n duration: Date.now() - startTime,\n dryRun: true\n }\n }\n\n const result = await this.down(executed.length)\n this.logger.info('All migrations reset')\n return result\n }\n\n /**\n * Run migrations up to a specific migration (inclusive)\n */\n async upTo(targetName: string): Promise<MigrationResult> {\n const targetIndex = this.migrations.findIndex(m => m.name === targetName)\n if (targetIndex === -1) {\n throw new NotFoundError('Migration', { name: targetName })\n }\n\n const migrationsToRun = this.migrations.slice(0, targetIndex + 1)\n const result = await this.runUp(migrationsToRun)\n\n if (!this.runnerOptions.dryRun && result.failed.length === 0) {\n this.logger.info(`Migrated up to ${targetName}`)\n }\n\n return result\n }\n}\n\n// ============================================================================\n// Factory Functions\n// ============================================================================\n\n/**\n * Create a migration runner instance\n * Options are validated using Zod schema\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport function createMigrationRunner<DB = unknown>(\n db: Kysely<DB>,\n migrations: Migration<DB>[],\n options?: MigrationRunnerOptions\n): MigrationRunner<DB> {\n return new MigrationRunner(db, migrations, options)\n}\n\n/**\n * Helper to create a simple migration\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport function createMigration<DB = unknown>(\n name: string,\n up: (db: Kysely<DB>) => Promise<void>,\n down?: (db: Kysely<DB>) => Promise<void>\n): Migration<DB> {\n const migration: Migration<DB> = { name, up }\n if (down !== undefined) {\n migration.down = down\n }\n return migration\n}\n\n/**\n * Helper to create a migration with metadata\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport function createMigrationWithMeta<DB = unknown>(\n name: string,\n options: {\n up: (db: Kysely<DB>) => Promise<void>\n down?: (db: Kysely<DB>) => Promise<void>\n description?: string\n breaking?: boolean\n estimatedDuration?: number\n tags?: string[]\n }\n): MigrationWithMeta<DB> {\n const migration: MigrationWithMeta<DB> = {\n name,\n up: options.up\n }\n if (options.down !== undefined) {\n migration.down = options.down\n }\n if (options.description !== undefined) {\n migration.description = options.description\n }\n if (options.breaking !== undefined) {\n migration.breaking = options.breaking\n }\n if (options.estimatedDuration !== undefined) {\n migration.estimatedDuration = options.estimatedDuration\n }\n if (options.tags !== undefined) {\n migration.tags = options.tags\n }\n return migration\n}\n\n// ============================================================================\n// Level 2: Developer Experience APIs\n// ============================================================================\n\n/**\n * Define migrations using an object-based syntax for cleaner code\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport function defineMigrations<DB = unknown>(\n definitions: MigrationDefinitions<DB>\n): MigrationWithMeta<DB>[] {\n return Object.entries(definitions).map(([name, def]) => {\n const migration: MigrationWithMeta<DB> = {\n name,\n up: def.up\n }\n if (def.down !== undefined) {\n migration.down = def.down\n }\n if (def.description !== undefined) {\n migration.description = def.description\n }\n if (def.breaking !== undefined) {\n migration.breaking = def.breaking\n }\n if (def.estimatedDuration !== undefined) {\n migration.estimatedDuration = def.estimatedDuration\n }\n if (def.tags !== undefined) {\n migration.tags = def.tags\n }\n return migration\n })\n}\n\n/**\n * Run all pending migrations - one-liner convenience function\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport async function runMigrations<DB = unknown>(\n db: Kysely<DB>,\n migrations: Migration<DB>[],\n options?: MigrationRunnerOptions\n): Promise<MigrationResult> {\n const runner = new MigrationRunner(db, migrations, options)\n return await runner.up()\n}\n\n/**\n * Rollback migrations - one-liner convenience function\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport async function rollbackMigrations<DB = unknown>(\n db: Kysely<DB>,\n migrations: Migration<DB>[],\n steps = 1,\n options?: MigrationRunnerOptions\n): Promise<MigrationResult> {\n const runner = new MigrationRunner(db, migrations, options)\n return await runner.down(steps)\n}\n\n/**\n * Get migration status - one-liner convenience function\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport async function getMigrationStatus<DB = unknown>(\n db: Kysely<DB>,\n migrations: Migration<DB>[],\n options?: Pick<MigrationRunnerOptions, 'logger' | 'verbose'>\n): Promise<MigrationStatus> {\n const runner = new MigrationRunner(db, migrations, options)\n return await runner.status()\n}\n\n// ============================================================================\n// Level 3: Ecosystem Integration\n// ============================================================================\n\n/**\n * Migration plugin interface - consistent with @kysera/repository Plugin\n * Provides lifecycle hooks for migration execution\n * Generic DB type allows type-safe plugins when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport interface MigrationPlugin<DB = unknown> {\n /** Plugin name */\n name: string\n /** Plugin version */\n version: string\n /** Called once when the runner is initialized (consistent with repository Plugin.onInit) */\n onInit?(runner: MigrationRunner<DB>): Promise<void> | void\n /** Called before migration execution */\n beforeMigration?(migration: Migration<DB>, operation: 'up' | 'down'): Promise<void> | void\n /** Called after successful migration execution */\n afterMigration?(\n migration: Migration<DB>,\n operation: 'up' | 'down',\n duration: number\n ): Promise<void> | void\n /** Called on migration error (unknown type for consistency with repository Plugin.onError) */\n onMigrationError?(\n migration: Migration<DB>,\n operation: 'up' | 'down',\n error: unknown\n ): Promise<void> | void\n}\n\n/**\n * Extended migration runner options with plugin support\n * Generic DB type allows type-safe plugins when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport interface MigrationRunnerWithPluginsOptions<DB = unknown> extends MigrationRunnerOptions {\n /** Plugins to apply */\n plugins?: MigrationPlugin<DB>[]\n}\n\n/**\n * Create a migration runner with plugin support\n * Async factory to properly initialize plugins (consistent with @kysera/repository createORM)\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport async function createMigrationRunnerWithPlugins<DB = unknown>(\n db: Kysely<DB>,\n migrations: Migration<DB>[],\n options?: MigrationRunnerWithPluginsOptions<DB>\n): Promise<MigrationRunnerWithPlugins<DB>> {\n const runner = new MigrationRunnerWithPlugins(db, migrations, options)\n\n // Initialize plugins (consistent with repository Plugin.onInit pattern)\n if (options?.plugins) {\n for (const plugin of options.plugins) {\n if (plugin.onInit) {\n const result = plugin.onInit(runner)\n if (result instanceof Promise) {\n await result\n }\n }\n }\n }\n\n return runner\n}\n\n/**\n * Extended migration runner with plugin support\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n *\n * This class overrides up() and down() to call plugin lifecycle hooks\n * (beforeMigration, afterMigration, onMigrationError) around each migration execution.\n */\nexport class MigrationRunnerWithPlugins<DB = unknown> extends MigrationRunner<DB> {\n private plugins: MigrationPlugin<DB>[]\n\n constructor(\n db: Kysely<DB>,\n migrations: Migration<DB>[],\n options: MigrationRunnerWithPluginsOptions<DB> = {}\n ) {\n super(db, migrations, options)\n this.plugins = options.plugins ?? []\n }\n\n /**\n * Execute plugin hooks before migration\n * Can be called by consumers extending this class\n */\n protected async runBeforeHooks(\n migration: Migration<DB>,\n operation: 'up' | 'down'\n ): Promise<void> {\n for (const plugin of this.plugins) {\n if (plugin.beforeMigration) {\n await plugin.beforeMigration(migration, operation)\n }\n }\n }\n\n /**\n * Execute plugin hooks after migration\n * Can be called by consumers extending this class\n */\n protected async runAfterHooks(\n migration: Migration<DB>,\n operation: 'up' | 'down',\n duration: number\n ): Promise<void> {\n for (const plugin of this.plugins) {\n if (plugin.afterMigration) {\n await plugin.afterMigration(migration, operation, duration)\n }\n }\n }\n\n /**\n * Execute plugin hooks on error\n * Can be called by consumers extending this class\n */\n protected async runErrorHooks(\n migration: Migration<DB>,\n operation: 'up' | 'down',\n error: unknown\n ): Promise<void> {\n for (const plugin of this.plugins) {\n if (plugin.onMigrationError) {\n await plugin.onMigrationError(migration, operation, error)\n }\n }\n }\n\n /**\n * Get the list of registered plugins\n */\n getPlugins(): MigrationPlugin<DB>[] {\n return [...this.plugins]\n }\n\n /**\n * Run all pending migrations with plugin hooks.\n * Delegates to parent's runUp with plugin lifecycle hooks.\n */\n override async up(): Promise<MigrationResult> {\n return this.runUp(this.migrations, {\n before: async (migration) => { await this.runBeforeHooks(migration, 'up') },\n after: async (migration, duration) => { await this.runAfterHooks(migration, 'up', duration) },\n onError: async (migration, error) => { await this.runErrorHooks(migration, 'up', error) }\n })\n }\n\n /**\n * Rollback last N migrations with plugin hooks.\n * Delegates to parent's runDown with plugin lifecycle hooks.\n */\n override async down(steps = 1): Promise<MigrationResult> {\n return this.runDown(steps, {\n before: async (migration) => { await this.runBeforeHooks(migration, 'down') },\n after: async (migration, duration) => { await this.runAfterHooks(migration, 'down', duration) },\n onError: async (migration, error) => { await this.runErrorHooks(migration, 'down', error) }\n })\n }\n}\n\n// ============================================================================\n// Built-in Plugins\n// ============================================================================\n\n/**\n * Logging plugin - logs migration events with timing\n * Works with any DB type (generic plugin)\n */\nexport function createLoggingPlugin<DB = unknown>(\n logger: KyseraLogger = silentLogger\n): MigrationPlugin<DB> {\n return {\n name: '@kysera/migrations/logging',\n version: VERSION,\n beforeMigration(migration, operation) {\n logger.info(`Starting ${operation} for ${migration.name}`)\n },\n afterMigration(migration, operation, duration) {\n logger.info(`Completed ${operation} for ${migration.name} in ${duration}ms`)\n },\n onMigrationError(migration, operation, error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.error(`Error during ${operation} for ${migration.name}: ${message}`)\n }\n }\n}\n\n/**\n * Metrics plugin - collects migration metrics\n * Works with any DB type (generic plugin)\n */\nexport function createMetricsPlugin<DB = unknown>(): MigrationPlugin<DB> & {\n getMetrics(): {\n migrations: { name: string; operation: string; duration: number; success: boolean }[]\n }\n} {\n const metrics: { name: string; operation: string; duration: number; success: boolean }[] = []\n\n return {\n name: '@kysera/migrations/metrics',\n version: VERSION,\n afterMigration(migration, operation, duration) {\n metrics.push({ name: migration.name, operation, duration, success: true })\n },\n onMigrationError(migration, operation) {\n metrics.push({ name: migration.name, operation, duration: 0, success: false })\n },\n getMetrics() {\n return { migrations: [...metrics] }\n }\n }\n}\n\n// ============================================================================\n// Re-exports from @kysera/core for convenience\n// ============================================================================\n\nexport { DatabaseError, NotFoundError, BadRequestError, silentLogger } from '@kysera/core'\nexport type { KyseraLogger } from '@kysera/core'\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kysera/migrations",
3
- "version": "0.8.6",
3
+ "version": "0.8.8",
4
4
  "description": "Database migration management for Kysely with dry-run support and flexible rollback capabilities",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -26,21 +26,21 @@
26
26
  "author": "Kysera Team",
27
27
  "license": "MIT",
28
28
  "dependencies": {
29
- "@kysera/core": "0.8.6"
29
+ "@kysera/core": "0.8.8"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@types/better-sqlite3": "^7.6.13",
33
- "@types/node": "^25.2.1",
34
- "@vitest/coverage-v8": "^4.0.16",
35
- "better-sqlite3": "^12.5.0",
36
- "kysely": "^0.28.9",
33
+ "@types/node": "^25.5.2",
34
+ "@vitest/coverage-v8": "^4.1.3",
35
+ "better-sqlite3": "^12.8.0",
36
+ "kysely": "^0.28.15",
37
37
  "tsup": "^8.5.1",
38
- "typescript": "^5.9.3",
39
- "vitest": "^4.0.16",
38
+ "typescript": "^6.0.2",
39
+ "vitest": "^4.1.3",
40
40
  "zod": "^4.3.6"
41
41
  },
42
42
  "peerDependencies": {
43
- "kysely": ">=0.28.8",
43
+ "kysely": ">=0.28.14",
44
44
  "zod": "^4.3.6"
45
45
  },
46
46
  "sideEffects": false,