@kysera/migrations 0.7.2 → 0.7.4

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/README.md CHANGED
@@ -9,6 +9,7 @@
9
9
  ## Features
10
10
 
11
11
  ### Core Migration Management
12
+
12
13
  - **Simple API** - Intuitive migration creation and execution
13
14
  - **Type-safe** - Full TypeScript support with Kysely integration
14
15
  - **State tracking** - Automatic migration history in database
@@ -16,6 +17,7 @@
16
17
  - **Dry run mode** - Preview changes before execution
17
18
 
18
19
  ### Advanced Features
20
+
19
21
  - **Rollback support** - Roll back one or multiple migrations
20
22
  - **Partial migration** - Run up to specific migration
21
23
  - **Status reporting** - View executed and pending migrations
@@ -24,12 +26,14 @@
24
26
  - **Duplicate detection** - Validates unique migration names
25
27
 
26
28
  ### Developer Experience (v0.5.0+)
29
+
27
30
  - **`defineMigrations()`** - Object-based migration definition
28
31
  - **`runMigrations()`** - One-liner to run pending migrations
29
32
  - **`rollbackMigrations()`** - One-liner for rollbacks
30
33
  - **Migration metadata** - Description, breaking flag, tags, timing
31
34
 
32
35
  ### Plugin System (v0.5.0+)
36
+
33
37
  - **Plugin hooks** - Before/after migration events
34
38
  - **Built-in plugins** - Logging and metrics plugins
35
39
  - **Extensible** - Create custom plugins for your needs
@@ -38,18 +42,20 @@
38
42
 
39
43
  ```bash
40
44
  # pnpm (recommended)
41
- pnpm add @kysera/migrations kysely
45
+ pnpm add @kysera/migrations kysely zod
42
46
 
43
47
  # npm
44
- npm install @kysera/migrations kysely
48
+ npm install @kysera/migrations kysely zod
45
49
 
46
50
  # yarn
47
- yarn add @kysera/migrations kysely
51
+ yarn add @kysera/migrations kysely zod
48
52
 
49
53
  # bun
50
- bun add @kysera/migrations kysely
54
+ bun add @kysera/migrations kysely zod
51
55
  ```
52
56
 
57
+ **Note:** Zod is a **required peer dependency** (not optional) for schema validation in the migration system.
58
+
53
59
  ## Quick Start
54
60
 
55
61
  ### Basic Usage
@@ -62,7 +68,7 @@ import { createMigrationRunner, createMigration } from '@kysera/migrations'
62
68
  const migrations = [
63
69
  createMigration(
64
70
  '001_create_users',
65
- async (db) => {
71
+ async db => {
66
72
  await db.schema
67
73
  .createTable('users')
68
74
  .addColumn('id', 'serial', col => col.primaryKey())
@@ -70,14 +76,14 @@ const migrations = [
70
76
  .addColumn('name', 'varchar(255)', col => col.notNull())
71
77
  .execute()
72
78
  },
73
- async (db) => {
79
+ async db => {
74
80
  await db.schema.dropTable('users').execute()
75
81
  }
76
82
  ),
77
83
 
78
84
  createMigration(
79
85
  '002_create_posts',
80
- async (db) => {
86
+ async db => {
81
87
  await db.schema
82
88
  .createTable('posts')
83
89
  .addColumn('id', 'serial', col => col.primaryKey())
@@ -87,14 +93,16 @@ const migrations = [
87
93
  .addColumn('title', 'varchar(255)', col => col.notNull())
88
94
  .execute()
89
95
  },
90
- async (db) => {
96
+ async db => {
91
97
  await db.schema.dropTable('posts').execute()
92
98
  }
93
99
  )
94
100
  ]
95
101
 
96
102
  // Create migration runner
97
- const db = new Kysely<Database>({ /* ... */ })
103
+ const db = new Kysely<Database>({
104
+ /* ... */
105
+ })
98
106
  const runner = createMigrationRunner(db, migrations)
99
107
 
100
108
  // Run all pending migrations
@@ -117,30 +125,30 @@ import { defineMigrations, runMigrations } from '@kysera/migrations'
117
125
  const migrations = defineMigrations({
118
126
  '001_create_users': {
119
127
  description: 'Create users table with email and name',
120
- up: async (db) => {
128
+ up: async db => {
121
129
  await db.schema
122
130
  .createTable('users')
123
131
  .addColumn('id', 'serial', col => col.primaryKey())
124
132
  .addColumn('email', 'varchar(255)', col => col.notNull().unique())
125
133
  .execute()
126
134
  },
127
- down: async (db) => {
135
+ down: async db => {
128
136
  await db.schema.dropTable('users').execute()
129
- },
137
+ }
130
138
  },
131
139
 
132
140
  '002_create_posts': {
133
141
  description: 'Create posts table',
134
142
  breaking: false,
135
143
  tags: ['schema'],
136
- up: async (db) => {
144
+ up: async db => {
137
145
  await db.schema
138
146
  .createTable('posts')
139
147
  .addColumn('id', 'serial', col => col.primaryKey())
140
148
  .addColumn('title', 'varchar(255)', col => col.notNull())
141
149
  .execute()
142
- },
143
- },
150
+ }
151
+ }
144
152
  })
145
153
 
146
154
  // One-liner to run all migrations
@@ -178,10 +186,10 @@ interface Migration {
178
186
 
179
187
  ```typescript
180
188
  interface MigrationWithMeta extends Migration {
181
- description?: string // Shown in logs
182
- breaking?: boolean // Shows warning
189
+ description?: string // Shown in logs
190
+ breaking?: boolean // Shows warning
183
191
  estimatedDuration?: number // In milliseconds
184
- tags?: string[] // For categorization
192
+ tags?: string[] // For categorization
185
193
  }
186
194
  ```
187
195
 
@@ -199,11 +207,11 @@ interface MigrationStatus {
199
207
 
200
208
  ```typescript
201
209
  interface MigrationResult {
202
- executed: string[] // Successfully executed
203
- skipped: string[] // Already executed or no down()
204
- failed: string[] // Failed migrations
205
- duration: number // Total time in ms
206
- dryRun: boolean // Whether dry run mode
210
+ executed: string[] // Successfully executed
211
+ skipped: string[] // Already executed or no down()
212
+ failed: string[] // Failed migrations
213
+ duration: number // Total time in ms
214
+ dryRun: boolean // Whether dry run mode
207
215
  }
208
216
  ```
209
217
 
@@ -211,11 +219,11 @@ interface MigrationResult {
211
219
 
212
220
  ```typescript
213
221
  interface MigrationRunnerOptions {
214
- dryRun?: boolean // Preview only (default: false)
215
- logger?: KyseraLogger // Logger instance from @kysera/core (default: silentLogger)
222
+ dryRun?: boolean // Preview only (default: false)
223
+ logger?: KyseraLogger // Logger instance from @kysera/core (default: silentLogger)
216
224
  useTransactions?: boolean // Wrap in transactions (default: false)
217
- stopOnError?: boolean // Stop on first error (default: true)
218
- verbose?: boolean // Show metadata (default: true)
225
+ stopOnError?: boolean // Stop on first error (default: true)
226
+ verbose?: boolean // Show metadata (default: true)
219
227
  }
220
228
  ```
221
229
 
@@ -249,7 +257,10 @@ interface MigrationRunnerWithPluginsOptions extends MigrationRunnerOptions {
249
257
  #### `MigrationErrorCode`
250
258
 
251
259
  ```typescript
252
- type MigrationErrorCode = 'MIGRATION_UP_FAILED' | 'MIGRATION_DOWN_FAILED' | 'MIGRATION_VALIDATION_FAILED'
260
+ type MigrationErrorCode =
261
+ | 'MIGRATION_UP_FAILED'
262
+ | 'MIGRATION_DOWN_FAILED'
263
+ | 'MIGRATION_VALIDATION_FAILED'
253
264
  ```
254
265
 
255
266
  ### Factory Functions
@@ -261,8 +272,12 @@ Create a simple migration:
261
272
  ```typescript
262
273
  const migration = createMigration(
263
274
  '001_create_users',
264
- async (db) => { /* up */ },
265
- async (db) => { /* down */ }
275
+ async db => {
276
+ /* up */
277
+ },
278
+ async db => {
279
+ /* down */
280
+ }
266
281
  )
267
282
  ```
268
283
 
@@ -276,8 +291,12 @@ const migration = createMigrationWithMeta('001_create_users', {
276
291
  breaking: true,
277
292
  tags: ['schema', 'users'],
278
293
  estimatedDuration: 5000,
279
- up: async (db) => { /* ... */ },
280
- down: async (db) => { /* ... */ },
294
+ up: async db => {
295
+ /* ... */
296
+ },
297
+ down: async db => {
298
+ /* ... */
299
+ }
281
300
  })
282
301
  ```
283
302
 
@@ -289,7 +308,7 @@ Create a MigrationRunner instance:
289
308
  const runner = createMigrationRunner(db, migrations, {
290
309
  dryRun: false,
291
310
  logger: console.log,
292
- useTransactions: true,
311
+ useTransactions: true
293
312
  })
294
313
  ```
295
314
 
@@ -300,7 +319,7 @@ Create a MigrationRunner with plugin support (async factory):
300
319
  ```typescript
301
320
  const runner = await createMigrationRunnerWithPlugins(db, migrations, {
302
321
  plugins: [createLoggingPlugin(), createMetricsPlugin()],
303
- useTransactions: true,
322
+ useTransactions: true
304
323
  })
305
324
 
306
325
  // Runner is ready with plugins initialized via onInit
@@ -317,9 +336,13 @@ Define migrations using object syntax:
317
336
  const migrations = defineMigrations({
318
337
  '001_users': {
319
338
  description: 'Create users',
320
- up: async (db) => { /* ... */ },
321
- down: async (db) => { /* ... */ },
322
- },
339
+ up: async db => {
340
+ /* ... */
341
+ },
342
+ down: async db => {
343
+ /* ... */
344
+ }
345
+ }
323
346
  })
324
347
  ```
325
348
 
@@ -337,8 +360,8 @@ const result = await runMigrations(db, migrations, { dryRun: true })
337
360
  Rollback migrations:
338
361
 
339
362
  ```typescript
340
- await rollbackMigrations(db, migrations) // Last 1
341
- await rollbackMigrations(db, migrations, 3) // Last 3
363
+ await rollbackMigrations(db, migrations) // Last 1
364
+ await rollbackMigrations(db, migrations, 3) // Last 3
342
365
  await rollbackMigrations(db, migrations, 1, { dryRun: true })
343
366
  ```
344
367
 
@@ -368,8 +391,8 @@ console.log(`Executed: ${result.executed.length} migrations`)
368
391
  Rollback last N migrations:
369
392
 
370
393
  ```typescript
371
- await runner.down(1) // Rollback last one
372
- await runner.down(3) // Rollback last three
394
+ await runner.down(1) // Rollback last one
395
+ await runner.down(3) // Rollback last three
373
396
  ```
374
397
 
375
398
  #### `status(): Promise<MigrationStatus>`
@@ -386,7 +409,7 @@ const status = await runner.status()
386
409
  Rollback all migrations:
387
410
 
388
411
  ```typescript
389
- await runner.reset() // Dangerous! Rolls back everything
412
+ await runner.reset() // Dangerous! Rolls back everything
390
413
  ```
391
414
 
392
415
  #### `upTo(targetName): Promise<MigrationResult>`
@@ -448,9 +471,17 @@ interface MigrationPlugin {
448
471
  // Called once when runner is initialized (consistent with repository Plugin.onInit)
449
472
  onInit?(runner: MigrationRunner): Promise<void> | void
450
473
  beforeMigration?(migration: Migration, operation: 'up' | 'down'): Promise<void> | void
451
- afterMigration?(migration: Migration, operation: 'up' | 'down', duration: number): Promise<void> | void
474
+ afterMigration?(
475
+ migration: Migration,
476
+ operation: 'up' | 'down',
477
+ duration: number
478
+ ): Promise<void> | void
452
479
  // Unknown error type for consistency with repository Plugin.onError
453
- onMigrationError?(migration: Migration, operation: 'up' | 'down', error: unknown): Promise<void> | void
480
+ onMigrationError?(
481
+ migration: Migration,
482
+ operation: 'up' | 'down',
483
+ error: unknown
484
+ ): Promise<void> | void
454
485
  }
455
486
  ```
456
487
 
@@ -463,7 +494,7 @@ import { createLoggingPlugin } from '@kysera/migrations'
463
494
 
464
495
  const loggingPlugin = createLoggingPlugin(console.log)
465
496
  // or with custom logger
466
- const loggingPlugin = createLoggingPlugin((msg) => logger.info(msg))
497
+ const loggingPlugin = createLoggingPlugin(msg => logger.info(msg))
467
498
  ```
468
499
 
469
500
  #### Metrics Plugin
@@ -503,7 +534,7 @@ const notificationPlugin: MigrationPlugin = {
503
534
  // Error is unknown type - handle appropriately
504
535
  const message = error instanceof Error ? error.message : String(error)
505
536
  await pagerduty.alert(`Migration failed: ${message}`)
506
- },
537
+ }
507
538
  }
508
539
  ```
509
540
 
@@ -588,8 +619,12 @@ try {
588
619
  ```typescript
589
620
  createMigration(
590
621
  '001_create_users',
591
- async (db) => { /* up */ },
592
- async (db) => { /* down - always provide this! */ }
622
+ async db => {
623
+ /* up */
624
+ },
625
+ async db => {
626
+ /* down - always provide this! */
627
+ }
593
628
  )
594
629
  ```
595
630
 
@@ -598,9 +633,11 @@ createMigration(
598
633
  ```typescript
599
634
  createMigrationWithMeta('005_big_refactor', {
600
635
  description: 'Refactors user permissions system',
601
- breaking: true, // Will show warning
636
+ breaking: true, // Will show warning
602
637
  tags: ['breaking', 'permissions'],
603
- up: async (db) => { /* ... */ },
638
+ up: async db => {
639
+ /* ... */
640
+ }
604
641
  })
605
642
  ```
606
643
 
@@ -618,7 +655,7 @@ await runMigrations(db, migrations)
618
655
 
619
656
  ```typescript
620
657
  const runner = createMigrationRunner(db, migrations, {
621
- useTransactions: true, // Each migration wrapped in transaction
658
+ useTransactions: true // Each migration wrapped in transaction
622
659
  })
623
660
  ```
624
661
 
@@ -628,7 +665,12 @@ const runner = createMigrationRunner(db, migrations, {
628
665
  // scripts/migrate.ts
629
666
  import { Kysely, PostgresDialect } from 'kysely'
630
667
  import { Pool } from 'pg'
631
- import { runMigrations, rollbackMigrations, getMigrationStatus, defineMigrations } from '@kysera/migrations'
668
+ import {
669
+ runMigrations,
670
+ rollbackMigrations,
671
+ getMigrationStatus,
672
+ defineMigrations
673
+ } from '@kysera/migrations'
632
674
 
633
675
  const migrations = defineMigrations({
634
676
  // ... your migrations
@@ -694,58 +736,51 @@ main()
694
736
  ### PostgreSQL
695
737
 
696
738
  ```typescript
697
- createMigration(
698
- '001_create_users',
699
- async (db) => {
700
- await db.schema
701
- .createTable('users')
702
- .addColumn('id', 'serial', col => col.primaryKey())
703
- .addColumn('created_at', 'timestamp', col =>
704
- col.notNull().defaultTo(db.fn('now'))
705
- )
706
- .execute()
707
- }
708
- )
739
+ createMigration('001_create_users', async db => {
740
+ await db.schema
741
+ .createTable('users')
742
+ .addColumn('id', 'serial', col => col.primaryKey())
743
+ .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(db.fn('now')))
744
+ .execute()
745
+ })
709
746
  ```
710
747
 
711
748
  ### MySQL
712
749
 
713
750
  ```typescript
714
- createMigration(
715
- '001_create_users',
716
- async (db) => {
717
- await db.schema
718
- .createTable('users')
719
- .addColumn('id', 'integer', col =>
720
- col.primaryKey().autoIncrement()
721
- )
722
- .addColumn('created_at', 'datetime', col =>
723
- col.notNull().defaultTo(db.fn('now'))
724
- )
725
- .execute()
726
- }
727
- )
751
+ createMigration('001_create_users', async db => {
752
+ await db.schema
753
+ .createTable('users')
754
+ .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
755
+ .addColumn('created_at', 'datetime', col => col.notNull().defaultTo(db.fn('now')))
756
+ .execute()
757
+ })
728
758
  ```
729
759
 
730
760
  ### SQLite
731
761
 
732
762
  ```typescript
733
- createMigration(
734
- '001_create_users',
735
- async (db) => {
736
- await db.schema
737
- .createTable('users')
738
- .addColumn('id', 'integer', col =>
739
- col.primaryKey().autoIncrement()
740
- )
741
- .addColumn('created_at', 'text', col =>
742
- col.notNull().defaultTo(sql`CURRENT_TIMESTAMP`)
743
- )
744
- .execute()
745
- }
746
- )
763
+ createMigration('001_create_users', async db => {
764
+ await db.schema
765
+ .createTable('users')
766
+ .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
767
+ .addColumn('created_at', 'text', col => col.notNull().defaultTo(sql`CURRENT_TIMESTAMP`))
768
+ .execute()
769
+ })
747
770
  ```
748
771
 
772
+ ## Implementation Details
773
+
774
+ ### Version File Fallback Pattern
775
+
776
+ The migration system uses a robust version file fallback pattern to ensure compatibility across different build environments:
777
+
778
+ 1. **Primary:** Try to load `version.ts` (development/source code)
779
+ 2. **Fallback:** Try to load `version.js` (compiled/production code)
780
+ 3. **Default:** Use `'0.0.0-dev'` if both fail
781
+
782
+ This pattern ensures migrations work correctly in both development and production environments without requiring specific build configurations.
783
+
749
784
  ## Changelog
750
785
 
751
786
  ### v0.5.1
@@ -758,6 +793,7 @@ createMigration(
758
793
  - **Added** `MigrationDefinition` and `MigrationDefinitions` type exports
759
794
  - **Added** `MigrationRunnerWithPluginsOptions` interface export
760
795
  - **Added** `DatabaseError` and `BadRequestError` re-exports from `@kysera/core`
796
+ - **Added** Version file fallback pattern for cross-environment compatibility
761
797
  - **Changed** Validation errors now throw `BadRequestError` instead of generic `Error`
762
798
 
763
799
  ### v0.5.0
package/dist/index.d.ts CHANGED
@@ -121,10 +121,12 @@ declare function setupMigrations(db: Kysely<unknown>): Promise<void>;
121
121
  * defaults to unknown for maximum flexibility
122
122
  */
123
123
  declare class MigrationRunner<DB = unknown> {
124
- private db;
125
- private migrations;
126
- private logger;
127
- private options;
124
+ protected logger: KyseraLogger;
125
+ protected runnerOptions: Required<Omit<MigrationRunnerOptions, 'logger'>> & {
126
+ logger: KyseraLogger;
127
+ };
128
+ protected db: Kysely<DB>;
129
+ protected migrations: Migration<DB>[];
128
130
  constructor(db: Kysely<DB>, migrations: Migration<DB>[], options?: MigrationRunnerOptions);
129
131
  /**
130
132
  * Get list of executed migrations from database
@@ -144,11 +146,11 @@ declare class MigrationRunner<DB = unknown> {
144
146
  /**
145
147
  * Log migration metadata if available
146
148
  */
147
- private logMigrationMeta;
149
+ protected logMigrationMeta(migration: Migration<DB>): void;
148
150
  /**
149
151
  * Execute a single migration with optional transaction wrapping
150
152
  */
151
- private executeMigration;
153
+ protected executeMigration(migration: Migration<DB>, operation: 'up' | 'down'): Promise<void>;
152
154
  /**
153
155
  * Run all pending migrations
154
156
  */
@@ -261,6 +263,9 @@ declare function createMigrationRunnerWithPlugins<DB = unknown>(db: Kysely<DB>,
261
263
  * Extended migration runner with plugin support
262
264
  * Generic DB type allows type-safe migrations when schema is known,
263
265
  * defaults to unknown for maximum flexibility
266
+ *
267
+ * This class overrides up() and down() to call plugin lifecycle hooks
268
+ * (beforeMigration, afterMigration, onMigrationError) around each migration execution.
264
269
  */
265
270
  declare class MigrationRunnerWithPlugins<DB = unknown> extends MigrationRunner<DB> {
266
271
  private plugins;
@@ -284,6 +289,16 @@ declare class MigrationRunnerWithPlugins<DB = unknown> extends MigrationRunner<D
284
289
  * Get the list of registered plugins
285
290
  */
286
291
  getPlugins(): MigrationPlugin<DB>[];
292
+ /**
293
+ * Run all pending migrations with plugin hooks
294
+ * Overrides parent to call beforeMigration/afterMigration/onMigrationError hooks
295
+ */
296
+ up(): Promise<MigrationResult>;
297
+ /**
298
+ * Rollback last N migrations with plugin hooks
299
+ * Overrides parent to call beforeMigration/afterMigration/onMigrationError hooks
300
+ */
301
+ down(steps?: number): Promise<MigrationResult>;
287
302
  }
288
303
  /**
289
304
  * Logging plugin - logs migration events with timing
@@ -296,12 +311,12 @@ declare function createLoggingPlugin<DB = unknown>(logger?: KyseraLogger): Migra
296
311
  */
297
312
  declare function createMetricsPlugin<DB = unknown>(): MigrationPlugin<DB> & {
298
313
  getMetrics(): {
299
- migrations: Array<{
314
+ migrations: {
300
315
  name: string;
301
316
  operation: string;
302
317
  duration: number;
303
318
  success: boolean;
304
- }>;
319
+ }[];
305
320
  };
306
321
  };
307
322
 
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 as z$1}from'zod';var d=z$1.object({dryRun:z$1.boolean().default(false),logger:z$1.any().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()}),x=z$1.object({logger:z$1.any().optional()}),D=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.any().optional(),beforeMigration:z$1.any().optional(),afterMigration:z$1.any().optional(),onMigrationError:z$1.any().optional()}),b=z$1.object({executed:z$1.array(z$1.string()),pending:z$1.array(z$1.string()),total:z$1.number().int().nonnegative()}),P=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()}),B=d.extend({plugins:z$1.array(D).optional()});function k(e){return d.parse(e)}function O(e){return d.safeParse(e)}function E(e){return m.parse(e)}function v(e){return m.safeParse(e)}var f=class extends DatabaseError{migrationName;operation;constructor(n,i,t,o){let a=t==="up"?"MIGRATION_UP_FAILED":"MIGRATION_DOWN_FAILED";super(n,a,i),this.name="MigrationError",this.migrationName=i,this.operation=t,o&&(this.cause=o);}toJSON(){let n=this.cause instanceof Error?this.cause:void 0;return {...super.toJSON(),migrationName:this.migrationName,operation:this.operation,cause:n?.message}}};async function c(e){await e.schema.createTable("migrations").ifNotExists().addColumn("name","varchar(255)",n=>n.primaryKey()).addColumn("executed_at","timestamp",n=>n.notNull().defaultTo(sql`CURRENT_TIMESTAMP`)).execute();}function h(e){return "description"in e||"breaking"in e||"tags"in e}function M(e){return e instanceof Error?e.message:String(e)}function N(e){let n=new Set;for(let i of e){if(n.has(i.name))throw new BadRequestError(`Duplicate migration name: ${i.name}`);n.add(i.name);}}var p=class{constructor(n,i,t={}){this.db=n;this.migrations=i;let o=d.safeParse(t);if(!o.success)throw new BadRequestError(`Invalid migration runner options: ${o.error.message}`);this.logger=t.logger??silentLogger,this.options={dryRun:o.data.dryRun,logger:this.logger,useTransactions:o.data.useTransactions,stopOnError:o.data.stopOnError,verbose:o.data.verbose},N(i);}logger;options;async getExecutedMigrations(){return await c(this.db),(await this.db.selectFrom("migrations").select("name").orderBy("executed_at","asc").execute()).map(i=>i.name)}async markAsExecuted(n){await this.db.insertInto("migrations").values({name:n}).execute();}async markAsRolledBack(n){await this.db.deleteFrom("migrations").where("name","=",n).execute();}logMigrationMeta(n){if(!this.options.verbose||!h(n))return;let i=n;if(i.description&&this.logger.info(` Description: ${i.description}`),i.breaking&&this.logger.warn(" BREAKING CHANGE - Review carefully before proceeding"),i.tags&&i.tags.length>0&&this.logger.info(` Tags: ${i.tags.join(", ")}`),i.estimatedDuration){let t=(i.estimatedDuration/1e3).toFixed(1);this.logger.info(` Estimated: ${t}s`);}}async executeMigration(n,i){let t=i==="up"?n.up:n.down;t&&(this.options.useTransactions?await this.db.transaction().execute(async o=>{await t(o);}):await t(this.db));}async up(){let n=Date.now(),i={executed:[],skipped:[],failed:[],duration:0,dryRun:this.options.dryRun};await c(this.db);let t=await this.getExecutedMigrations();if(this.migrations.filter(a=>!t.includes(a.name)).length===0)return this.logger.info("No pending migrations"),i.skipped=t,i.duration=Date.now()-n,i;this.options.dryRun&&this.logger.info("DRY RUN - No changes will be made");for(let a of this.migrations){if(t.includes(a.name)){this.logger.info(`${a.name} (already executed)`),i.skipped.push(a.name);continue}try{this.logger.info(`Running ${a.name}...`),this.logMigrationMeta(a),this.options.dryRun||(await this.executeMigration(a,"up"),await this.markAsExecuted(a.name)),this.logger.info(`${a.name} completed`),i.executed.push(a.name);}catch(g){let s=M(g);if(this.logger.error(`${a.name} failed: ${s}`),i.failed.push(a.name),this.options.stopOnError)throw new f(`Migration ${a.name} failed: ${s}`,a.name,"up",g instanceof Error?g:void 0)}}return this.options.dryRun?this.logger.info("Dry run completed - no changes made"):this.logger.info("All migrations completed successfully"),i.duration=Date.now()-n,i}async down(n=1){let i=Date.now(),t={executed:[],skipped:[],failed:[],duration:0,dryRun:this.options.dryRun};await c(this.db);let o=await this.getExecutedMigrations();if(o.length===0)return this.logger.warn("No executed migrations to rollback"),t.duration=Date.now()-i,t;let a=o.slice(-n).reverse();this.options.dryRun&&this.logger.info("DRY RUN - No changes will be made");for(let g of a){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.options.dryRun||(await this.executeMigration(s,"down"),await this.markAsRolledBack(g)),this.logger.info(`${g} rolled back`),t.executed.push(g);}catch(u){let l=M(u);if(this.logger.error(`${g} rollback failed: ${l}`),t.failed.push(g),this.options.stopOnError)throw new f(`Rollback of ${g} failed: ${l}`,g,"down",u instanceof Error?u:void 0)}}return this.options.dryRun?this.logger.info("Dry run completed - no changes made"):this.logger.info("Rollback completed successfully"),t.duration=Date.now()-i,t}async status(){await c(this.db);let n=await this.getExecutedMigrations(),i=this.migrations.filter(t=>!n.includes(t.name)).map(t=>t.name);if(this.logger.info("Migration Status:"),this.logger.info(` Executed: ${n.length}`),this.logger.info(` Pending: ${i.length}`),this.logger.info(` Total: ${this.migrations.length}`),n.length>0){this.logger.info("Executed migrations:");for(let t of n){let o=this.migrations.find(a=>a.name===t);o&&h(o)&&o.description?this.logger.info(` ${t} - ${o.description}`):this.logger.info(` ${t}`);}}if(i.length>0){this.logger.info("Pending migrations:");for(let t of i){let o=this.migrations.find(a=>a.name===t);if(o&&h(o)){let a=o,g=a.breaking?" BREAKING":"",s=a.description?` - ${a.description}`:"";this.logger.info(` ${t}${s}${g}`);}else this.logger.info(` ${t}`);}}return {executed:n,pending:i,total:this.migrations.length}}async reset(){let n=Date.now();await c(this.db);let i=await this.getExecutedMigrations();if(i.length===0)return this.logger.warn("No migrations to reset"),{executed:[],skipped:[],failed:[],duration:Date.now()-n,dryRun:this.options.dryRun};if(this.logger.warn(`Resetting ${i.length} migrations...`),this.options.dryRun){this.logger.info("DRY RUN - Would rollback the following migrations:");for(let o of [...i].reverse())this.migrations.find(g=>g.name===o)?.down?this.logger.info(` ${o}`):this.logger.warn(` ${o} (no down method - would be skipped)`);return this.logger.info("Dry run completed - no changes made"),{executed:[],skipped:i,failed:[],duration:Date.now()-n,dryRun:true}}let t=await this.down(i.length);return this.logger.info("All migrations reset"),t}async upTo(n){let i=Date.now(),t={executed:[],skipped:[],failed:[],duration:0,dryRun:this.options.dryRun};await c(this.db);let o=await this.getExecutedMigrations(),a=this.migrations.findIndex(s=>s.name===n);if(a===-1)throw new NotFoundError("Migration",{name:n});let g=this.migrations.slice(0,a+1);this.options.dryRun&&this.logger.info("DRY RUN - No changes will be made");for(let s of g){if(o.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.options.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 l=M(u);throw this.logger.error(`${s.name} failed: ${l}`),t.failed.push(s.name),new f(`Migration ${s.name} failed: ${l}`,s.name,"up",u instanceof Error?u:void 0)}}return this.options.dryRun?this.logger.info(`Dry run completed - would migrate up to ${n}`):this.logger.info(`Migrated up to ${n}`),t.duration=Date.now()-i,t}};function z(e,n,i){return new p(e,n,i)}function _(e,n,i){let t={name:e,up:n};return i!==void 0&&(t.down=i),t}function F(e,n){let i={name:e,up:n.up};return n.down!==void 0&&(i.down=n.down),n.description!==void 0&&(i.description=n.description),n.breaking!==void 0&&(i.breaking=n.breaking),n.estimatedDuration!==void 0&&(i.estimatedDuration=n.estimatedDuration),n.tags!==void 0&&(i.tags=n.tags),i}function j(e){return Object.entries(e).map(([n,i])=>{let t={name:n,up:i.up};return i.down!==void 0&&(t.down=i.down),i.description!==void 0&&(t.description=i.description),i.breaking!==void 0&&(t.breaking=i.breaking),i.estimatedDuration!==void 0&&(t.estimatedDuration=i.estimatedDuration),i.tags!==void 0&&(t.tags=i.tags),t})}async function G(e,n,i){return new p(e,n,i).up()}async function q(e,n,i=1,t){return new p(e,n,t).down(i)}async function C(e,n,i){return new p(e,n,i).status()}async function U(e,n,i){let t=new y(e,n,i);if(i?.plugins){for(let o of i.plugins)if(o.onInit){let a=o.onInit(t);a instanceof Promise&&await a;}}return t}var y=class extends p{plugins;constructor(n,i,t={}){super(n,i,t),this.plugins=t.plugins??[];}async runBeforeHooks(n,i){for(let t of this.plugins)t.beforeMigration&&await t.beforeMigration(n,i);}async runAfterHooks(n,i,t){for(let o of this.plugins)o.afterMigration&&await o.afterMigration(n,i,t);}async runErrorHooks(n,i,t){for(let o of this.plugins)o.onMigrationError&&await o.onMigrationError(n,i,t);}getPlugins(){return [...this.plugins]}};function H(e=silentLogger){return {name:"@kysera/migrations/logging",version:"0.5.1",beforeMigration(n,i){e.info(`Starting ${i} for ${n.name}`);},afterMigration(n,i,t){e.info(`Completed ${i} for ${n.name} in ${t}ms`);},onMigrationError(n,i,t){let o=t instanceof Error?t.message:String(t);e.error(`Error during ${i} for ${n.name}: ${o}`);}}}function Y(){let e=[];return {name:"@kysera/migrations/metrics",version:"0.5.1",afterMigration(n,i,t){e.push({name:n.name,operation:i,duration:t,success:true});},onMigrationError(n,i){e.push({name:n.name,operation:i,duration:0,success:false});},getMetrics(){return {migrations:[...e]}}}}export{m as MigrationDefinitionSchema,f as MigrationError,x as MigrationPluginOptionsSchema,D as MigrationPluginSchema,P as MigrationResultSchema,p as MigrationRunner,d as MigrationRunnerOptionsSchema,y as MigrationRunnerWithPlugins,B as MigrationRunnerWithPluginsOptionsSchema,b as MigrationStatusSchema,H as createLoggingPlugin,Y as createMetricsPlugin,_ as createMigration,z as createMigrationRunner,U as createMigrationRunnerWithPlugins,F as createMigrationWithMeta,j as defineMigrations,C as getMigrationStatus,E as parseMigrationDefinition,k as parseMigrationRunnerOptions,q as rollbackMigrations,G as runMigrations,v as safeParseMigrationDefinition,O as safeParseMigrationRunnerOptions,c as setupMigrations};//# sourceMappingURL=index.js.map
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
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/schemas.ts","../src/index.ts"],"names":["MigrationRunnerOptionsSchema","z","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","createLoggingPlugin","logger","createMetricsPlugin","metrics"],"mappings":"2NAUO,IAAMA,CAAAA,CAA+BC,GAAAA,CAAE,MAAA,CAAO,CAEnD,MAAA,CAAQA,GAAAA,CAAE,OAAA,EAAQ,CAAE,OAAA,CAAQ,KAAK,EAEjC,MAAA,CAAQA,GAAAA,CAAE,GAAA,EAAI,CAAE,QAAA,EAAS,CAEzB,eAAA,CAAiBA,GAAAA,CAAE,OAAA,EAAQ,CAAE,OAAA,CAAQ,KAAK,CAAA,CAE1C,WAAA,CAAaA,GAAAA,CAAE,OAAA,EAAQ,CAAE,OAAA,CAAQ,IAAI,CAAA,CAErC,OAAA,CAASA,GAAAA,CAAE,OAAA,EAAQ,CAAE,OAAA,CAAQ,IAAI,CACnC,CAAC,CAAA,CAUYC,CAAAA,CAA4BD,GAAAA,CAAE,MAAA,CAAO,CAEhD,IAAA,CAAMA,GAAAA,CAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAA,CAAG,4BAA4B,CAAA,CAEpD,WAAA,CAAaA,GAAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS,CAEjC,QAAA,CAAUA,GAAAA,CAAE,OAAA,EAAQ,CAAE,OAAA,CAAQ,KAAK,CAAA,CAEnC,IAAA,CAAMA,GAAAA,CAAE,KAAA,CAAMA,GAAAA,CAAE,MAAA,EAAQ,CAAA,CAAE,OAAA,CAAQ,EAAE,CAAA,CAEpC,kBAAmBA,GAAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAChC,CAAC,CAAA,CAUYE,CAAAA,CAA+BF,GAAAA,CAAE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sD,CAAAA,CAAU,CAC7CE,CAAAA,CAAO,KAAK,CAAA,UAAA,EAAaxD,CAAS,CAAA,KAAA,EAAQS,CAAAA,CAAU,IAAI,CAAA,IAAA,EAAO6C,CAAQ,CAAA,EAAA,CAAI,EAC7E,CAAA,CACA,gBAAA,CAAiB7C,CAAAA,CAAWT,CAAAA,CAAWW,CAAAA,CAAO,CAC5C,IAAMb,EAAUa,CAAAA,YAAiB,KAAA,CAAQA,CAAAA,CAAM,OAAA,CAAU,MAAA,CAAOA,CAAK,CAAA,CACrE6C,CAAAA,CAAO,KAAA,CAAM,CAAA,aAAA,EAAgBxD,CAAS,CAAA,KAAA,EAAQS,CAAAA,CAAU,IAAI,CAAA,EAAA,EAAKX,CAAO,EAAE,EAC5E,CACF,CACF,CAMO,SAAS2D,CAAAA,EAEd,CACA,IAAMC,CAAAA,CAA0F,EAAC,CAEjG,OAAO,CACL,IAAA,CAAM,4BAAA,CACN,OAAA,CAAS,OAAA,CACT,cAAA,CAAejD,CAAAA,CAAWT,CAAAA,CAAWsD,CAAAA,CAAU,CAC7CI,CAAAA,CAAQ,IAAA,CAAK,CAAE,IAAA,CAAMjD,CAAAA,CAAU,IAAA,CAAM,SAAA,CAAAT,CAAAA,CAAW,QAAA,CAAAsD,CAAAA,CAAU,QAAS,IAAK,CAAC,EAC3E,CAAA,CACA,gBAAA,CAAiB7C,CAAAA,CAAWT,CAAAA,CAAW,CACrC0D,CAAAA,CAAQ,IAAA,CAAK,CAAE,IAAA,CAAMjD,CAAAA,CAAU,IAAA,CAAM,SAAA,CAAAT,CAAAA,CAAW,SAAU,CAAA,CAAG,OAAA,CAAS,KAAM,CAAC,EAC/E,CAAA,CACA,UAAA,EAAa,CACX,OAAO,CAAE,UAAA,CAAY,CAAC,GAAG0D,CAAO,CAAE,CACpC,CACF,CACF","file":"index.js","sourcesContent":["import { z } from 'zod';\n\n// ============================================================================\n// Migration Runner Options Schema\n// ============================================================================\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 function - validated as any since function schemas are complex in Zod v4 */\n logger: z.any().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: z.any().optional(),\n});\n\n// ============================================================================\n// Migration Plugin Schema\n// ============================================================================\n\n/**\n * Schema for MigrationPlugin\n * Validates migration plugin structure\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.any().optional(),\n /** Called before migration execution */\n beforeMigration: z.any().optional(),\n /** Called after successful migration execution */\n afterMigration: z.any().optional(),\n /** Called on migration error */\n onMigrationError: z.any().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<typeof MigrationRunnerWithPluginsOptionsSchema>;\n\n/** Output type for MigrationRunnerWithPluginsOptions */\nexport type MigrationRunnerWithPluginsOptionsOutput = z.output<typeof MigrationRunnerWithPluginsOptionsSchema>;\n\n// ============================================================================\n// Validation Helpers\n// ============================================================================\n\n/**\n * Validate and parse MigrationRunnerOptions with defaults\n */\nexport function parseMigrationRunnerOptions(\n options: unknown\n): 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(\n definition: unknown\n): 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';\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 = 'MIGRATION_UP_FAILED' | 'MIGRATION_DOWN_FAILED' | '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(\n message: string,\n migrationName: string,\n operation: 'up' | 'down',\n cause?: Error\n ) {\n const code: MigrationErrorCode = 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\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 private logger: KyseraLogger;\n private options: Required<Omit<MigrationRunnerOptions, 'logger'>> & { logger: KyseraLogger };\n\n constructor(\n private db: Kysely<DB>,\n private migrations: Migration<DB>[],\n options: MigrationRunnerOptions = {}\n ) {\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.logger = options.logger ?? silentLogger;\n this.options = {\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 Array<{ 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)\n .insertInto('migrations')\n .values({ name })\n .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)\n .deleteFrom('migrations')\n .where('name', '=', name)\n .execute();\n }\n\n /**\n * Log migration metadata if available\n */\n private logMigrationMeta(migration: Migration<DB>): void {\n if (!this.options.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 private 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.options.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.options.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.options.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.options.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.options.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.options.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.options.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.options.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.options.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.options.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.options.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.options.dryRun,\n };\n }\n\n this.logger.warn(`Resetting ${executed.length} migrations...`);\n\n if (this.options.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.options.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.options.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.options.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.options.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>(definitions: MigrationDefinitions<DB>): 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 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 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 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?(migration: Migration<DB>, operation: 'up' | 'down', duration: number): Promise<void> | void;\n /** Called on migration error (unknown type for consistency with repository Plugin.onError) */\n onMigrationError?(migration: Migration<DB>, operation: 'up' | 'down', error: unknown): 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 */\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(migration: Migration<DB>, operation: 'up' | 'down'): 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// ============================================================================\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: '0.5.1',\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(): { migrations: Array<{ name: string; operation: string; duration: number; success: boolean }> };\n} {\n const metrics: Array<{ name: string; operation: string; duration: number; success: boolean }> = [];\n\n return {\n name: '@kysera/migrations/metrics',\n version: '0.5.1',\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","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,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,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"]}
package/dist/schemas.d.ts CHANGED
@@ -6,7 +6,14 @@ import { z } from 'zod';
6
6
  */
7
7
  declare const MigrationRunnerOptionsSchema: z.ZodObject<{
8
8
  dryRun: z.ZodDefault<z.ZodBoolean>;
9
- logger: z.ZodOptional<z.ZodAny>;
9
+ logger: z.ZodOptional<z.ZodObject<{
10
+ trace: z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
11
+ debug: z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
12
+ info: z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
13
+ warn: z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
14
+ error: z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
15
+ fatal: z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
16
+ }, z.core.$loose>>;
10
17
  useTransactions: z.ZodDefault<z.ZodBoolean>;
11
18
  stopOnError: z.ZodDefault<z.ZodBoolean>;
12
19
  verbose: z.ZodDefault<z.ZodBoolean>;
@@ -27,19 +34,29 @@ declare const MigrationDefinitionSchema: z.ZodObject<{
27
34
  * Validates options passed to migration plugins
28
35
  */
29
36
  declare const MigrationPluginOptionsSchema: z.ZodObject<{
30
- logger: z.ZodOptional<z.ZodAny>;
37
+ logger: z.ZodOptional<z.ZodObject<{
38
+ trace: z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
39
+ debug: z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
40
+ info: z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
41
+ warn: z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
42
+ error: z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
43
+ fatal: z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
44
+ }, z.core.$loose>>;
31
45
  }, z.core.$strip>;
32
46
  /**
33
47
  * Schema for MigrationPlugin
34
- * Validates migration plugin structure
48
+ * Validates migration plugin structure.
49
+ *
50
+ * Note: Lifecycle hooks are validated as functions. Full type safety for
51
+ * generic parameters (Migration<DB>) is provided by TypeScript interfaces.
35
52
  */
36
53
  declare const MigrationPluginSchema: z.ZodObject<{
37
54
  name: z.ZodString;
38
55
  version: z.ZodString;
39
- onInit: z.ZodOptional<z.ZodAny>;
40
- beforeMigration: z.ZodOptional<z.ZodAny>;
41
- afterMigration: z.ZodOptional<z.ZodAny>;
42
- onMigrationError: z.ZodOptional<z.ZodAny>;
56
+ onInit: z.ZodOptional<z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>>;
57
+ beforeMigration: z.ZodOptional<z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>>;
58
+ afterMigration: z.ZodOptional<z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>>;
59
+ onMigrationError: z.ZodOptional<z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>>;
43
60
  }, z.core.$strip>;
44
61
  /**
45
62
  * Schema for MigrationStatus
@@ -67,17 +84,24 @@ declare const MigrationResultSchema: z.ZodObject<{
67
84
  */
68
85
  declare const MigrationRunnerWithPluginsOptionsSchema: z.ZodObject<{
69
86
  dryRun: z.ZodDefault<z.ZodBoolean>;
70
- logger: z.ZodOptional<z.ZodAny>;
87
+ logger: z.ZodOptional<z.ZodObject<{
88
+ trace: z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
89
+ debug: z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
90
+ info: z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
91
+ warn: z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
92
+ error: z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
93
+ fatal: z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
94
+ }, z.core.$loose>>;
71
95
  useTransactions: z.ZodDefault<z.ZodBoolean>;
72
96
  stopOnError: z.ZodDefault<z.ZodBoolean>;
73
97
  verbose: z.ZodDefault<z.ZodBoolean>;
74
98
  plugins: z.ZodOptional<z.ZodArray<z.ZodObject<{
75
99
  name: z.ZodString;
76
100
  version: z.ZodString;
77
- onInit: z.ZodOptional<z.ZodAny>;
78
- beforeMigration: z.ZodOptional<z.ZodAny>;
79
- afterMigration: z.ZodOptional<z.ZodAny>;
80
- onMigrationError: z.ZodOptional<z.ZodAny>;
101
+ onInit: z.ZodOptional<z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>>;
102
+ beforeMigration: z.ZodOptional<z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>>;
103
+ afterMigration: z.ZodOptional<z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>>;
104
+ onMigrationError: z.ZodOptional<z.ZodFunction<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>>;
81
105
  }, z.core.$strip>>>;
82
106
  }, z.core.$strip>;
83
107
  /** Input type for MigrationRunnerOptions - before defaults are applied */
@@ -117,7 +141,15 @@ declare function safeParseMigrationRunnerOptions(options: unknown): z.ZodSafePar
117
141
  useTransactions: boolean;
118
142
  stopOnError: boolean;
119
143
  verbose: boolean;
120
- logger?: any;
144
+ logger?: {
145
+ [x: string]: unknown;
146
+ trace: z.core.$InferOuterFunctionType<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
147
+ debug: z.core.$InferOuterFunctionType<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
148
+ info: z.core.$InferOuterFunctionType<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
149
+ warn: z.core.$InferOuterFunctionType<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
150
+ error: z.core.$InferOuterFunctionType<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
151
+ fatal: z.core.$InferOuterFunctionType<z.core.$ZodFunctionArgs, z.core.$ZodFunctionOut>;
152
+ } | undefined;
121
153
  }>;
122
154
  /**
123
155
  * Validate and parse MigrationDefinition with defaults
package/dist/schemas.js CHANGED
@@ -1,2 +1,2 @@
1
- import {z}from'zod';var i=z.object({dryRun:z.boolean().default(false),logger:z.any().optional(),useTransactions:z.boolean().default(false),stopOnError:z.boolean().default(true),verbose:z.boolean().default(true)}),o=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()}),a=z.object({logger:z.any().optional()}),e=z.object({name:z.string().min(1,"Plugin name is required"),version:z.string().min(1,"Plugin version is required"),onInit:z.any().optional(),beforeMigration:z.any().optional(),afterMigration:z.any().optional(),onMigrationError:z.any().optional()}),p=z.object({executed:z.array(z.string()),pending:z.array(z.string()),total:z.number().int().nonnegative()}),u=z.object({executed:z.array(z.string()),skipped:z.array(z.string()),failed:z.array(z.string()),duration:z.number().nonnegative(),dryRun:z.boolean()}),g=i.extend({plugins:z.array(e).optional()});function s(n){return i.parse(n)}function l(n){return i.safeParse(n)}function f(n){return o.parse(n)}function y(n){return o.safeParse(n)}export{o as MigrationDefinitionSchema,a as MigrationPluginOptionsSchema,e as MigrationPluginSchema,u as MigrationResultSchema,i as MigrationRunnerOptionsSchema,g as MigrationRunnerWithPluginsOptionsSchema,p as MigrationStatusSchema,f as parseMigrationDefinition,s as parseMigrationRunnerOptions,y as safeParseMigrationDefinition,l as safeParseMigrationRunnerOptions};//# sourceMappingURL=schemas.js.map
1
+ import {z}from'zod';var o=z.object({trace:z.function(),debug:z.function(),info:z.function(),warn:z.function(),error:z.function(),fatal:z.function()}).passthrough(),i=z.object({dryRun:z.boolean().default(false),logger:o.optional(),useTransactions:z.boolean().default(false),stopOnError:z.boolean().default(true),verbose:z.boolean().default(true)}),e=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()}),u=z.object({logger:o.optional()}),r=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()}),g=z.object({executed:z.array(z.string()),skipped:z.array(z.string()),failed:z.array(z.string()),duration:z.number().nonnegative(),dryRun:z.boolean()}),s=i.extend({plugins:z.array(r).optional()});function f(n){return i.parse(n)}function c(n){return i.safeParse(n)}function l(n){return e.parse(n)}function M(n){return e.safeParse(n)}export{e as MigrationDefinitionSchema,u as MigrationPluginOptionsSchema,r as MigrationPluginSchema,g as MigrationResultSchema,i as MigrationRunnerOptionsSchema,s as MigrationRunnerWithPluginsOptionsSchema,p as MigrationStatusSchema,l as parseMigrationDefinition,f as parseMigrationRunnerOptions,M as safeParseMigrationDefinition,c as safeParseMigrationRunnerOptions};//# sourceMappingURL=schemas.js.map
2
2
  //# sourceMappingURL=schemas.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/schemas.ts"],"names":["MigrationRunnerOptionsSchema","z","MigrationDefinitionSchema","MigrationPluginOptionsSchema","MigrationPluginSchema","MigrationStatusSchema","MigrationResultSchema","MigrationRunnerWithPluginsOptionsSchema","parseMigrationRunnerOptions","options","safeParseMigrationRunnerOptions","parseMigrationDefinition","definition","safeParseMigrationDefinition"],"mappings":"oBAUO,IAAMA,CAAAA,CAA+BC,CAAAA,CAAE,MAAA,CAAO,CAEnD,MAAA,CAAQA,CAAAA,CAAE,OAAA,EAAQ,CAAE,OAAA,CAAQ,KAAK,CAAA,CAEjC,MAAA,CAAQA,CAAAA,CAAE,GAAA,EAAI,CAAE,QAAA,EAAS,CAEzB,eAAA,CAAiBA,CAAAA,CAAE,OAAA,EAAQ,CAAE,OAAA,CAAQ,KAAK,CAAA,CAE1C,YAAaA,CAAAA,CAAE,OAAA,EAAQ,CAAE,OAAA,CAAQ,IAAI,CAAA,CAErC,OAAA,CAASA,CAAAA,CAAE,OAAA,EAAQ,CAAE,OAAA,CAAQ,IAAI,CACnC,CAAC,CAAA,CAUYC,CAAAA,CAA4BD,CAAAA,CAAE,MAAA,CAAO,CAEhD,IAAA,CAAMA,CAAAA,CAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAA,CAAG,4BAA4B,CAAA,CAEpD,WAAA,CAAaA,CAAAA,CAAE,MAAA,EAAO,CAAE,QAAA,GAExB,QAAA,CAAUA,CAAAA,CAAE,OAAA,EAAQ,CAAE,OAAA,CAAQ,KAAK,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AAA,CAASA,CAAAA,CAAE,KAAA,CAAMA,CAAAA,CAAE,MAAA,EAAQ,CAAA,CAE3B,MAAA,CAAQA,CAAAA,CAAE,MAAMA,CAAAA,CAAE,MAAA,EAAQ,CAAA,CAE1B,QAAA,CAAUA,CAAAA,CAAE,MAAA,EAAO,CAAE,WAAA,EAAY,CAEjC,MAAA,CAAQA,CAAAA,CAAE,OAAA,EACZ,CAAC,CAAA,CAUYM,CAAAA,CAA0CP,CAAAA,CAA6B,MAAA,CAAO,CAEzF,OAAA,CAASC,CAAAA,CAAE,KAAA,CAAMG,CAAqB,CAAA,CAAE,QAAA,EAC1C,CAAC,EAiDM,SAASI,CAAAA,CACdC,CAAAA,CAC8B,CAC9B,OAAOT,CAAAA,CAA6B,KAAA,CAAMS,CAAO,CACnD,CAMO,SAASC,CAAAA,CAAgCD,CAAAA,CAAkB,CAChE,OAAOT,CAAAA,CAA6B,SAAA,CAAUS,CAAO,CACvD,CAKO,SAASE,CAAAA,CACdC,CAAAA,CAC2B,CAC3B,OAAOV,CAAAA,CAA0B,KAAA,CAAMU,CAAU,CACnD,CAMO,SAASC,CAAAA,CAA6BD,CAAAA,CAAqB,CAChE,OAAOV,CAAAA,CAA0B,SAAA,CAAUU,CAAU,CACvD","file":"schemas.js","sourcesContent":["import { z } from 'zod';\n\n// ============================================================================\n// Migration Runner Options Schema\n// ============================================================================\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 function - validated as any since function schemas are complex in Zod v4 */\n logger: z.any().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: z.any().optional(),\n});\n\n// ============================================================================\n// Migration Plugin Schema\n// ============================================================================\n\n/**\n * Schema for MigrationPlugin\n * Validates migration plugin structure\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.any().optional(),\n /** Called before migration execution */\n beforeMigration: z.any().optional(),\n /** Called after successful migration execution */\n afterMigration: z.any().optional(),\n /** Called on migration error */\n onMigrationError: z.any().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<typeof MigrationRunnerWithPluginsOptionsSchema>;\n\n/** Output type for MigrationRunnerWithPluginsOptions */\nexport type MigrationRunnerWithPluginsOptionsOutput = z.output<typeof MigrationRunnerWithPluginsOptionsSchema>;\n\n// ============================================================================\n// Validation Helpers\n// ============================================================================\n\n/**\n * Validate and parse MigrationRunnerOptions with defaults\n */\nexport function parseMigrationRunnerOptions(\n options: unknown\n): 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(\n definition: unknown\n): 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"]}
1
+ {"version":3,"sources":["../src/schemas.ts"],"names":["LoggerSchema","z","MigrationRunnerOptionsSchema","MigrationDefinitionSchema","MigrationPluginOptionsSchema","MigrationPluginSchema","MigrationStatusSchema","MigrationResultSchema","MigrationRunnerWithPluginsOptionsSchema","parseMigrationRunnerOptions","options","safeParseMigrationRunnerOptions","parseMigrationDefinition","definition","safeParseMigrationDefinition"],"mappings":"oBAUA,IAAMA,EAAeC,CAAAA,CAClB,MAAA,CAAO,CACN,KAAA,CAAOA,CAAAA,CAAE,QAAA,EAAS,CAClB,KAAA,CAAOA,EAAE,QAAA,EAAS,CAClB,IAAA,CAAMA,CAAAA,CAAE,QAAA,EAAS,CACjB,IAAA,CAAMA,CAAAA,CAAE,UAAS,CACjB,KAAA,CAAOA,CAAAA,CAAE,QAAA,EAAS,CAClB,KAAA,CAAOA,CAAAA,CAAE,QAAA,EACX,CAAC,CAAA,CACA,WAAA,EAAY,CAMFC,CAAAA,CAA+BD,CAAAA,CAAE,MAAA,CAAO,CAEnD,OAAQA,CAAAA,CAAE,OAAA,EAAQ,CAAE,OAAA,CAAQ,KAAK,CAAA,CAEjC,MAAA,CAA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============================================================================\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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kysera/migrations",
3
- "version": "0.7.2",
3
+ "version": "0.7.4",
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,28 +26,23 @@
26
26
  "author": "Kysera Team",
27
27
  "license": "MIT",
28
28
  "dependencies": {
29
- "@kysera/core": "0.7.2"
29
+ "@kysera/core": "0.7.4"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@types/better-sqlite3": "^7.6.13",
33
33
  "@types/node": "^24.10.1",
34
- "@vitest/coverage-v8": "^4.0.15",
34
+ "@vitest/coverage-v8": "^4.0.16",
35
35
  "better-sqlite3": "^12.5.0",
36
36
  "kysely": "^0.28.9",
37
37
  "tsup": "^8.5.1",
38
38
  "typescript": "^5.9.3",
39
- "vitest": "^4.0.15",
39
+ "vitest": "^4.0.16",
40
40
  "zod": "^4.1.13"
41
41
  },
42
42
  "peerDependencies": {
43
43
  "kysely": ">=0.28.8",
44
44
  "zod": "^4.1.13"
45
45
  },
46
- "peerDependenciesMeta": {
47
- "zod": {
48
- "optional": true
49
- }
50
- },
51
46
  "sideEffects": false,
52
47
  "engines": {
53
48
  "node": ">=20.0.0",