@warlock.js/cascade 5.30.0 → 5.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (277) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +1 -5
  3. package/cjs/index.cjs +104 -86
  4. package/cjs/index.cjs.map +1 -1
  5. package/esm/context/database-data-source-context.d.mts +2 -3
  6. package/esm/context/database-data-source-context.d.mts.map +1 -1
  7. package/esm/context/database-transaction-context.d.mts +2 -3
  8. package/esm/context/database-transaction-context.d.mts.map +1 -1
  9. package/esm/contracts/database-driver.contract.d.mts +56 -36
  10. package/esm/contracts/database-driver.contract.d.mts.map +1 -1
  11. package/esm/contracts/database-id-generator.contract.d.mts +7 -5
  12. package/esm/contracts/database-id-generator.contract.d.mts.map +1 -1
  13. package/esm/contracts/database-remover.contract.d.mts +3 -5
  14. package/esm/contracts/database-remover.contract.d.mts.map +1 -1
  15. package/esm/contracts/database-restorer.contract.d.mts +6 -6
  16. package/esm/contracts/database-restorer.contract.d.mts.map +1 -1
  17. package/esm/contracts/database-writer.contract.d.mts +4 -6
  18. package/esm/contracts/database-writer.contract.d.mts.map +1 -1
  19. package/esm/contracts/driver-blueprint.contract.d.mts +2 -3
  20. package/esm/contracts/driver-blueprint.contract.d.mts.map +1 -1
  21. package/esm/contracts/index.d.mts +2 -1
  22. package/esm/contracts/migration-driver.contract.d.mts +101 -53
  23. package/esm/contracts/migration-driver.contract.d.mts.map +1 -1
  24. package/esm/contracts/query-builder.contract.d.mts +51 -33
  25. package/esm/contracts/query-builder.contract.d.mts.map +1 -1
  26. package/esm/contracts/sync-adapter.contract.d.mts +25 -14
  27. package/esm/contracts/sync-adapter.contract.d.mts.map +1 -1
  28. package/esm/data-source/data-source-registry.d.mts +4 -5
  29. package/esm/data-source/data-source-registry.d.mts.map +1 -1
  30. package/esm/data-source/data-source-registry.mjs.map +1 -1
  31. package/esm/data-source/data-source.d.mts +8 -5
  32. package/esm/data-source/data-source.d.mts.map +1 -1
  33. package/esm/database-dirty-tracker.d.mts +2 -2
  34. package/esm/database-dirty-tracker.d.mts.map +1 -1
  35. package/esm/database-dirty-tracker.mjs +3 -2
  36. package/esm/database-dirty-tracker.mjs.map +1 -1
  37. package/esm/drivers/mongodb/mongodb-driver.d.mts +3 -4
  38. package/esm/drivers/mongodb/mongodb-driver.d.mts.map +1 -1
  39. package/esm/drivers/mongodb/mongodb-driver.mjs.map +1 -1
  40. package/esm/drivers/mongodb/mongodb-id-generator.d.mts +2 -3
  41. package/esm/drivers/mongodb/mongodb-id-generator.d.mts.map +1 -1
  42. package/esm/drivers/mongodb/mongodb-id-generator.mjs.map +1 -1
  43. package/esm/drivers/mongodb/mongodb-migration-driver.d.mts +1 -3
  44. package/esm/drivers/mongodb/mongodb-migration-driver.d.mts.map +1 -1
  45. package/esm/drivers/mongodb/mongodb-query-builder.d.mts +2 -3
  46. package/esm/drivers/mongodb/mongodb-query-builder.d.mts.map +1 -1
  47. package/esm/drivers/mongodb/mongodb-query-builder.mjs +8 -5
  48. package/esm/drivers/mongodb/mongodb-query-builder.mjs.map +1 -1
  49. package/esm/drivers/mongodb/mongodb-query-operations.d.mts +1 -3
  50. package/esm/drivers/mongodb/mongodb-query-operations.d.mts.map +1 -1
  51. package/esm/drivers/mongodb/mongodb-query-operations.mjs.map +1 -1
  52. package/esm/drivers/mongodb/mongodb-query-parser.d.mts +7 -6
  53. package/esm/drivers/mongodb/mongodb-query-parser.d.mts.map +1 -1
  54. package/esm/drivers/mongodb/mongodb-query-parser.mjs +2 -6
  55. package/esm/drivers/mongodb/mongodb-query-parser.mjs.map +1 -1
  56. package/esm/drivers/mongodb/mongodb-sync-adapter.d.mts +1 -3
  57. package/esm/drivers/mongodb/mongodb-sync-adapter.d.mts.map +1 -1
  58. package/esm/drivers/mongodb/types.d.mts +11 -9
  59. package/esm/drivers/mongodb/types.d.mts.map +1 -1
  60. package/esm/drivers/postgres/index.d.mts +2 -1
  61. package/esm/drivers/postgres/index.mjs +1 -1
  62. package/esm/drivers/postgres/naming.mjs +1 -1
  63. package/esm/drivers/postgres/naming.mjs.map +1 -1
  64. package/esm/drivers/postgres/postgres-blueprint.d.mts +1 -3
  65. package/esm/drivers/postgres/postgres-blueprint.d.mts.map +1 -1
  66. package/esm/drivers/postgres/postgres-dialect.d.mts +4 -6
  67. package/esm/drivers/postgres/postgres-dialect.d.mts.map +1 -1
  68. package/esm/drivers/postgres/postgres-dialect.mjs.map +1 -1
  69. package/esm/drivers/postgres/postgres-driver.d.mts +4 -5
  70. package/esm/drivers/postgres/postgres-driver.d.mts.map +1 -1
  71. package/esm/drivers/postgres/postgres-driver.mjs.map +1 -1
  72. package/esm/drivers/postgres/postgres-migration-driver.d.mts +1 -3
  73. package/esm/drivers/postgres/postgres-migration-driver.d.mts.map +1 -1
  74. package/esm/drivers/postgres/postgres-migration-driver.mjs +13 -10
  75. package/esm/drivers/postgres/postgres-migration-driver.mjs.map +1 -1
  76. package/esm/drivers/postgres/postgres-query-builder.d.mts +4 -4
  77. package/esm/drivers/postgres/postgres-query-builder.d.mts.map +1 -1
  78. package/esm/drivers/postgres/postgres-query-builder.mjs +14 -10
  79. package/esm/drivers/postgres/postgres-query-builder.mjs.map +1 -1
  80. package/esm/drivers/postgres/postgres-query-parser.d.mts +16 -11
  81. package/esm/drivers/postgres/postgres-query-parser.d.mts.map +1 -1
  82. package/esm/drivers/postgres/postgres-query-parser.mjs +1 -2
  83. package/esm/drivers/postgres/postgres-query-parser.mjs.map +1 -1
  84. package/esm/drivers/postgres/postgres-sql-serializer.mjs +13 -10
  85. package/esm/drivers/postgres/postgres-sql-serializer.mjs.map +1 -1
  86. package/esm/drivers/postgres/postgres-ttl-purge.mjs +1 -1
  87. package/esm/drivers/postgres/postgres-ttl-purge.mjs.map +1 -1
  88. package/esm/drivers/postgres/postgres-type-converters.mjs +2 -2
  89. package/esm/drivers/postgres/postgres-type-converters.mjs.map +1 -1
  90. package/esm/drivers/postgres/postgres-update-validator.mjs +1 -1
  91. package/esm/drivers/postgres/postgres-update-validator.mjs.map +1 -1
  92. package/esm/drivers/postgres/types.d.mts +87 -45
  93. package/esm/drivers/postgres/types.d.mts.map +1 -1
  94. package/esm/drivers/sql/sql-dialect.contract.d.mts +1 -3
  95. package/esm/drivers/sql/sql-dialect.contract.d.mts.map +1 -1
  96. package/esm/drivers/sql/sql-types.d.mts +113 -59
  97. package/esm/drivers/sql/sql-types.d.mts.map +1 -1
  98. package/esm/errors/missing-data-source.error.d.mts +1 -2
  99. package/esm/errors/missing-data-source.error.d.mts.map +1 -1
  100. package/esm/errors/transaction-rollback.error.d.mts +1 -2
  101. package/esm/errors/transaction-rollback.error.d.mts.map +1 -1
  102. package/esm/errors/undefined-where-value.error.d.mts +1 -2
  103. package/esm/errors/undefined-where-value.error.d.mts.map +1 -1
  104. package/esm/errors/unsafe-filter.error.d.mts +1 -2
  105. package/esm/errors/unsafe-filter.error.d.mts.map +1 -1
  106. package/esm/errors/unsafe-raw-expression.error.d.mts +1 -2
  107. package/esm/errors/unsafe-raw-expression.error.d.mts.map +1 -1
  108. package/esm/errors/unsupported-lean-operation.error.d.mts +1 -2
  109. package/esm/errors/unsupported-lean-operation.error.d.mts.map +1 -1
  110. package/esm/errors/unsupported-lock-for-update.error.d.mts +1 -2
  111. package/esm/errors/unsupported-lock-for-update.error.d.mts.map +1 -1
  112. package/esm/errors/unsupported-query-operation.error.d.mts +1 -2
  113. package/esm/errors/unsupported-query-operation.error.d.mts.map +1 -1
  114. package/esm/errors/unsupported-query-operation.error.mjs.map +1 -1
  115. package/esm/errors/unsupported-update-operation.error.d.mts +1 -2
  116. package/esm/errors/unsupported-update-operation.error.d.mts.map +1 -1
  117. package/esm/events/model-events.d.mts +8 -6
  118. package/esm/events/model-events.d.mts.map +1 -1
  119. package/esm/expressions/aggregate-expressions.d.mts +7 -7
  120. package/esm/expressions/aggregate-expressions.d.mts.map +1 -1
  121. package/esm/expressions/column-expressions.d.mts +11 -11
  122. package/esm/expressions/column-expressions.d.mts.map +1 -1
  123. package/esm/expressions/column-expressions.mjs.map +1 -1
  124. package/esm/index.d.mts +7 -2
  125. package/esm/index.mjs +1 -1
  126. package/esm/migration/column-builder.d.mts +2 -3
  127. package/esm/migration/column-builder.d.mts.map +1 -1
  128. package/esm/migration/column-helpers.d.mts +49 -50
  129. package/esm/migration/column-helpers.d.mts.map +1 -1
  130. package/esm/migration/column-helpers.mjs +1 -1
  131. package/esm/migration/foreign-key-builder.d.mts +2 -3
  132. package/esm/migration/foreign-key-builder.d.mts.map +1 -1
  133. package/esm/migration/foreign-key-builder.mjs.map +1 -1
  134. package/esm/migration/index.d.mts +3 -2
  135. package/esm/migration/index.mjs +2 -2
  136. package/esm/migration/migration-runner.d.mts +7 -6
  137. package/esm/migration/migration-runner.d.mts.map +1 -1
  138. package/esm/migration/migration-runner.mjs +15 -11
  139. package/esm/migration/migration-runner.mjs.map +1 -1
  140. package/esm/migration/migration.d.mts +50 -32
  141. package/esm/migration/migration.d.mts.map +1 -1
  142. package/esm/migration/migration.mjs +1 -3
  143. package/esm/migration/migration.mjs.map +1 -1
  144. package/esm/migration/parse-created-at.mjs.map +1 -1
  145. package/esm/migration/sql-grammar.mjs.map +1 -1
  146. package/esm/migration/sql-serializer.d.mts +1 -3
  147. package/esm/migration/sql-serializer.d.mts.map +1 -1
  148. package/esm/migration/types.d.mts +7 -7
  149. package/esm/migration/types.d.mts.map +1 -1
  150. package/esm/model/generate-model-id.mjs.map +1 -1
  151. package/esm/model/methods/accessor-methods.mjs +1 -1
  152. package/esm/model/methods/accessor-methods.mjs.map +1 -1
  153. package/esm/model/methods/dirty-methods.mjs.map +1 -1
  154. package/esm/model/methods/hydration-methods.mjs.map +1 -1
  155. package/esm/model/methods/meta-methods.mjs +4 -2
  156. package/esm/model/methods/meta-methods.mjs.map +1 -1
  157. package/esm/model/methods/query-methods.mjs +1 -1
  158. package/esm/model/methods/query-methods.mjs.map +1 -1
  159. package/esm/model/methods/scope-methods.mjs.map +1 -1
  160. package/esm/model/methods/static-event-methods.mjs.map +1 -1
  161. package/esm/model/methods/write-methods.d.mts +3 -2
  162. package/esm/model/methods/write-methods.d.mts.map +1 -1
  163. package/esm/model/methods/write-methods.mjs +5 -2
  164. package/esm/model/methods/write-methods.mjs.map +1 -1
  165. package/esm/model/model.d.mts +9 -9
  166. package/esm/model/model.d.mts.map +1 -1
  167. package/esm/model/model.mjs.map +1 -1
  168. package/esm/model/model.types.d.mts +7 -7
  169. package/esm/model/model.types.d.mts.map +1 -1
  170. package/esm/model/register-model.d.mts +13 -15
  171. package/esm/model/register-model.d.mts.map +1 -1
  172. package/esm/model/register-model.mjs.map +1 -1
  173. package/esm/model/relation-decorators.d.mts +6 -8
  174. package/esm/model/relation-decorators.d.mts.map +1 -1
  175. package/esm/operations/database.d.mts +13 -8
  176. package/esm/operations/database.d.mts.map +1 -1
  177. package/esm/operations/index.d.mts +2 -1
  178. package/esm/operations/index.mjs +1 -1
  179. package/esm/operations/migrations.d.mts +18 -14
  180. package/esm/operations/migrations.d.mts.map +1 -1
  181. package/esm/operations/migrations.mjs.map +1 -1
  182. package/esm/query-builder/query-builder.d.mts +2 -4
  183. package/esm/query-builder/query-builder.d.mts.map +1 -1
  184. package/esm/query-builder/query-builder.mjs +12 -11
  185. package/esm/query-builder/query-builder.mjs.map +1 -1
  186. package/esm/relations/index.d.mts +2 -1
  187. package/esm/relations/index.mjs +1 -1
  188. package/esm/relations/key-conventions.mjs +2 -1
  189. package/esm/relations/key-conventions.mjs.map +1 -1
  190. package/esm/relations/pivot-operations.d.mts +3 -5
  191. package/esm/relations/pivot-operations.d.mts.map +1 -1
  192. package/esm/relations/pivot-operations.mjs.map +1 -1
  193. package/esm/relations/relation-hydrator.d.mts +3 -5
  194. package/esm/relations/relation-hydrator.d.mts.map +1 -1
  195. package/esm/relations/relation-loader.d.mts +2 -4
  196. package/esm/relations/relation-loader.d.mts.map +1 -1
  197. package/esm/relations/relation-loader.mjs +4 -5
  198. package/esm/relations/relation-loader.mjs.map +1 -1
  199. package/esm/relations/types.d.mts +14 -15
  200. package/esm/relations/types.d.mts.map +1 -1
  201. package/esm/remover/database-remover.d.mts +1 -3
  202. package/esm/remover/database-remover.d.mts.map +1 -1
  203. package/esm/remover/database-remover.mjs.map +1 -1
  204. package/esm/restorer/database-restorer.d.mts +1 -3
  205. package/esm/restorer/database-restorer.d.mts.map +1 -1
  206. package/esm/restorer/database-restorer.mjs +2 -1
  207. package/esm/restorer/database-restorer.mjs.map +1 -1
  208. package/esm/sql-database-dirty-tracker.d.mts +1 -3
  209. package/esm/sql-database-dirty-tracker.d.mts.map +1 -1
  210. package/esm/sync/model-events.mjs +1 -1
  211. package/esm/sync/model-sync-operation.d.mts +2 -4
  212. package/esm/sync/model-sync-operation.d.mts.map +1 -1
  213. package/esm/sync/model-sync.d.mts +3 -4
  214. package/esm/sync/model-sync.d.mts.map +1 -1
  215. package/esm/sync/sync-context.d.mts +2 -4
  216. package/esm/sync/sync-context.d.mts.map +1 -1
  217. package/esm/sync/sync-context.mjs.map +1 -1
  218. package/esm/sync/sync-fanout.mjs +1 -1
  219. package/esm/sync/sync-fanout.mjs.map +1 -1
  220. package/esm/sync/sync-manager.d.mts +2 -4
  221. package/esm/sync/sync-manager.d.mts.map +1 -1
  222. package/esm/sync/sync-manager.mjs.map +1 -1
  223. package/esm/sync/types.d.mts +121 -64
  224. package/esm/sync/types.d.mts.map +1 -1
  225. package/esm/transactions/after-commit.d.mts +2 -2
  226. package/esm/transactions/after-commit.d.mts.map +1 -1
  227. package/esm/types.d.mts +7 -8
  228. package/esm/types.d.mts.map +1 -1
  229. package/esm/utils/connect-to-database.d.mts +7 -8
  230. package/esm/utils/connect-to-database.d.mts.map +1 -1
  231. package/esm/utils/database-writer.utils.d.mts +3 -4
  232. package/esm/utils/database-writer.utils.d.mts.map +1 -1
  233. package/esm/utils/database-writer.utils.mjs.map +1 -1
  234. package/esm/utils/define-model.d.mts +3 -5
  235. package/esm/utils/define-model.d.mts.map +1 -1
  236. package/esm/utils/escape-regex.d.mts +3 -4
  237. package/esm/utils/escape-regex.d.mts.map +1 -1
  238. package/esm/utils/is-valid-date-value.mjs.map +1 -1
  239. package/esm/utils/once-connected.d.mts +2 -4
  240. package/esm/utils/once-connected.d.mts.map +1 -1
  241. package/esm/utils/sanitize-filter.d.mts +3 -4
  242. package/esm/utils/sanitize-filter.d.mts.map +1 -1
  243. package/esm/validation/database-seal-plugins.d.mts +2 -1
  244. package/esm/validation/database-writer-validation-error.d.mts +1 -3
  245. package/esm/validation/database-writer-validation-error.d.mts.map +1 -1
  246. package/esm/validation/index.d.mts +3 -1
  247. package/esm/validation/index.mjs +1 -1
  248. package/esm/validation/plugins/database-rules-plugin.d.mts +2 -3
  249. package/esm/validation/plugins/database-rules-plugin.d.mts.map +1 -1
  250. package/esm/validation/plugins/embed-validator-plugin.d.mts +4 -3
  251. package/esm/validation/plugins/embed-validator-plugin.d.mts.map +1 -1
  252. package/esm/validation/types.d.mts +14 -10
  253. package/esm/validation/types.d.mts.map +1 -1
  254. package/esm/validation/validators/embed-validator.d.mts +2 -3
  255. package/esm/validation/validators/embed-validator.d.mts.map +1 -1
  256. package/esm/writer/database-writer.d.mts +1 -3
  257. package/esm/writer/database-writer.d.mts.map +1 -1
  258. package/esm/writer/database-writer.mjs +1 -1
  259. package/esm/writer/database-writer.mjs.map +1 -1
  260. package/llms-full.txt +541 -434
  261. package/package.json +5 -5
  262. package/skills/aggregate-data/SKILL.md +28 -17
  263. package/skills/alter-migration/SKILL.md +325 -233
  264. package/skills/cascade-basics/SKILL.md +19 -19
  265. package/skills/configure-delete-strategy/SKILL.md +11 -11
  266. package/skills/define-model/SKILL.md +19 -17
  267. package/skills/define-relations/SKILL.md +13 -18
  268. package/skills/index.md +3 -0
  269. package/skills/manage-transactions/SKILL.md +18 -12
  270. package/skills/paginate-results/SKILL.md +6 -8
  271. package/skills/perform-atomic-ops/SKILL.md +26 -21
  272. package/skills/query-data/SKILL.md +27 -33
  273. package/skills/run-cascade-cli/SKILL.md +11 -10
  274. package/skills/search-by-vector/SKILL.md +8 -5
  275. package/skills/subscribe-to-model-events/SKILL.md +17 -17
  276. package/skills/track-changes/SKILL.md +9 -9
  277. package/skills/write-migration/SKILL.md +4 -4
@@ -1,7 +1,6 @@
1
1
  import { Migration, MigrationContract, MigrationOrigin } from "./migration.mjs";
2
2
  import { DataSource } from "../data-source/data-source.mjs";
3
3
  import { MigrationRecord, MigrationResult } from "./types.mjs";
4
-
5
4
  //#region ../../packages/cascade/src/migration/migration-runner.d.ts
6
5
  /**
7
6
  * Migration class type with static name property.
@@ -36,7 +35,9 @@ type RegisterableMigration = (new () => MigrationContract) & {
36
35
  * Options for migration execution.
37
36
  */
38
37
  type ExecuteOptions = {
39
- /** Run in dry-run mode (no actual changes) */readonly dryRun?: boolean; /** Record to migrations table (default: true for batch, false for single) */
38
+ /** Run in dry-run mode (no actual changes) */
39
+ readonly dryRun?: boolean;
40
+ /** Record to migrations table (default: true for batch, false for single) */
40
41
  readonly record?: boolean;
41
42
  /**
42
43
  * Rollback only: delete the `_migrations` rows whose migration file is no
@@ -49,7 +50,7 @@ type ExecuteOptions = {
49
50
  * and strip a trailing `-migration` / `_migration` suffix. Shared by every CLI
50
51
  * so the same file is recorded under the same name.
51
52
  */
52
- declare function inferMigrationName(file: string): string;
53
+ export declare function inferMigrationName(file: string): string;
53
54
  /**
54
55
  * Migration runner that executes migrations.
55
56
  *
@@ -84,7 +85,7 @@ declare function inferMigrationName(file: string): string;
84
85
  * await runner.rollbackAll();
85
86
  * ```
86
87
  */
87
- declare class MigrationRunner {
88
+ export declare class MigrationRunner {
88
89
  /** Registered migrations */
89
90
  readonly migrations: MigrationClass[];
90
91
  /** Data source to use */
@@ -360,7 +361,7 @@ declare class MigrationRunner {
360
361
  */
361
362
  private getNextBatchNumber;
362
363
  }
363
- declare const migrationRunner: MigrationRunner;
364
+ export declare const migrationRunner: MigrationRunner;
364
365
  //#endregion
365
- export { MigrationRunner, inferMigrationName, migrationRunner };
366
+ export {};
366
367
  //# sourceMappingURL=migration-runner.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"migration-runner.d.mts","names":[],"sources":["../../../../../../../../packages/cascade/src/migration/migration-runner.ts"],"mappings":";;;;;;;AAgB2E;KAKtE,cAAA,cAA4B,SAAA;EAC/B,aAAA;EACA,SAAA;EACA,MAAA,GAAS,eAAe;AAAA;;;;;AAAA;AAAA;;;;;;;;;;AAsBA;KAHrB,qBAAA,cAAmC,iBAAA;EACtC,aAAA;EACA,SAAA;EACA,MAAA,GAAS,eAAe;AAAA;;;;KA0BrB,cAAA;EA8CW,uDA5CL,MAAA;WAEA,MAAA;EA0CoC;AAwC/C;;;EAxC+C,SArCpC,YAAA;AAAA;;;;;;iBAqCK,kBAAA,CAAmB,IAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAwClC,eAAA;EAWM;EAAA,SATD,UAAA,EAAY,cAAA;;UAGpB,UAAA;EAkBS;EAAA,iBAfA,gBAAA;EAiBb;EAAA,iBAda,eAAA;EA6BV;EAAA,iBA1BU,OAAA;EA0BI;;;;;cAlBnB,OAAA;IACE,UAAA,GAAa,UAAA;IACb,eAAA;IACA,OAAA;EAAA;EA+IU;;;EAhIP,aAAA,CAAc,UAAA,EAAY,UAAA;EA2O8B;;;EAAA,QAlOvD,aAAA;EAuQY;;;EAAA,QA7PZ,kBAAA;EAqSU;;;;EAAA,QAtRV,iBAAA;EAwRG;EAAA,QAjRH,QAAA;EAqSU;EAAA,QAhSV,UAAA;EAiSG;;;;;;;EAAA,QAlRH,oBAAA;EA6SmD;EAAA,QArRnD,WAAA;EAohBK;EAAA,QAjhBC,YAAA;EAkhBsB;;;;EAAA,QAxgBtB,QAAA;EA4mBY;EAAA,QA9kBZ,WAAA;EA8kBmD;;;;;;;;;;;;;;;EAne1D,QAAA,CAAS,cAAA,EAAgB,qBAAA,EAAuB,MAAA,GAAQ,eAAA;EAojBb;;;;;;EA/gB3C,YAAA,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AA;;;;UAWA,kBAAA;AAAA;AAAA,cAUH,eAAA,EAAe,eAAwB"}
1
+ {"version":3,"file":"migration-runner.d.mts","names":[],"sources":["../../../../../../../../packages/cascade/src/migration/migration-runner.ts"],"mappings":";;;;;;;KAqBK,4BAA4B;EAC/B;EACA;EACA,SAAS;;;;;;;;;;;;;;;;;;KAmBN,mCAAmC;EACtC;EACA;EACA,SAAS;;;;;KA0BN;;WAEM;;WAEA;;;;;WAKA;;;;;;;wBAqCK,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAwCtB;;WAEK,YAAY;;UAGpB;;mBAGS;;mBAGA;;mBAGA;;;;;;EAOjB,YACE;IACE,aAAa;IACb;IACA;;;;;EAeG,cAAc,YAAY;;;;UASzB;;;;UAUA;;;;;UAeA;;UAOA;;UAKA;;;;;;;;UAeA;;UAwBA;;UAGM;;;;;UAUA;;UA8BA;;;;;;;;;;;;;;;;EA2GP,SAAS,gBAAgB,uBAAuB,SAAQ;;;;;;;EAqCxD,aAAa,YAAY;;;;EAUzB;;;;EAQA;;;;;;;;;;;;;;EAqBM,IACX,gBAAgB,gBAChB,UAAS,iBACR,QAAQ;;;;;;;;;;;;;EAmBE,SACX,gBAAgB,gBAChB,UAAS,iBACR,QAAQ;;;;;;;;;;;;;;;;EA0BE,OAAO,UAAS,iBAAsB,QAAQ;UAS7C;;;;;EAsPD,UACX;IAAW;IAAuB;MACjC;;;;;;;EAmGU,aAAa,UAAS,iBAAsB,QAAQ;;;;;;;;EAWpD,gBACX,iBACA,UAAS,iBACR,QAAQ;UAMG;;;;;;;EAkDD,YAAY,UAAS,iBAAsB,QAAQ;;;;;;;EAWnD,MAAM,UAAS,iBAAsB,QAAQ;;;;EAa7C,UAAU,QACrB;IACE;IACA;IACA;IACA;;;;;;;;;;;;;UAsCU;;;;UA2CA;;;;;;;;;UA6JN;;;;;;;;;;;;;;;;;;;UA0BA;;;;;;;;;;;;;EA8CK,qBACX;IAAW;MACV,QAAQ;;;;;;;;;;;;;;;UA6BG;;;;EA6DD,sBACX,aAAY,YACZ;IAAW;MACV,QAAQ;;;;UAuBG;;;;UAuBA;;;;UAWA;;qBAUH,iBAAe"}
@@ -11,8 +11,8 @@ import path from "path";
11
11
  /** Name of the lock document Mongo migrations claim inside the migrations collection. */
12
12
  const MIGRATION_LOCK_NAME = "__warlock_migration_lock__";
13
13
  const MIGRATION_LOCK_KEY = "warlock:migrations";
14
- const MIGRATION_LOCK_TTL_MS = 600 * 1e3;
15
- const MIGRATION_LOCK_WAIT_MS = 60 * 1e3;
14
+ const MIGRATION_LOCK_TTL_MS = 6e5;
15
+ const MIGRATION_LOCK_WAIT_MS = 6e4;
16
16
  const MIGRATION_LOCK_RETRY_MS = 1e3;
17
17
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
18
18
  /**
@@ -119,7 +119,7 @@ var MigrationRunner = class {
119
119
  }
120
120
  /** Distinct data sources across the registered migrations (runner's own included). */
121
121
  getSources() {
122
- const sources = new Set([this.getDataSource()]);
122
+ const sources = /* @__PURE__ */ new Set([this.getDataSource()]);
123
123
  for (const MigrationClass of this.migrations) sources.add(this.sourceOf(MigrationClass));
124
124
  return [...sources];
125
125
  }
@@ -689,17 +689,21 @@ var MigrationRunner = class {
689
689
  };
690
690
  if (shouldUseTransaction && databaseDriver.transaction) await databaseDriver.transaction(async () => {
691
691
  await applyMigration();
692
- if (record) if (direction === "up") {
693
- const batch = options.batch ?? await this.getNextBatchNumber(dataSource);
694
- await this.recordMigration(name, batch, MigrationClass.createdAt ? parseCreatedAt(MigrationClass.createdAt) : /* @__PURE__ */ new Date(), dataSource);
695
- } else await this.removeMigrationRecord(name, dataSource);
692
+ if (record) {
693
+ if (direction === "up") {
694
+ const batch = options.batch ?? await this.getNextBatchNumber(dataSource);
695
+ await this.recordMigration(name, batch, MigrationClass.createdAt ? parseCreatedAt(MigrationClass.createdAt) : /* @__PURE__ */ new Date(), dataSource);
696
+ } else await this.removeMigrationRecord(name, dataSource);
697
+ }
696
698
  });
697
699
  else {
698
700
  await applyMigration();
699
- if (record) if (direction === "up") {
700
- const batch = options.batch ?? await this.getNextBatchNumber(dataSource);
701
- await this.recordMigration(name, batch, MigrationClass.createdAt ? parseCreatedAt(MigrationClass.createdAt) : /* @__PURE__ */ new Date(), dataSource);
702
- } else await this.removeMigrationRecord(name, dataSource);
701
+ if (record) {
702
+ if (direction === "up") {
703
+ const batch = options.batch ?? await this.getNextBatchNumber(dataSource);
704
+ await this.recordMigration(name, batch, MigrationClass.createdAt ? parseCreatedAt(MigrationClass.createdAt) : /* @__PURE__ */ new Date(), dataSource);
705
+ } else await this.removeMigrationRecord(name, dataSource);
706
+ }
703
707
  }
704
708
  }
705
709
  } catch (err) {
@@ -1 +1 @@
1
- {"version":3,"file":"migration-runner.mjs","names":[],"sources":["../../../../../../../../packages/cascade/src/migration/migration-runner.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport { log } from \"@warlock.js/logger\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport type { MigrationDriverContract } from \"../contracts/migration-driver.contract\";\nimport type { DataSource } from \"../data-source/data-source\";\nimport { dataSourceRegistry } from \"../data-source/data-source-registry\";\nimport {\n type Migration,\n type MigrationContract,\n type MigrationOrigin,\n type MigrationStep,\n} from \"./migration\";\nimport { sortMigrations, sortMigrationsForRollback } from \"./migration-order\";\nimport { parseCreatedAt } from \"./parse-created-at\";\nimport { SQLGrammar } from \"./sql-grammar\";\nimport type { MigrationRecord, MigrationResult, TaggedSQL } from \"./types\";\n\n/**\n * Migration class type with static name property.\n */\ntype MigrationClass = (new () => Migration) & {\n migrationName: string;\n createdAt?: string;\n origin?: MigrationOrigin;\n};\n\n/**\n * What a caller may hand to {@link MigrationRunner.register}.\n *\n * Looser than {@link MigrationClass} in exactly one way: `migrationName` may be\n * absent. That is the documented workflow — the CLI imports a migration file and\n * sets the name from the filename afterwards — and `register()` enforces it at\n * runtime, throwing a message that says so. Once past that check the name IS\n * present, which is why everything stored and read downstream uses the stricter\n * type. Requiring it on the INPUT made the runner reject the very classes the\n * public `MigrationConstructor` describes.\n *\n * It constructs a MigrationContract rather than the abstract Migration class for the\n * same reason: `typeof Migration` is abstract and cannot satisfy `new () => Migration`,\n * and the public MigrationConstructor is declared against the contract. The runner only\n * ever uses contract members on what it registers.\n */\ntype RegisterableMigration = (new () => MigrationContract) & {\n migrationName?: string;\n createdAt?: string;\n origin?: MigrationOrigin;\n};\n\n/**\n * Resolved instance data for a single pending migration.\n * @internal\n */\ntype MigrationData = {\n MigrationClass: MigrationClass;\n migration: Migration;\n name: string;\n /** Data source this migration runs against (its own, else the runner's). */\n dataSource: DataSource;\n /** Serialized `up()` statements (empty for direct-execution drivers). */\n statements: string[];\n /** Same as `statements`, with queued data steps kept in authored order. */\n steps: MigrationStep[];\n /** Whether the migration runs inside a transaction. */\n transactional: boolean;\n /** Driver has no SQL dialect (MongoDB): executed through `runMigration`. */\n direct: boolean;\n};\n\n/**\n * Options for migration execution.\n */\ntype ExecuteOptions = {\n /** Run in dry-run mode (no actual changes) */\n readonly dryRun?: boolean;\n /** Record to migrations table (default: true for batch, false for single) */\n readonly record?: boolean;\n /**\n * Rollback only: delete the `_migrations` rows whose migration file is no\n * longer registered, instead of failing on them.\n */\n readonly pruneMissing?: boolean;\n};\n\n/** Name of the lock document Mongo migrations claim inside the migrations collection. */\nconst MIGRATION_LOCK_NAME = \"__warlock_migration_lock__\";\nconst MIGRATION_LOCK_KEY = \"warlock:migrations\";\nconst MIGRATION_LOCK_TTL_MS = 10 * 60 * 1000;\nconst MIGRATION_LOCK_WAIT_MS = 60 * 1000;\nconst MIGRATION_LOCK_RETRY_MS = 1000;\n\n/** Held lock for one data source. `refresh` extends the TTL; `release` frees it. */\ntype MigrationLock = {\n refresh: () => Promise<void>;\n release: () => Promise<void>;\n};\n\ntype PgLockClient = {\n query: (sql: string, params?: unknown[]) => Promise<unknown>;\n release: () => void;\n};\n\n/** Minimal Mongo surface the lock needs (kept structural: no driver import). */\ntype MongoLockDatabase = {\n collection: (name: string) => {\n findOneAndUpdate: (filter: object, update: object, options: object) => Promise<unknown>;\n findOne: (filter: object) => Promise<{ owner?: string; expiresAt?: unknown } | null>;\n deleteOne: (filter: object) => Promise<unknown>;\n };\n};\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\n/**\n * Derive a migration name from a file path: drop everything after the first dot\n * and strip a trailing `-migration` / `_migration` suffix. Shared by every CLI\n * so the same file is recorded under the same name.\n */\nexport function inferMigrationName(file: string): string {\n const basename = path.basename(file).split(\".\")[0] ?? \"\";\n\n return basename.replace(/-migration$/, \"\").replace(/_migration$/, \"\");\n}\n\n/**\n * Migration runner that executes migrations.\n *\n * This is a pure executor - it doesn't discover migrations.\n * Discovery is handled by the framework (e.g., @warlock.js/core CLI).\n *\n * The migration name is read from the static `name` property on the class,\n * which should be set by the CLI after importing:\n *\n * @example\n * ```typescript\n * // In CLI after importing:\n * const { default: MigrationClass } = await import(\"./create-users.migration.ts\");\n * MigrationClass.migrationName ??= \"create-users\";\n *\n * // Then register or execute:\n * runner.register(MigrationClass);\n * // or\n * await runner.execute(MigrationClass);\n * ```\n *\n * @example\n * ```typescript\n * // Simple direct execution\n * await runner.execute(CreateUsersTable);\n * await runner.rollback(CreateUsersTable);\n *\n * // Registry pattern for batch operations\n * runner.register(CreateUsersTable);\n * runner.register(AddEmailIndex);\n * await runner.runAll();\n * await runner.rollbackAll();\n * ```\n */\nexport class MigrationRunner {\n /** Registered migrations */\n public readonly migrations: MigrationClass[] = [];\n\n /** Data source to use */\n private dataSource?: DataSource;\n\n /** Cached migration drivers, one per data source */\n private readonly migrationDrivers = new Map<DataSource, MigrationDriverContract>();\n\n /** Table name for tracking migrations */\n private readonly migrationsTable: string;\n\n /** Whether to log operations */\n private readonly verbose: boolean;\n\n /**\n * Create a new migration runner.\n *\n * @param options - Runner options\n */\n public constructor(\n options: {\n dataSource?: DataSource;\n migrationsTable?: string;\n verbose?: boolean;\n } = {},\n ) {\n this.dataSource = options.dataSource;\n this.migrationsTable = options.migrationsTable ?? \"_migrations\";\n this.verbose = options.verbose ?? true;\n }\n\n // ============================================================================\n // DATA SOURCE\n // ============================================================================\n\n /**\n * Set the data source.\n */\n public setDataSource(dataSource: DataSource): this {\n this.dataSource = dataSource;\n this.migrationDrivers.clear();\n return this;\n }\n\n /**\n * Get the data source.\n */\n private getDataSource(): DataSource {\n if (!this.dataSource) {\n this.dataSource = dataSourceRegistry.get();\n }\n return this.dataSource;\n }\n\n /**\n * Get the migration driver.\n */\n private getMigrationDriver(\n dataSource: DataSource = this.getDataSource(),\n ): MigrationDriverContract {\n let driver = this.migrationDrivers.get(dataSource);\n if (!driver) {\n driver = dataSource.driver.migrationDriver();\n this.migrationDrivers.set(dataSource, driver);\n }\n return driver;\n }\n\n /**\n * Resolve a migration's declared data source (name or instance).\n * Falls back to the runner's own data source when it declares none.\n */\n private resolveDataSource(declared?: string | DataSource): DataSource {\n if (!declared) return this.getDataSource();\n if (typeof declared === \"string\") return dataSourceRegistry.get(declared);\n return declared;\n }\n\n /** Data source a registered migration class runs against. */\n private sourceOf(MigrationClass: MigrationClass): DataSource {\n return this.resolveDataSource(new MigrationClass().dataSource);\n }\n\n /** Distinct data sources across the registered migrations (runner's own included). */\n private getSources(): DataSource[] {\n const sources = new Set<DataSource>([this.getDataSource()]);\n for (const MigrationClass of this.migrations) {\n sources.add(this.sourceOf(MigrationClass));\n }\n return [...sources];\n }\n\n /**\n * Resolve whether a migration runs in a transaction:\n * 1. migration-level flag (instance, else the static from `Migration.create/alter`)\n * 2. `CONCURRENTLY` statements cannot run in a transaction block\n * 3. data-source config\n * 4. driver default\n */\n private resolveTransactional(\n MigrationClass: MigrationClass,\n migration: Migration,\n dataSource: DataSource,\n statements: string[] = [],\n ): boolean {\n const explicit =\n migration.transactional ?? (MigrationClass as { transactional?: boolean }).transactional;\n\n if (explicit !== undefined) return explicit;\n\n if (statements.some((sql) => /\\bCONCURRENTLY\\b/i.test(sql))) return false;\n\n return (\n dataSource.migrations?.transactional ??\n this.getMigrationDriver(dataSource).getDefaultTransactional()\n );\n }\n\n // ============================================================================\n // LOCKING\n // ============================================================================\n\n /** Locks held by the run in progress (Mongo TTL heartbeat). */\n private activeLocks: MigrationLock[] = [];\n\n /** Extend every held lock's TTL; called between migrations. */\n private async refreshLocks(): Promise<void> {\n for (const lock of this.activeLocks) {\n await lock.refresh();\n }\n }\n\n /**\n * Run `callback` while holding a migration lock on every given data source, so\n * concurrent `migrate` invocations (replicas, init containers) serialize.\n */\n private async withLock<T>(sources: DataSource[], callback: () => Promise<T>): Promise<T> {\n const held: MigrationLock[] = [];\n\n try {\n for (const dataSource of sources) {\n const lock = await this.acquireLock(dataSource);\n if (lock) held.push(lock);\n }\n\n this.activeLocks = held;\n\n return await callback();\n } finally {\n this.activeLocks = [];\n\n for (const lock of held.reverse()) {\n try {\n await lock.release();\n } catch (error) {\n log.warn(\n \"database\",\n \"migration\",\n `Failed to release migration lock: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n }\n }\n\n /** Acquire the lock for one data source; `undefined` when its driver has no lock support. */\n private async acquireLock(dataSource: DataSource): Promise<MigrationLock | undefined> {\n const driver = dataSource.driver as unknown as {\n name: string;\n getClient?: () => { connect?: () => Promise<PgLockClient> };\n getDatabase?: () => MongoLockDatabase;\n };\n\n if (driver.name === \"postgres\" && driver.getClient) {\n // A dedicated client: advisory locks are per-session, not per-pool.\n const client = await driver.getClient().connect?.();\n if (!client) return undefined;\n\n try {\n await client.query(\"SELECT pg_advisory_lock(hashtext($1))\", [MIGRATION_LOCK_KEY]);\n } catch (error) {\n client.release();\n throw error;\n }\n\n return {\n refresh: async () => {},\n release: async () => {\n try {\n await client.query(\"SELECT pg_advisory_unlock(hashtext($1))\", [MIGRATION_LOCK_KEY]);\n } finally {\n client.release();\n }\n },\n };\n }\n\n if (driver.getDatabase) {\n // The unique index on `name` (created here) makes the claim below atomic.\n await this.getMigrationDriver(dataSource).ensureMigrationsTable(this.migrationsTable);\n\n const collection = driver.getDatabase().collection(this.migrationsTable);\n const owner = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n const deadline = Date.now() + MIGRATION_LOCK_WAIT_MS;\n\n const claim = async (): Promise<boolean> => {\n const now = new Date();\n\n try {\n await collection.findOneAndUpdate(\n {\n name: MIGRATION_LOCK_NAME,\n $or: [{ expiresAt: { $lt: now } }, { owner }],\n },\n {\n $set: { owner, expiresAt: new Date(now.getTime() + MIGRATION_LOCK_TTL_MS) },\n $setOnInsert: { batch: 0 },\n },\n { upsert: true },\n );\n\n return true;\n } catch (error) {\n // Held by someone else: the upsert collides with the unique `name` index.\n if ((error as { code?: number }).code === 11000) return false;\n throw error;\n }\n };\n\n while (!(await claim())) {\n if (Date.now() >= deadline) {\n const holder = await collection.findOne({ name: MIGRATION_LOCK_NAME });\n throw new Error(\n `Could not acquire the migration lock within ${MIGRATION_LOCK_WAIT_MS / 1000}s; ` +\n `held by \"${holder?.owner ?? \"unknown\"}\" until ${holder?.expiresAt ?? \"unknown\"}.`,\n );\n }\n\n await sleep(MIGRATION_LOCK_RETRY_MS);\n }\n\n return {\n refresh: async () => {\n await claim();\n },\n release: async () => {\n await collection.deleteOne({ name: MIGRATION_LOCK_NAME, owner });\n },\n };\n }\n\n return undefined;\n }\n\n // ============================================================================\n // REGISTRATION\n // ============================================================================\n\n /**\n * Register a migration.\n *\n * The migration name is read from `MigrationClass.migrationName`.\n *\n * @param MigrationClass - Migration class (must have static `name` set)\n * @param origin - Registration source; defaults to `\"app\"` for direct registrations.\n * @returns This runner for chaining\n *\n * @example\n * ```typescript\n * CreateUsersTable.migrationName = \"2024-01-15_create-users\";\n * runner.register(CreateUsersTable);\n * ```\n */\n public register(MigrationClass: RegisterableMigration, origin: MigrationOrigin = \"app\"): this {\n const name = MigrationClass.migrationName;\n if (!name) {\n throw new Error(\n `Migration class must have a static 'migrationName' property set. ` +\n `Set it in CLI after importing: MigrationClass.migrationName = \"filename\";`,\n );\n }\n const existing = this.migrations.find((m) => m.migrationName === name);\n\n if (existing) {\n // Re-registering the same class is idempotent; a DIFFERENT class under the\n // same name would silently never run, so fail loudly.\n if ((existing as unknown) !== MigrationClass) {\n throw new Error(\n `Duplicate migration name \"${name}\": two different migration classes resolve to the same name. ` +\n `Rename one of the files (or set a unique static 'migrationName').`,\n );\n }\n\n return this;\n }\n\n // `name` is proven present by the throw above, so this satisfies the stricter\n // stored type that every reader downstream relies on.\n MigrationClass.origin = origin;\n this.migrations.push(MigrationClass as MigrationClass);\n\n return this;\n }\n\n /**\n * Register multiple migrations.\n *\n * @param migrations - Array of migration classes\n * @returns This runner for chaining\n */\n public registerMany(migrations: RegisterableMigration[]): this {\n for (const MigrationClass of migrations) {\n this.register(MigrationClass);\n }\n return this;\n }\n\n /**\n * Clear all registered migrations.\n */\n public clear(): this {\n this.migrations.length = 0;\n return this;\n }\n\n /**\n * Get all registered migration names.\n */\n public getRegisteredNames(): string[] {\n return this.migrations.map((m) => m.migrationName);\n }\n\n // ============================================================================\n // SINGLE EXECUTION\n // ============================================================================\n\n /**\n * Execute a single migration's up() method.\n *\n * @param MigrationClass - Migration class to execute\n * @param options - Execution options\n * @returns Migration result\n *\n * @example\n * ```typescript\n * await runner.execute(CreateUsersTable);\n * await runner.execute(AddEmailIndex, { dryRun: true });\n * ```\n */\n public async run(\n MigrationClass: MigrationClass,\n options: ExecuteOptions = {},\n ): Promise<MigrationResult> {\n return this.runMigration(MigrationClass, \"up\", {\n dryRun: options.dryRun,\n record: options.record ?? false,\n });\n }\n\n /**\n * Execute a single migration's down() method.\n *\n * @param MigrationClass - Migration class to rollback\n * @param options - Execution options\n * @returns Migration result\n *\n * @example\n * ```typescript\n * await runner.rollback(CreateUsersTable);\n * ```\n */\n public async rollback(\n MigrationClass: MigrationClass,\n options: ExecuteOptions = {},\n ): Promise<MigrationResult> {\n return this.runMigration(MigrationClass, \"down\", {\n dryRun: options.dryRun,\n record: options.record ?? false,\n });\n }\n\n // ============================================================================\n // BATCH EXECUTION (REGISTERED MIGRATIONS)\n // ============================================================================\n\n /**\n * Run all pending registered migrations.\n *\n * Only runs migrations not already in the migrations table.\n *\n * @param options - Execution options\n * @returns Results for each migration\n *\n * @example\n * ```typescript\n * runner.register(CreateUsersTable);\n * runner.register(AddEmailIndex);\n * const results = await runner.runAll();\n * ```\n */\n public async runAll(options: ExecuteOptions = {}): Promise<MigrationResult[]> {\n // A dry run writes nothing, so it needs no lock.\n if (options.dryRun) return this.runAllUnlocked(options);\n\n // The pending set is computed INSIDE the lock, so a replica that waited sees\n // what the winner already applied.\n return this.withLock(this.getSources(), () => this.runAllUnlocked(options));\n }\n\n private async runAllUnlocked(options: ExecuteOptions): Promise<MigrationResult[]> {\n const { dryRun = false, record = true } = options;\n\n const results: MigrationResult[] = [];\n\n // Get pending migrations (a dry run must not create the migrations table)\n const pending = await this.getPendingMigrations({ readOnly: dryRun });\n\n if (pending.length === 0) {\n log.warn(\"database\", \"migration\", \"Nothing to migrate.\");\n return results;\n }\n\n // Next batch number per data source: each source has its own migrations table.\n const sources = new Set<DataSource>();\n const migrationsData: MigrationData[] = [];\n\n log.info(\"database\", \"migration\", `Found ${pending.length} pending migration(s).`);\n\n // 1. Resolve each migration's data source and transactional mode, and collect\n // its SQL. Drivers without SQL serialization (MongoDB) are executed\n // directly through the migration driver instead.\n // Extension checks fire concurrently as CREATE EXTENSION statements are met.\n const extensionChecks: Promise<void>[] = [];\n\n for (const MigrationClass of pending) {\n const migration = this.createMigrationInstance(MigrationClass);\n const name = MigrationClass.migrationName;\n const dataSource = this.resolveDataSource(migration.dataSource);\n sources.add(dataSource);\n\n if (dataSource.driver.supportsSqlSerialization === false) {\n migrationsData.push({\n MigrationClass,\n migration,\n name,\n dataSource,\n statements: [],\n steps: [],\n transactional: false,\n direct: true,\n });\n continue;\n }\n\n migration.setDriver(this.getMigrationDriver(dataSource));\n migration.setMigrationDefaults(dataSource.migrationDefaults);\n // Collection must not run `withConnection` side effects during a dry run.\n migration.setDryRun?.(dryRun);\n\n await migration.up();\n const steps: MigrationStep[] = migration.toSteps?.() ?? migration.toSQL();\n const statements = steps.map((step) =>\n typeof step === \"string\" ? step : \"-- data step (withConnection) skipped\",\n );\n migration.setDryRun?.(false);\n\n migrationsData.push({\n MigrationClass,\n migration,\n name,\n dataSource,\n statements,\n steps,\n transactional:\n !!dataSource.driver.transaction &&\n this.resolveTransactional(MigrationClass, migration, dataSource, statements),\n direct: false,\n });\n\n for (const sql of statements) {\n if (SQLGrammar.classify(sql) === \"CREATE_EXTENSION\") {\n const ext = SQLGrammar.extractExtensionName(sql);\n if (ext) extensionChecks.push(this.informIfExtensionMissing(ext, dataSource));\n }\n }\n }\n\n // 2. Resolve all extension checks before any SQL is executed.\n await Promise.all(extensionChecks);\n\n // 3. Dry run: print statements in migration order (authored order kept; no\n // global phase sort, which would reorder add-column → backfill → NOT NULL).\n if (dryRun) {\n log.info(\"database\", \"migration\", \"Dry run enabled. Would execute the following statements:\");\n for (const data of migrationsData) {\n for (const sql of data.statements) {\n console.log(\n `-- [${SQLGrammar.classify(sql)}] Phase ${SQLGrammar.phase(sql)} [${data.name}]`,\n );\n console.log(sql + \";\\n\");\n }\n }\n return [];\n }\n\n const batches = new Map<DataSource, number>();\n for (const dataSource of sources) {\n batches.set(dataSource, await this.getNextBatchNumber(dataSource));\n }\n\n // 4. Split into runs: consecutive transactional migrations on the same data\n // source share one transaction; every other migration (non-transactional\n // or direct) runs alone.\n const runs: MigrationData[][] = [];\n for (const data of migrationsData) {\n const last = runs[runs.length - 1];\n const lastFirst = last?.[0];\n if (\n data.transactional &&\n last &&\n lastFirst?.transactional &&\n lastFirst.dataSource === data.dataSource\n ) {\n last.push(data);\n } else {\n runs.push([data]);\n }\n }\n\n for (const run of runs) {\n const first = run[0];\n if (!first) continue;\n await this.refreshLocks();\n const dataSource = first.dataSource;\n const nextBatch = batches.get(dataSource)!;\n const startTime = Date.now();\n\n if (first.direct) {\n const result = await this.runMigration(first.MigrationClass, \"up\", {\n dryRun,\n record,\n batch: nextBatch,\n });\n results.push(result);\n if (!result.success) break;\n continue;\n }\n\n const driver = dataSource.driver;\n let failed = false;\n let errorMessage = \"\";\n /** The migration that owns the SQL statement that threw. */\n let failingMigrationName: string | undefined;\n\n const executeRun = async (): Promise<void> => {\n for (const data of run) {\n for (const step of data.steps) {\n try {\n if (typeof step === \"string\") await driver.query(step);\n else await step.data();\n } catch (err) {\n failingMigrationName = data.name;\n throw err;\n }\n }\n\n // A non-transactional migration is recorded right after it applied.\n // Transactional ones are recorded inside the shared transaction.\n if (record) {\n await this.recordMigration(\n data.name,\n nextBatch,\n data.MigrationClass.createdAt\n ? parseCreatedAt(data.MigrationClass.createdAt)\n : new Date(),\n dataSource,\n );\n }\n }\n };\n\n try {\n if (first.transactional && driver.transaction) {\n await driver.transaction(executeRun);\n } else {\n await executeRun();\n }\n } catch (err) {\n failed = true;\n errorMessage = err instanceof Error ? err.message : String(err);\n }\n\n const durationMs = Date.now() - startTime;\n\n // Only the migration that owns the failing statement is marked failed;\n // the rest of its run is reported as rolled back.\n for (const data of run) {\n const isCulprit = failed && data.name === failingMigrationName;\n const wasSkipped = failed && !isCulprit;\n\n results.push({\n name: data.name,\n table: data.migration.table,\n direction: \"up\",\n success: !failed,\n error: isCulprit ? errorMessage : undefined,\n durationMs: Math.round(durationMs / run.length),\n executedAt: new Date(),\n });\n\n if (isCulprit) {\n log.error(\n \"database\",\n \"migration\",\n `${colors.magenta(data.name)}: ✗ Failed: ${errorMessage}`,\n );\n } else if (wasSkipped) {\n log.warn(\n \"database\",\n \"migration\",\n `${colors.magenta(data.name)}: rolled back (batch transaction failed)`,\n );\n } else {\n log.success(\n \"database\",\n \"migration\",\n `Migrated: ${colors.magenta(data.name)} successfully`,\n );\n }\n }\n\n if (failed) {\n log.error(\n \"database\",\n \"migration\",\n `Batch execution failed. Rollback performed if transactional.`,\n );\n throw new Error(\"Migration batch failed: \" + errorMessage);\n }\n }\n\n const successCount = results.filter((r) => r.success).length;\n log.success(\n \"database\",\n \"migration\",\n `Migration execution complete: ${successCount}/${pending.length} migrations processed successfully.`,\n );\n\n return results;\n }\n\n /**\n * Export migrations as phase-ordered SQL files in database/sql/ directory.\n * By default, it exports all registered migrations. Use `pendingOnly: true` to export only pending ones.\n */\n public async exportSQL(\n options: { pendingOnly?: boolean; compact?: boolean } = {},\n ): Promise<void> {\n if (this.getDataSource().driver.supportsSqlSerialization === false) {\n throw new Error(\n \"SQL export is not supported on this data source — its driver has no SQL dialect. \" +\n \"Migrations on this driver execute native commands through the migration driver instead.\",\n );\n }\n\n const migrationsToExport = options.pendingOnly\n ? await this.getPendingMigrations({ readOnly: true })\n : this.migrations;\n\n if (migrationsToExport.length === 0) {\n log.warn(\"database\", \"migration\", \"No migrations to export.\");\n return;\n }\n\n log.info(\n \"database\",\n \"migration\",\n `Exporting ${migrationsToExport.length} ${options.pendingOnly ? \"pending \" : \"\"}migration(s) to SQL files...`,\n );\n\n const upStatements: TaggedSQL[] = [];\n // Down SQL is grouped per migration so only the migration order is reversed,\n // never the statements inside one migration's down().\n const downGroups: { createdAt?: string; index: number; statements: TaggedSQL[] }[] = [];\n\n for (const [index, MigrationClass] of migrationsToExport.entries()) {\n const migration = this.createMigrationInstance(MigrationClass);\n const name = MigrationClass.migrationName;\n\n // Export performs no writes: `withConnection` callbacks are skipped.\n migration.setDryRun?.(true);\n\n // Collect up SQL\n await migration.up();\n for (const sql of migration.toSQL()) {\n upStatements.push({\n sql,\n phase: SQLGrammar.phase(sql),\n statementType: SQLGrammar.classify(sql),\n createdAt: MigrationClass.createdAt,\n migrationName: name,\n });\n }\n\n // Collect down SQL (reuse same instance — toSQL() cleared pendingOps)\n await migration.down();\n const statements: TaggedSQL[] = [];\n for (const sql of migration.toSQL()) {\n statements.push({\n sql,\n phase: SQLGrammar.phase(sql),\n statementType: SQLGrammar.classify(sql),\n createdAt: MigrationClass.createdAt,\n migrationName: name,\n });\n }\n downGroups.push({ createdAt: MigrationClass.createdAt, index, statements });\n }\n\n const sortedUp = SQLGrammar.sort(upStatements);\n // Down SQL: newest migration first (chronological, registration order breaks\n // ties), each migration's own down() statements keep their order.\n const sortedDown = downGroups\n .sort((a, b) => {\n const byDate = (a.createdAt ?? \"\").localeCompare(b.createdAt ?? \"\");\n return byDate !== 0 ? byDate : a.index - b.index;\n })\n .reverse()\n .flatMap((group) => group.statements);\n\n const upSQLString = this.formatSQLForExport(sortedUp, options.compact);\n const downSQLString = this.formatSQLForExport(sortedDown, options.compact);\n\n const rootPath = process.cwd();\n const sqlDir = path.join(rootPath, \"database\", \"sql\");\n\n if (!fs.existsSync(sqlDir)) {\n fs.mkdirSync(sqlDir, { recursive: true });\n }\n\n const timestamp = new Date().toISOString().replace(/T/, \"_\").replace(/:/g, \"-\").split(\".\")[0];\n const upPath = path.join(sqlDir, `migration_${timestamp}.up.sql`);\n const downPath = path.join(sqlDir, `migration_${timestamp}.down.sql`);\n\n fs.writeFileSync(upPath, upSQLString);\n fs.writeFileSync(downPath, downSQLString);\n\n log.success(\"database\", \"migration\", `Exported to:\\n- ${upPath}\\n- ${downPath}`);\n }\n\n /**\n * Rollback the last batch of migrations.\n *\n * @param options - Execution options\n * @returns Results for each migration\n */\n public async rollbackLast(options: ExecuteOptions = {}): Promise<MigrationResult[]> {\n return this.rollbackBatches(1, options);\n }\n\n /**\n * Rollback N batches of migrations.\n *\n * @param batches - Number of batches to rollback\n * @param options - Execution options\n * @returns Results for each migration\n */\n public async rollbackBatches(\n batches: number,\n options: ExecuteOptions = {},\n ): Promise<MigrationResult[]> {\n if (options.dryRun) return this.rollbackBatchesUnlocked(batches, options);\n\n return this.withLock(this.getSources(), () => this.rollbackBatchesUnlocked(batches, options));\n }\n\n private async rollbackBatchesUnlocked(\n batches: number,\n options: ExecuteOptions,\n ): Promise<MigrationResult[]> {\n const dryRun = options.dryRun ?? false;\n const record = options.record ?? true;\n const results: MigrationResult[] = [];\n\n const toRollback = await this.getMigrationsToRollback(batches, {\n pruneMissing: options.pruneMissing,\n readOnly: dryRun,\n });\n\n if (toRollback.length === 0) {\n log.warn(\"database\", \"migration\", \"Nothing to rollback.\");\n return results;\n }\n\n log.info(\"database\", \"migration\", `Rolling back ${toRollback.length} migration(s).`);\n\n for (const MigrationClass of toRollback) {\n await this.refreshLocks();\n\n const result = await this.runMigration(MigrationClass, \"down\", {\n dryRun,\n record,\n });\n results.push(result);\n\n if (!result.success) {\n break;\n }\n }\n\n const successCount = results.filter((r) => r.success).length;\n log.success(\n \"database\",\n \"migration\",\n `Rollback complete: ${successCount}/${toRollback.length} successful.`,\n );\n\n return results;\n }\n\n /**\n * Rollback all executed migrations.\n *\n * @param options - Execution options\n * @returns Results for each migration\n */\n public async rollbackAll(options: ExecuteOptions = {}): Promise<MigrationResult[]> {\n // Batch numbers are per data source; rolling back \"all\" is every batch of each.\n return this.rollbackBatches(Number.POSITIVE_INFINITY, options);\n }\n\n /**\n * Reset and re-run: rollback all then run all.\n *\n * @param options - Execution options\n * @returns Combined results\n */\n public async fresh(options: ExecuteOptions = {}): Promise<MigrationResult[]> {\n const rollbackResults = await this.rollbackAll(options);\n const runResults = await this.runAll(options);\n return [...rollbackResults, ...runResults];\n }\n\n // ============================================================================\n // STATUS\n // ============================================================================\n\n /**\n * Get status of all registered migrations.\n */\n public async status(): Promise<\n Array<{\n name: string;\n table: string;\n executed: boolean;\n batch: number | null;\n }>\n > {\n const executedBySource = new Map<DataSource, Map<string, MigrationRecord>>();\n\n for (const dataSource of this.getSources()) {\n const executed = await this.getExecutedMigrations(dataSource, { readOnly: true });\n executedBySource.set(dataSource, new Map(executed.map((r) => [r.name, r])));\n }\n\n return this.migrations.map((MigrationClass) => {\n const instance = new MigrationClass();\n const name = MigrationClass.migrationName;\n const record = executedBySource.get(this.sourceOf(MigrationClass))?.get(name);\n return {\n name,\n table: instance.table,\n executed: !!record,\n batch: record?.batch ?? null,\n };\n });\n }\n\n // ============================================================================\n // EXTENSION PRE-FLIGHT\n // ============================================================================\n\n /**\n * Check whether a database extension is available and inform the developer\n * if it is not installed.\n *\n * Does NOT throw — execution proceeds normally. If the extension is truly\n * missing, the database will surface its own error with full context already\n * displayed to the developer.\n *\n * @example\n * await this.informIfExtensionMissing(\"vector\");\n */\n private async informIfExtensionMissing(\n extension: string,\n dataSource: DataSource = this.getDataSource(),\n ): Promise<void> {\n try {\n const migrationDriver = this.getMigrationDriver(dataSource);\n const isAvailable = await migrationDriver.isExtensionAvailable(extension);\n\n if (!isAvailable) {\n const hr = \"─\".repeat(60);\n console.log(`\\n${colors.yellow(hr)}`);\n console.log(colors.yellow(` ⚠ Missing Database Extension: ${colors.bold(extension)}`));\n console.log(colors.yellow(hr));\n console.log();\n console.log(` A pending migration requires the ${colors.cyan(extension)} extension,`);\n console.log(` which is not installed on your database server.`);\n console.log();\n console.log(\n ` ${colors.bold(\"This means the physical database server is missing the extension package.\")}`,\n );\n console.log(` You cannot simply run CREATE EXTENSION until the package is installed`);\n console.log(` on the host machine or Docker container.`);\n console.log();\n\n const docsUrl = migrationDriver.getExtensionDocsUrl(extension);\n if (docsUrl) {\n console.log(` ${colors.bold(\"Or follow the installation guide:\")}`);\n console.log(` ${colors.cyan(docsUrl)}`);\n }\n console.log(`\\n${colors.yellow(hr)}\\n`);\n }\n } catch {\n // If the check itself fails, silently skip — don't break the migration.\n }\n }\n\n // ============================================================================\n // PRIVATE HELPERS\n // ============================================================================\n\n /**\n * Run a single migration.\n */\n private async runMigration(\n MigrationClass: MigrationClass,\n direction: \"up\" | \"down\",\n options: {\n dryRun?: boolean;\n record?: boolean;\n batch?: number;\n } = {},\n ): Promise<MigrationResult> {\n const { dryRun = false, record = true } = options;\n const startTime = Date.now();\n let success = true;\n let error: string | undefined;\n\n const migration = new MigrationClass();\n const name = MigrationClass.migrationName;\n\n log.info(\n \"database\",\n \"migration\",\n `${direction === \"up\" ? \"Migrating\" : \"Rolling back\"}: ${colors.magenta(name)}...`,\n );\n\n try {\n if (!dryRun) {\n // The migration runs against its declared data source (default: the runner's)\n // and is recorded in THAT source's migrations table.\n const dataSource = this.resolveDataSource(migration.dataSource);\n const driver = this.getMigrationDriver(dataSource);\n migration.setDriver(driver);\n migration.setMigrationDefaults(dataSource.migrationDefaults);\n\n // ============================================================================\n // TRANSACTION RESOLUTION (3-tier hierarchy)\n // ============================================================================\n // 1. Migration-level explicit override (instance or static)\n // 2. CONCURRENTLY statements (cannot run in a transaction block)\n // 3. Config-level global override\n // 4. Driver default (PostgreSQL: true, MongoDB: false)\n // Resolved below, once the statements are known.\n\n // ============================================================================\n // EXECUTE WITH OR WITHOUT TRANSACTION\n // ============================================================================\n\n // Collect the requested direction's operations\n if (direction === \"up\") {\n await migration.up();\n } else {\n await migration.down();\n }\n\n const databaseDriver = dataSource.driver;\n\n // SQL-capable drivers serialize the queued operations to SQL strings;\n // drivers without SQL serialization (MongoDB) keep them queued and\n // execute them directly through the migration driver.\n const directExecution = databaseDriver.supportsSqlSerialization === false;\n const steps: MigrationStep[] = directExecution\n ? []\n : (migration.toSteps?.() ?? migration.toSQL());\n const sqlStatements = steps.filter((step): step is string => typeof step === \"string\");\n const shouldUseTransaction = this.resolveTransactional(\n MigrationClass,\n migration,\n dataSource,\n sqlStatements,\n );\n\n const applyMigration = async (): Promise<void> => {\n if (directExecution) {\n await migration.execute();\n return;\n }\n\n // Execute generated SQL statements sequentially (no phase-sorting here since it's single execution)\n for (const step of steps) {\n if (typeof step === \"string\") await databaseDriver.query(step);\n else await step.data();\n }\n };\n\n if (shouldUseTransaction && databaseDriver.transaction) {\n // Transactional execution\n await databaseDriver.transaction(async () => {\n await applyMigration();\n\n // Record migration tracking\n if (record) {\n if (direction === \"up\") {\n const batch = options.batch ?? (await this.getNextBatchNumber(dataSource));\n await this.recordMigration(\n name,\n batch,\n MigrationClass.createdAt ? parseCreatedAt(MigrationClass.createdAt) : new Date(),\n dataSource,\n );\n } else {\n await this.removeMigrationRecord(name, dataSource);\n }\n }\n });\n } else {\n // Non-transactional execution\n await applyMigration();\n\n if (record) {\n if (direction === \"up\") {\n const batch = options.batch ?? (await this.getNextBatchNumber(dataSource));\n await this.recordMigration(\n name,\n batch,\n MigrationClass.createdAt ? parseCreatedAt(MigrationClass.createdAt) : new Date(),\n dataSource,\n );\n } else {\n await this.removeMigrationRecord(name, dataSource);\n }\n }\n }\n }\n } catch (err) {\n success = false;\n error = err instanceof Error ? err.message : String(err);\n log.error(\"database\", \"migration\", `${colors.magenta(name)}: ✗ Failed: ${error}`);\n throw err;\n }\n\n const durationMs = Date.now() - startTime;\n\n if (success) {\n log.success(\n \"database\",\n \"migration\",\n `${direction == \"up\" ? \"Migrated\" : \"Rolled back\"}: ${colors.magenta(name)} successfully (${durationMs}ms)`,\n );\n }\n\n return {\n name,\n table: migration.table,\n direction,\n success,\n error,\n durationMs,\n executedAt: new Date(),\n };\n }\n\n /**\n * Create, configure, and return a ready-to-use migration instance.\n *\n * Centralises the repeated \"new + setDriver + setMigrationDefaults\" boilerplate\n * that all batch/single execution paths need.\n *\n * @internal\n */\n private createMigrationInstance(MigrationClass: MigrationClass): Migration {\n const migration = new MigrationClass();\n const dataSource = this.resolveDataSource(migration.dataSource);\n migration.setDriver(this.getMigrationDriver(dataSource));\n migration.setMigrationDefaults(dataSource.migrationDefaults);\n return migration;\n }\n\n /**\n * Format an ordered array of TaggedSQL into a human-readable SQL file string.\n *\n * Consecutive statements that belong to the same (phase, migration) group share\n * a single block comment at the top, avoiding the noisy per-statement repetition.\n *\n * Example output:\n * ```sql\n * /* Phase 3 [create-users] *\\/\n * ALTER TABLE \"users\" ADD COLUMN \"name\" TEXT NOT NULL;\n * ALTER TABLE \"users\" ADD COLUMN \"email\" TEXT NOT NULL;\n *\n * /* Phase 4 [create-users] *\\/\n * CREATE UNIQUE INDEX ...;\n * ```\n *\n * @internal\n */\n private formatSQLForExport(statements: TaggedSQL[], compact: boolean = false): string {\n const lines: string[] = [];\n\n if (compact) {\n // Just output raw statements, no grouping, no blank lines\n for (const stmt of statements) {\n lines.push(`${stmt.sql};`);\n }\n return lines.join(\"\\n\");\n }\n\n // Group statements by their phase and migration name\n const grouped = new Map<string, string[]>();\n\n for (const stmt of statements) {\n const groupKey = `Phase ${stmt.phase} [${stmt.migrationName}]`;\n if (!grouped.has(groupKey)) {\n grouped.set(groupKey, []);\n }\n grouped.get(groupKey)!.push(stmt.sql);\n }\n\n // Format each group\n for (const [groupKey, sqls] of grouped.entries()) {\n if (lines.length > 0) lines.push(\"\"); // blank line between groups\n lines.push(`/* ${groupKey} */`);\n for (const sql of sqls) {\n lines.push(`${sql};`);\n }\n }\n\n return lines.join(\"\\n\");\n }\n\n /**\n * Get pending (not executed) registered migrations, in the order they would\n * execute.\n *\n * ⚠️ \"Registered\" is load-bearing. This filters `this.migrations`, which is\n * populated only by `register()` / `registerMany()`. A caller that has not\n * registered anything gets `[]` — indistinguishable from a database with\n * nothing pending. Anything reporting this set to a human MUST register\n * migrations first, or it will print a confident all-clear over an unknown.\n *\n * @see listPendingMigrations\n */\n public async getPendingMigrations(\n options: { readOnly?: boolean } = {},\n ): Promise<MigrationClass[]> {\n // \"Executed\" is judged in each migration's own data source's migrations table.\n const executedNames = new Map<DataSource, Set<string>>();\n for (const dataSource of this.getSources()) {\n const executed = await this.getExecutedMigrations(dataSource, options);\n executedNames.set(dataSource, new Set(executed.map((r) => r.name)));\n }\n\n const migrations = this.migrations.filter(\n (m) => !executedNames.get(this.sourceOf(m))?.has(m.migrationName),\n );\n\n return migrations.sort(sortMigrations);\n }\n\n /**\n * Get migrations to rollback, newest-first.\n *\n * A rollback must undo migrations in the exact inverse of the order `up`\n * applied them, or a `down()` will hit schema its predecessor already\n * removed — dropping a table before dropping the column added to it, say.\n *\n * The sort has to be explicitly **descending**. Reversing the executed list\n * is not enough: `getExecutedMigrations` orders by `batch, name`, so the\n * input is alphabetical rather than chronological, and reversing it only\n * yields reverse-alphabetical order. (Sorting *ascending* here — which is\n * what this method used to do after a `.reverse()` — silently restored the\n * forward `up` order and made the reverse dead code.)\n */\n private async getMigrationsToRollback(\n batches: number,\n options: { pruneMissing?: boolean; readOnly?: boolean } = {},\n ): Promise<MigrationClass[]> {\n const migrations: MigrationClass[] = [];\n const batchOf = new Map<MigrationClass, number>();\n const orphans: Array<{ name: string; dataSource: DataSource }> = [];\n\n // Batches are numbered per data source (each has its own migrations table).\n for (const dataSource of this.getSources()) {\n const executed = await this.getExecutedMigrations(dataSource, {\n readOnly: options.readOnly,\n });\n if (executed.length === 0) continue;\n\n const batchNumbers = [...new Set(executed.map((r) => r.batch))]\n .sort((a, b) => b - a)\n .slice(0, batches);\n\n for (const record of executed) {\n if (!batchNumbers.includes(record.batch)) continue;\n\n const MigrationClass = this.migrations.find(\n (m) => m.migrationName === record.name && this.sourceOf(m) === dataSource,\n );\n if (MigrationClass) {\n migrations.push(MigrationClass);\n batchOf.set(MigrationClass, record.batch);\n } else {\n orphans.push({ name: record.name, dataSource });\n }\n }\n }\n\n if (orphans.length > 0) {\n if (!options.pruneMissing) {\n throw new Error(\n `Cannot roll back: ${orphans.length} executed migration(s) have no registered file: ` +\n `${orphans.map((o) => o.name).join(\", \")}. ` +\n `They were renamed, deleted, or not matched by the migration pattern. ` +\n `Restore the file(s), or pass pruneMissing (--prune-missing) to delete those records.`,\n );\n }\n\n if (!options.readOnly) {\n for (const orphan of orphans) {\n await this.removeMigrationRecord(orphan.name, orphan.dataSource);\n log.warn(\"database\", \"migration\", `Pruned orphaned migration record: ${orphan.name}`);\n }\n }\n }\n\n // Newest batch first, then newest migration first within a batch.\n return migrations.sort(\n (a, b) => (batchOf.get(b) ?? 0) - (batchOf.get(a) ?? 0) || sortMigrationsForRollback(a, b),\n );\n }\n\n /**\n * Get executed migration records.\n */\n public async getExecutedMigrations(\n dataSource: DataSource = this.getDataSource(),\n options: { readOnly?: boolean } = {},\n ): Promise<MigrationRecord[]> {\n const driver = dataSource.driver;\n const migrationDriver = this.getMigrationDriver(dataSource);\n\n if (options.readOnly) {\n // Dry runs and listings must not create the migrations table.\n if (!(await migrationDriver.tableExists(this.migrationsTable))) return [];\n } else {\n // A missing table is created here; every other error (connection,\n // permission…) propagates instead of looking like \"nothing executed\".\n await migrationDriver.ensureMigrationsTable(this.migrationsTable);\n }\n\n const queryBuilder = driver.queryBuilder<MigrationRecord>(this.migrationsTable);\n const records = await queryBuilder.orderBy(\"batch\", \"asc\").orderBy(\"name\", \"asc\").get();\n\n // The Mongo lock document lives in this collection; it is not a migration.\n return records.filter((record) => record.name !== MIGRATION_LOCK_NAME);\n }\n\n /**\n * Record a migration.\n */\n private async recordMigration(\n name: string,\n batch: number,\n createdAt?: Date,\n dataSource: DataSource = this.getDataSource(),\n ): Promise<void> {\n const driver = dataSource.driver;\n const migrationDriver = this.getMigrationDriver(dataSource);\n\n // Ensure migrations table exists\n await migrationDriver.ensureMigrationsTable(this.migrationsTable);\n\n await driver.insert(this.migrationsTable, {\n name,\n batch,\n executedAt: new Date(),\n createdAt,\n });\n }\n\n /**\n * Remove a migration record.\n */\n private async removeMigrationRecord(\n name: string,\n dataSource: DataSource = this.getDataSource(),\n ): Promise<void> {\n const driver = dataSource.driver;\n await driver.delete(this.migrationsTable, { name });\n }\n\n /**\n * Get next batch number.\n */\n private async getNextBatchNumber(\n dataSource: DataSource = this.getDataSource(),\n readOnly = false,\n ): Promise<number> {\n const executed = await this.getExecutedMigrations(dataSource, { readOnly });\n if (executed.length === 0) return 1;\n return Math.max(...executed.map((r) => r.batch)) + 1;\n }\n}\n\nexport const migrationRunner = new MigrationRunner();\n"],"mappings":";;;;;;;;;;;AAqFA,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;AAC3B,MAAM,wBAAwB,MAAU;AACxC,MAAM,yBAAyB,KAAK;AACpC,MAAM,0BAA0B;AAsBhC,MAAM,SAAS,OAAe,IAAI,SAAe,YAAY,WAAW,SAAS,EAAE,CAAC;;;;;;AAOpF,SAAgB,mBAAmB,MAAsB;CAGvD,QAFiB,KAAK,SAAS,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM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AI1B,MAHwB,KAAK,mBAAmB,UAG5B,CAAC,CAAC,sBAAsB,KAAK,eAAe;EAEhE,MAAM,OAAO,OAAO,KAAK,iBAAiB;GACxC;GACA;GACA,4BAAY,IAAI,KAAK;GACrB;EACF,CAAC;CACH;;;;CAKA,MAAc,sBACZ,MACA,aAAyB,KAAK,cAAc,GAC7B;EAEf,MADe,WAAW,OACb,OAAO,KAAK,iBAAiB,EAAE,KAAK,CAAC;CACpD;;;;CAKA,MAAc,mBACZ,aAAyB,KAAK,cAAc,GAC5C,WAAW,OACM;EACjB,MAAM,WAAW,MAAM,KAAK,sBAAsB,YAAY,EAAE,SAAS,CAAC;EAC1E,IAAI,SAAS,WAAW,GAAG,OAAO;EAClC,OAAO,KAAK,IAAI,GAAG,SAAS,KAAK,MAAM,EAAE,KAAK,CAAC,IAAI;CACrD;AACF;AAEA,MAAa,kBAAkB,IAAI,gBAAgB"}
1
+ {"version":3,"file":"migration-runner.mjs","names":[],"sources":["../../../../../../../../packages/cascade/src/migration/migration-runner.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport { log } from \"@warlock.js/logger\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport type { MigrationDriverContract } from \"../contracts/migration-driver.contract\";\nimport type { DataSource } from \"../data-source/data-source\";\nimport { dataSourceRegistry } from \"../data-source/data-source-registry\";\nimport {\n type Migration,\n type MigrationContract,\n type MigrationOrigin,\n type MigrationStep,\n} from \"./migration\";\nimport { sortMigrations, sortMigrationsForRollback } from \"./migration-order\";\nimport { parseCreatedAt } from \"./parse-created-at\";\nimport { SQLGrammar } from \"./sql-grammar\";\nimport type { MigrationRecord, MigrationResult, TaggedSQL } from \"./types\";\n\n/**\n * Migration class type with static name property.\n */\ntype MigrationClass = (new () => Migration) & {\n migrationName: string;\n createdAt?: string;\n origin?: MigrationOrigin;\n};\n\n/**\n * What a caller may hand to {@link MigrationRunner.register}.\n *\n * Looser than {@link MigrationClass} in exactly one way: `migrationName` may be\n * absent. That is the documented workflow — the CLI imports a migration file and\n * sets the name from the filename afterwards — and `register()` enforces it at\n * runtime, throwing a message that says so. Once past that check the name IS\n * present, which is why everything stored and read downstream uses the stricter\n * type. Requiring it on the INPUT made the runner reject the very classes the\n * public `MigrationConstructor` describes.\n *\n * It constructs a MigrationContract rather than the abstract Migration class for the\n * same reason: `typeof Migration` is abstract and cannot satisfy `new () => Migration`,\n * and the public MigrationConstructor is declared against the contract. The runner only\n * ever uses contract members on what it registers.\n */\ntype RegisterableMigration = (new () => MigrationContract) & {\n migrationName?: string;\n createdAt?: string;\n origin?: MigrationOrigin;\n};\n\n/**\n * Resolved instance data for a single pending migration.\n * @internal\n */\ntype MigrationData = {\n MigrationClass: MigrationClass;\n migration: Migration;\n name: string;\n /** Data source this migration runs against (its own, else the runner's). */\n dataSource: DataSource;\n /** Serialized `up()` statements (empty for direct-execution drivers). */\n statements: string[];\n /** Same as `statements`, with queued data steps kept in authored order. */\n steps: MigrationStep[];\n /** Whether the migration runs inside a transaction. */\n transactional: boolean;\n /** Driver has no SQL dialect (MongoDB): executed through `runMigration`. */\n direct: boolean;\n};\n\n/**\n * Options for migration execution.\n */\ntype ExecuteOptions = {\n /** Run in dry-run mode (no actual changes) */\n readonly dryRun?: boolean;\n /** Record to migrations table (default: true for batch, false for single) */\n readonly record?: boolean;\n /**\n * Rollback only: delete the `_migrations` rows whose migration file is no\n * longer registered, instead of failing on them.\n */\n readonly pruneMissing?: boolean;\n};\n\n/** Name of the lock document Mongo migrations claim inside the migrations collection. */\nconst MIGRATION_LOCK_NAME = \"__warlock_migration_lock__\";\nconst MIGRATION_LOCK_KEY = \"warlock:migrations\";\nconst MIGRATION_LOCK_TTL_MS = 10 * 60 * 1000;\nconst MIGRATION_LOCK_WAIT_MS = 60 * 1000;\nconst MIGRATION_LOCK_RETRY_MS = 1000;\n\n/** Held lock for one data source. `refresh` extends the TTL; `release` frees it. */\ntype MigrationLock = {\n refresh: () => Promise<void>;\n release: () => Promise<void>;\n};\n\ntype PgLockClient = {\n query: (sql: string, params?: unknown[]) => Promise<unknown>;\n release: () => void;\n};\n\n/** Minimal Mongo surface the lock needs (kept structural: no driver import). */\ntype MongoLockDatabase = {\n collection: (name: string) => {\n findOneAndUpdate: (filter: object, update: object, options: object) => Promise<unknown>;\n findOne: (filter: object) => Promise<{ owner?: string; expiresAt?: unknown } | null>;\n deleteOne: (filter: object) => Promise<unknown>;\n };\n};\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\n/**\n * Derive a migration name from a file path: drop everything after the first dot\n * and strip a trailing `-migration` / `_migration` suffix. Shared by every CLI\n * so the same file is recorded under the same name.\n */\nexport function inferMigrationName(file: string): string {\n const basename = path.basename(file).split(\".\")[0] ?? \"\";\n\n return basename.replace(/-migration$/, \"\").replace(/_migration$/, \"\");\n}\n\n/**\n * Migration runner that executes migrations.\n *\n * This is a pure executor - it doesn't discover migrations.\n * Discovery is handled by the framework (e.g., @warlock.js/core CLI).\n *\n * The migration name is read from the static `name` property on the class,\n * which should be set by the CLI after importing:\n *\n * @example\n * ```typescript\n * // In CLI after importing:\n * const { default: MigrationClass } = await import(\"./create-users.migration.ts\");\n * MigrationClass.migrationName ??= \"create-users\";\n *\n * // Then register or execute:\n * runner.register(MigrationClass);\n * // or\n * await runner.execute(MigrationClass);\n * ```\n *\n * @example\n * ```typescript\n * // Simple direct execution\n * await runner.execute(CreateUsersTable);\n * await runner.rollback(CreateUsersTable);\n *\n * // Registry pattern for batch operations\n * runner.register(CreateUsersTable);\n * runner.register(AddEmailIndex);\n * await runner.runAll();\n * await runner.rollbackAll();\n * ```\n */\nexport class MigrationRunner {\n /** Registered migrations */\n public readonly migrations: MigrationClass[] = [];\n\n /** Data source to use */\n private dataSource?: DataSource;\n\n /** Cached migration drivers, one per data source */\n private readonly migrationDrivers = new Map<DataSource, MigrationDriverContract>();\n\n /** Table name for tracking migrations */\n private readonly migrationsTable: string;\n\n /** Whether to log operations */\n private readonly verbose: boolean;\n\n /**\n * Create a new migration runner.\n *\n * @param options - Runner options\n */\n public constructor(\n options: {\n dataSource?: DataSource;\n migrationsTable?: string;\n verbose?: boolean;\n } = {},\n ) {\n this.dataSource = options.dataSource;\n this.migrationsTable = options.migrationsTable ?? \"_migrations\";\n this.verbose = options.verbose ?? true;\n }\n\n // ============================================================================\n // DATA SOURCE\n // ============================================================================\n\n /**\n * Set the data source.\n */\n public setDataSource(dataSource: DataSource): this {\n this.dataSource = dataSource;\n this.migrationDrivers.clear();\n return this;\n }\n\n /**\n * Get the data source.\n */\n private getDataSource(): DataSource {\n if (!this.dataSource) {\n this.dataSource = dataSourceRegistry.get();\n }\n return this.dataSource;\n }\n\n /**\n * Get the migration driver.\n */\n private getMigrationDriver(\n dataSource: DataSource = this.getDataSource(),\n ): MigrationDriverContract {\n let driver = this.migrationDrivers.get(dataSource);\n if (!driver) {\n driver = dataSource.driver.migrationDriver();\n this.migrationDrivers.set(dataSource, driver);\n }\n return driver;\n }\n\n /**\n * Resolve a migration's declared data source (name or instance).\n * Falls back to the runner's own data source when it declares none.\n */\n private resolveDataSource(declared?: string | DataSource): DataSource {\n if (!declared) return this.getDataSource();\n if (typeof declared === \"string\") return dataSourceRegistry.get(declared);\n return declared;\n }\n\n /** Data source a registered migration class runs against. */\n private sourceOf(MigrationClass: MigrationClass): DataSource {\n return this.resolveDataSource(new MigrationClass().dataSource);\n }\n\n /** Distinct data sources across the registered migrations (runner's own included). */\n private getSources(): DataSource[] {\n const sources = new Set<DataSource>([this.getDataSource()]);\n for (const MigrationClass of this.migrations) {\n sources.add(this.sourceOf(MigrationClass));\n }\n return [...sources];\n }\n\n /**\n * Resolve whether a migration runs in a transaction:\n * 1. migration-level flag (instance, else the static from `Migration.create/alter`)\n * 2. `CONCURRENTLY` statements cannot run in a transaction block\n * 3. data-source config\n * 4. driver default\n */\n private resolveTransactional(\n MigrationClass: MigrationClass,\n migration: Migration,\n dataSource: DataSource,\n statements: string[] = [],\n ): boolean {\n const explicit =\n migration.transactional ?? (MigrationClass as { transactional?: boolean }).transactional;\n\n if (explicit !== undefined) return explicit;\n\n if (statements.some((sql) => /\\bCONCURRENTLY\\b/i.test(sql))) return false;\n\n return (\n dataSource.migrations?.transactional ??\n this.getMigrationDriver(dataSource).getDefaultTransactional()\n );\n }\n\n // ============================================================================\n // LOCKING\n // ============================================================================\n\n /** Locks held by the run in progress (Mongo TTL heartbeat). */\n private activeLocks: MigrationLock[] = [];\n\n /** Extend every held lock's TTL; called between migrations. */\n private async refreshLocks(): Promise<void> {\n for (const lock of this.activeLocks) {\n await lock.refresh();\n }\n }\n\n /**\n * Run `callback` while holding a migration lock on every given data source, so\n * concurrent `migrate` invocations (replicas, init containers) serialize.\n */\n private async withLock<T>(sources: DataSource[], callback: () => Promise<T>): Promise<T> {\n const held: MigrationLock[] = [];\n\n try {\n for (const dataSource of sources) {\n const lock = await this.acquireLock(dataSource);\n if (lock) held.push(lock);\n }\n\n this.activeLocks = held;\n\n return await callback();\n } finally {\n this.activeLocks = [];\n\n for (const lock of held.reverse()) {\n try {\n await lock.release();\n } catch (error) {\n log.warn(\n \"database\",\n \"migration\",\n `Failed to release migration lock: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n }\n }\n\n /** Acquire the lock for one data source; `undefined` when its driver has no lock support. */\n private async acquireLock(dataSource: DataSource): Promise<MigrationLock | undefined> {\n const driver = dataSource.driver as unknown as {\n name: string;\n getClient?: () => { connect?: () => Promise<PgLockClient> };\n getDatabase?: () => MongoLockDatabase;\n };\n\n if (driver.name === \"postgres\" && driver.getClient) {\n // A dedicated client: advisory locks are per-session, not per-pool.\n const client = await driver.getClient().connect?.();\n if (!client) return undefined;\n\n try {\n await client.query(\"SELECT pg_advisory_lock(hashtext($1))\", [MIGRATION_LOCK_KEY]);\n } catch (error) {\n client.release();\n throw error;\n }\n\n return {\n refresh: async () => {},\n release: async () => {\n try {\n await client.query(\"SELECT pg_advisory_unlock(hashtext($1))\", [MIGRATION_LOCK_KEY]);\n } finally {\n client.release();\n }\n },\n };\n }\n\n if (driver.getDatabase) {\n // The unique index on `name` (created here) makes the claim below atomic.\n await this.getMigrationDriver(dataSource).ensureMigrationsTable(this.migrationsTable);\n\n const collection = driver.getDatabase().collection(this.migrationsTable);\n const owner = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n const deadline = Date.now() + MIGRATION_LOCK_WAIT_MS;\n\n const claim = async (): Promise<boolean> => {\n const now = new Date();\n\n try {\n await collection.findOneAndUpdate(\n {\n name: MIGRATION_LOCK_NAME,\n $or: [{ expiresAt: { $lt: now } }, { owner }],\n },\n {\n $set: { owner, expiresAt: new Date(now.getTime() + MIGRATION_LOCK_TTL_MS) },\n $setOnInsert: { batch: 0 },\n },\n { upsert: true },\n );\n\n return true;\n } catch (error) {\n // Held by someone else: the upsert collides with the unique `name` index.\n if ((error as { code?: number }).code === 11000) return false;\n throw error;\n }\n };\n\n while (!(await claim())) {\n if (Date.now() >= deadline) {\n const holder = await collection.findOne({ name: MIGRATION_LOCK_NAME });\n throw new Error(\n `Could not acquire the migration lock within ${MIGRATION_LOCK_WAIT_MS / 1000}s; ` +\n `held by \"${holder?.owner ?? \"unknown\"}\" until ${holder?.expiresAt ?? \"unknown\"}.`,\n );\n }\n\n await sleep(MIGRATION_LOCK_RETRY_MS);\n }\n\n return {\n refresh: async () => {\n await claim();\n },\n release: async () => {\n await collection.deleteOne({ name: MIGRATION_LOCK_NAME, owner });\n },\n };\n }\n\n return undefined;\n }\n\n // ============================================================================\n // REGISTRATION\n // ============================================================================\n\n /**\n * Register a migration.\n *\n * The migration name is read from `MigrationClass.migrationName`.\n *\n * @param MigrationClass - Migration class (must have static `name` set)\n * @param origin - Registration source; defaults to `\"app\"` for direct registrations.\n * @returns This runner for chaining\n *\n * @example\n * ```typescript\n * CreateUsersTable.migrationName = \"2024-01-15_create-users\";\n * runner.register(CreateUsersTable);\n * ```\n */\n public register(MigrationClass: RegisterableMigration, origin: MigrationOrigin = \"app\"): this {\n const name = MigrationClass.migrationName;\n if (!name) {\n throw new Error(\n `Migration class must have a static 'migrationName' property set. ` +\n `Set it in CLI after importing: MigrationClass.migrationName = \"filename\";`,\n );\n }\n const existing = this.migrations.find((m) => m.migrationName === name);\n\n if (existing) {\n // Re-registering the same class is idempotent; a DIFFERENT class under the\n // same name would silently never run, so fail loudly.\n if ((existing as unknown) !== MigrationClass) {\n throw new Error(\n `Duplicate migration name \"${name}\": two different migration classes resolve to the same name. ` +\n `Rename one of the files (or set a unique static 'migrationName').`,\n );\n }\n\n return this;\n }\n\n // `name` is proven present by the throw above, so this satisfies the stricter\n // stored type that every reader downstream relies on.\n MigrationClass.origin = origin;\n this.migrations.push(MigrationClass as MigrationClass);\n\n return this;\n }\n\n /**\n * Register multiple migrations.\n *\n * @param migrations - Array of migration classes\n * @returns This runner for chaining\n */\n public registerMany(migrations: RegisterableMigration[]): this {\n for (const MigrationClass of migrations) {\n this.register(MigrationClass);\n }\n return this;\n }\n\n /**\n * Clear all registered migrations.\n */\n public clear(): this {\n this.migrations.length = 0;\n return this;\n }\n\n /**\n * Get all registered migration names.\n */\n public getRegisteredNames(): string[] {\n return this.migrations.map((m) => m.migrationName);\n }\n\n // ============================================================================\n // SINGLE EXECUTION\n // ============================================================================\n\n /**\n * Execute a single migration's up() method.\n *\n * @param MigrationClass - Migration class to execute\n * @param options - Execution options\n * @returns Migration result\n *\n * @example\n * ```typescript\n * await runner.execute(CreateUsersTable);\n * await runner.execute(AddEmailIndex, { dryRun: true });\n * ```\n */\n public async run(\n MigrationClass: MigrationClass,\n options: ExecuteOptions = {},\n ): Promise<MigrationResult> {\n return this.runMigration(MigrationClass, \"up\", {\n dryRun: options.dryRun,\n record: options.record ?? false,\n });\n }\n\n /**\n * Execute a single migration's down() method.\n *\n * @param MigrationClass - Migration class to rollback\n * @param options - Execution options\n * @returns Migration result\n *\n * @example\n * ```typescript\n * await runner.rollback(CreateUsersTable);\n * ```\n */\n public async rollback(\n MigrationClass: MigrationClass,\n options: ExecuteOptions = {},\n ): Promise<MigrationResult> {\n return this.runMigration(MigrationClass, \"down\", {\n dryRun: options.dryRun,\n record: options.record ?? false,\n });\n }\n\n // ============================================================================\n // BATCH EXECUTION (REGISTERED MIGRATIONS)\n // ============================================================================\n\n /**\n * Run all pending registered migrations.\n *\n * Only runs migrations not already in the migrations table.\n *\n * @param options - Execution options\n * @returns Results for each migration\n *\n * @example\n * ```typescript\n * runner.register(CreateUsersTable);\n * runner.register(AddEmailIndex);\n * const results = await runner.runAll();\n * ```\n */\n public async runAll(options: ExecuteOptions = {}): Promise<MigrationResult[]> {\n // A dry run writes nothing, so it needs no lock.\n if (options.dryRun) return this.runAllUnlocked(options);\n\n // The pending set is computed INSIDE the lock, so a replica that waited sees\n // what the winner already applied.\n return this.withLock(this.getSources(), () => this.runAllUnlocked(options));\n }\n\n private async runAllUnlocked(options: ExecuteOptions): Promise<MigrationResult[]> {\n const { dryRun = false, record = true } = options;\n\n const results: MigrationResult[] = [];\n\n // Get pending migrations (a dry run must not create the migrations table)\n const pending = await this.getPendingMigrations({ readOnly: dryRun });\n\n if (pending.length === 0) {\n log.warn(\"database\", \"migration\", \"Nothing to migrate.\");\n return results;\n }\n\n // Next batch number per data source: each source has its own migrations table.\n const sources = new Set<DataSource>();\n const migrationsData: MigrationData[] = [];\n\n log.info(\"database\", \"migration\", `Found ${pending.length} pending migration(s).`);\n\n // 1. Resolve each migration's data source and transactional mode, and collect\n // its SQL. Drivers without SQL serialization (MongoDB) are executed\n // directly through the migration driver instead.\n // Extension checks fire concurrently as CREATE EXTENSION statements are met.\n const extensionChecks: Promise<void>[] = [];\n\n for (const MigrationClass of pending) {\n const migration = this.createMigrationInstance(MigrationClass);\n const name = MigrationClass.migrationName;\n const dataSource = this.resolveDataSource(migration.dataSource);\n sources.add(dataSource);\n\n if (dataSource.driver.supportsSqlSerialization === false) {\n migrationsData.push({\n MigrationClass,\n migration,\n name,\n dataSource,\n statements: [],\n steps: [],\n transactional: false,\n direct: true,\n });\n continue;\n }\n\n migration.setDriver(this.getMigrationDriver(dataSource));\n migration.setMigrationDefaults(dataSource.migrationDefaults);\n // Collection must not run `withConnection` side effects during a dry run.\n migration.setDryRun?.(dryRun);\n\n await migration.up();\n const steps: MigrationStep[] = migration.toSteps?.() ?? migration.toSQL();\n const statements = steps.map((step) =>\n typeof step === \"string\" ? step : \"-- data step (withConnection) skipped\",\n );\n migration.setDryRun?.(false);\n\n migrationsData.push({\n MigrationClass,\n migration,\n name,\n dataSource,\n statements,\n steps,\n transactional:\n !!dataSource.driver.transaction &&\n this.resolveTransactional(MigrationClass, migration, dataSource, statements),\n direct: false,\n });\n\n for (const sql of statements) {\n if (SQLGrammar.classify(sql) === \"CREATE_EXTENSION\") {\n const ext = SQLGrammar.extractExtensionName(sql);\n if (ext) extensionChecks.push(this.informIfExtensionMissing(ext, dataSource));\n }\n }\n }\n\n // 2. Resolve all extension checks before any SQL is executed.\n await Promise.all(extensionChecks);\n\n // 3. Dry run: print statements in migration order (authored order kept; no\n // global phase sort, which would reorder add-column → backfill → NOT NULL).\n if (dryRun) {\n log.info(\"database\", \"migration\", \"Dry run enabled. Would execute the following statements:\");\n for (const data of migrationsData) {\n for (const sql of data.statements) {\n console.log(\n `-- [${SQLGrammar.classify(sql)}] Phase ${SQLGrammar.phase(sql)} [${data.name}]`,\n );\n console.log(sql + \";\\n\");\n }\n }\n return [];\n }\n\n const batches = new Map<DataSource, number>();\n for (const dataSource of sources) {\n batches.set(dataSource, await this.getNextBatchNumber(dataSource));\n }\n\n // 4. Split into runs: consecutive transactional migrations on the same data\n // source share one transaction; every other migration (non-transactional\n // or direct) runs alone.\n const runs: MigrationData[][] = [];\n for (const data of migrationsData) {\n const last = runs[runs.length - 1];\n const lastFirst = last?.[0];\n if (\n data.transactional &&\n last &&\n lastFirst?.transactional &&\n lastFirst.dataSource === data.dataSource\n ) {\n last.push(data);\n } else {\n runs.push([data]);\n }\n }\n\n for (const run of runs) {\n const first = run[0];\n if (!first) continue;\n await this.refreshLocks();\n const dataSource = first.dataSource;\n const nextBatch = batches.get(dataSource)!;\n const startTime = Date.now();\n\n if (first.direct) {\n const result = await this.runMigration(first.MigrationClass, \"up\", {\n dryRun,\n record,\n batch: nextBatch,\n });\n results.push(result);\n if (!result.success) break;\n continue;\n }\n\n const driver = dataSource.driver;\n let failed = false;\n let errorMessage = \"\";\n /** The migration that owns the SQL statement that threw. */\n let failingMigrationName: string | undefined;\n\n const executeRun = async (): Promise<void> => {\n for (const data of run) {\n for (const step of data.steps) {\n try {\n if (typeof step === \"string\") await driver.query(step);\n else await step.data();\n } catch (err) {\n failingMigrationName = data.name;\n throw err;\n }\n }\n\n // A non-transactional migration is recorded right after it applied.\n // Transactional ones are recorded inside the shared transaction.\n if (record) {\n await this.recordMigration(\n data.name,\n nextBatch,\n data.MigrationClass.createdAt\n ? parseCreatedAt(data.MigrationClass.createdAt)\n : new Date(),\n dataSource,\n );\n }\n }\n };\n\n try {\n if (first.transactional && driver.transaction) {\n await driver.transaction(executeRun);\n } else {\n await executeRun();\n }\n } catch (err) {\n failed = true;\n errorMessage = err instanceof Error ? err.message : String(err);\n }\n\n const durationMs = Date.now() - startTime;\n\n // Only the migration that owns the failing statement is marked failed;\n // the rest of its run is reported as rolled back.\n for (const data of run) {\n const isCulprit = failed && data.name === failingMigrationName;\n const wasSkipped = failed && !isCulprit;\n\n results.push({\n name: data.name,\n table: data.migration.table,\n direction: \"up\",\n success: !failed,\n error: isCulprit ? errorMessage : undefined,\n durationMs: Math.round(durationMs / run.length),\n executedAt: new Date(),\n });\n\n if (isCulprit) {\n log.error(\n \"database\",\n \"migration\",\n `${colors.magenta(data.name)}: ✗ Failed: ${errorMessage}`,\n );\n } else if (wasSkipped) {\n log.warn(\n \"database\",\n \"migration\",\n `${colors.magenta(data.name)}: rolled back (batch transaction failed)`,\n );\n } else {\n log.success(\n \"database\",\n \"migration\",\n `Migrated: ${colors.magenta(data.name)} successfully`,\n );\n }\n }\n\n if (failed) {\n log.error(\n \"database\",\n \"migration\",\n `Batch execution failed. Rollback performed if transactional.`,\n );\n throw new Error(\"Migration batch failed: \" + errorMessage);\n }\n }\n\n const successCount = results.filter((r) => r.success).length;\n log.success(\n \"database\",\n \"migration\",\n `Migration execution complete: ${successCount}/${pending.length} migrations processed successfully.`,\n );\n\n return results;\n }\n\n /**\n * Export migrations as phase-ordered SQL files in database/sql/ directory.\n * By default, it exports all registered migrations. Use `pendingOnly: true` to export only pending ones.\n */\n public async exportSQL(\n options: { pendingOnly?: boolean; compact?: boolean } = {},\n ): Promise<void> {\n if (this.getDataSource().driver.supportsSqlSerialization === false) {\n throw new Error(\n \"SQL export is not supported on this data source — its driver has no SQL dialect. \" +\n \"Migrations on this driver execute native commands through the migration driver instead.\",\n );\n }\n\n const migrationsToExport = options.pendingOnly\n ? await this.getPendingMigrations({ readOnly: true })\n : this.migrations;\n\n if (migrationsToExport.length === 0) {\n log.warn(\"database\", \"migration\", \"No migrations to export.\");\n return;\n }\n\n log.info(\n \"database\",\n \"migration\",\n `Exporting ${migrationsToExport.length} ${options.pendingOnly ? \"pending \" : \"\"}migration(s) to SQL files...`,\n );\n\n const upStatements: TaggedSQL[] = [];\n // Down SQL is grouped per migration so only the migration order is reversed,\n // never the statements inside one migration's down().\n const downGroups: { createdAt?: string; index: number; statements: TaggedSQL[] }[] = [];\n\n for (const [index, MigrationClass] of migrationsToExport.entries()) {\n const migration = this.createMigrationInstance(MigrationClass);\n const name = MigrationClass.migrationName;\n\n // Export performs no writes: `withConnection` callbacks are skipped.\n migration.setDryRun?.(true);\n\n // Collect up SQL\n await migration.up();\n for (const sql of migration.toSQL()) {\n upStatements.push({\n sql,\n phase: SQLGrammar.phase(sql),\n statementType: SQLGrammar.classify(sql),\n createdAt: MigrationClass.createdAt,\n migrationName: name,\n });\n }\n\n // Collect down SQL (reuse same instance — toSQL() cleared pendingOps)\n await migration.down();\n const statements: TaggedSQL[] = [];\n for (const sql of migration.toSQL()) {\n statements.push({\n sql,\n phase: SQLGrammar.phase(sql),\n statementType: SQLGrammar.classify(sql),\n createdAt: MigrationClass.createdAt,\n migrationName: name,\n });\n }\n downGroups.push({ createdAt: MigrationClass.createdAt, index, statements });\n }\n\n const sortedUp = SQLGrammar.sort(upStatements);\n // Down SQL: newest migration first (chronological, registration order breaks\n // ties), each migration's own down() statements keep their order.\n const sortedDown = downGroups\n .sort((a, b) => {\n const byDate = (a.createdAt ?? \"\").localeCompare(b.createdAt ?? \"\");\n return byDate !== 0 ? byDate : a.index - b.index;\n })\n .reverse()\n .flatMap((group) => group.statements);\n\n const upSQLString = this.formatSQLForExport(sortedUp, options.compact);\n const downSQLString = this.formatSQLForExport(sortedDown, options.compact);\n\n const rootPath = process.cwd();\n const sqlDir = path.join(rootPath, \"database\", \"sql\");\n\n if (!fs.existsSync(sqlDir)) {\n fs.mkdirSync(sqlDir, { recursive: true });\n }\n\n const timestamp = new Date().toISOString().replace(/T/, \"_\").replace(/:/g, \"-\").split(\".\")[0];\n const upPath = path.join(sqlDir, `migration_${timestamp}.up.sql`);\n const downPath = path.join(sqlDir, `migration_${timestamp}.down.sql`);\n\n fs.writeFileSync(upPath, upSQLString);\n fs.writeFileSync(downPath, downSQLString);\n\n log.success(\"database\", \"migration\", `Exported to:\\n- ${upPath}\\n- ${downPath}`);\n }\n\n /**\n * Rollback the last batch of migrations.\n *\n * @param options - Execution options\n * @returns Results for each migration\n */\n public async rollbackLast(options: ExecuteOptions = {}): Promise<MigrationResult[]> {\n return this.rollbackBatches(1, options);\n }\n\n /**\n * Rollback N batches of migrations.\n *\n * @param batches - Number of batches to rollback\n * @param options - Execution options\n * @returns Results for each migration\n */\n public async rollbackBatches(\n batches: number,\n options: ExecuteOptions = {},\n ): Promise<MigrationResult[]> {\n if (options.dryRun) return this.rollbackBatchesUnlocked(batches, options);\n\n return this.withLock(this.getSources(), () => this.rollbackBatchesUnlocked(batches, options));\n }\n\n private async rollbackBatchesUnlocked(\n batches: number,\n options: ExecuteOptions,\n ): Promise<MigrationResult[]> {\n const dryRun = options.dryRun ?? false;\n const record = options.record ?? true;\n const results: MigrationResult[] = [];\n\n const toRollback = await this.getMigrationsToRollback(batches, {\n pruneMissing: options.pruneMissing,\n readOnly: dryRun,\n });\n\n if (toRollback.length === 0) {\n log.warn(\"database\", \"migration\", \"Nothing to rollback.\");\n return results;\n }\n\n log.info(\"database\", \"migration\", `Rolling back ${toRollback.length} migration(s).`);\n\n for (const MigrationClass of toRollback) {\n await this.refreshLocks();\n\n const result = await this.runMigration(MigrationClass, \"down\", {\n dryRun,\n record,\n });\n results.push(result);\n\n if (!result.success) {\n break;\n }\n }\n\n const successCount = results.filter((r) => r.success).length;\n log.success(\n \"database\",\n \"migration\",\n `Rollback complete: ${successCount}/${toRollback.length} successful.`,\n );\n\n return results;\n }\n\n /**\n * Rollback all executed migrations.\n *\n * @param options - Execution options\n * @returns Results for each migration\n */\n public async rollbackAll(options: ExecuteOptions = {}): Promise<MigrationResult[]> {\n // Batch numbers are per data source; rolling back \"all\" is every batch of each.\n return this.rollbackBatches(Number.POSITIVE_INFINITY, options);\n }\n\n /**\n * Reset and re-run: rollback all then run all.\n *\n * @param options - Execution options\n * @returns Combined results\n */\n public async fresh(options: ExecuteOptions = {}): Promise<MigrationResult[]> {\n const rollbackResults = await this.rollbackAll(options);\n const runResults = await this.runAll(options);\n return [...rollbackResults, ...runResults];\n }\n\n // ============================================================================\n // STATUS\n // ============================================================================\n\n /**\n * Get status of all registered migrations.\n */\n public async status(): Promise<\n Array<{\n name: string;\n table: string;\n executed: boolean;\n batch: number | null;\n }>\n > {\n const executedBySource = new Map<DataSource, Map<string, MigrationRecord>>();\n\n for (const dataSource of this.getSources()) {\n const executed = await this.getExecutedMigrations(dataSource, { readOnly: true });\n executedBySource.set(dataSource, new Map(executed.map((r) => [r.name, r])));\n }\n\n return this.migrations.map((MigrationClass) => {\n const instance = new MigrationClass();\n const name = MigrationClass.migrationName;\n const record = executedBySource.get(this.sourceOf(MigrationClass))?.get(name);\n return {\n name,\n table: instance.table,\n executed: !!record,\n batch: record?.batch ?? null,\n };\n });\n }\n\n // ============================================================================\n // EXTENSION PRE-FLIGHT\n // ============================================================================\n\n /**\n * Check whether a database extension is available and inform the developer\n * if it is not installed.\n *\n * Does NOT throw — execution proceeds normally. If the extension is truly\n * missing, the database will surface its own error with full context already\n * displayed to the developer.\n *\n * @example\n * await this.informIfExtensionMissing(\"vector\");\n */\n private async informIfExtensionMissing(\n extension: string,\n dataSource: DataSource = this.getDataSource(),\n ): Promise<void> {\n try {\n const migrationDriver = this.getMigrationDriver(dataSource);\n const isAvailable = await migrationDriver.isExtensionAvailable(extension);\n\n if (!isAvailable) {\n const hr = \"─\".repeat(60);\n console.log(`\\n${colors.yellow(hr)}`);\n console.log(colors.yellow(` ⚠ Missing Database Extension: ${colors.bold(extension)}`));\n console.log(colors.yellow(hr));\n console.log();\n console.log(` A pending migration requires the ${colors.cyan(extension)} extension,`);\n console.log(` which is not installed on your database server.`);\n console.log();\n console.log(\n ` ${colors.bold(\"This means the physical database server is missing the extension package.\")}`,\n );\n console.log(` You cannot simply run CREATE EXTENSION until the package is installed`);\n console.log(` on the host machine or Docker container.`);\n console.log();\n\n const docsUrl = migrationDriver.getExtensionDocsUrl(extension);\n if (docsUrl) {\n console.log(` ${colors.bold(\"Or follow the installation guide:\")}`);\n console.log(` ${colors.cyan(docsUrl)}`);\n }\n console.log(`\\n${colors.yellow(hr)}\\n`);\n }\n } catch {\n // If the check itself fails, silently skip — don't break the migration.\n }\n }\n\n // ============================================================================\n // PRIVATE HELPERS\n // ============================================================================\n\n /**\n * Run a single migration.\n */\n private async runMigration(\n MigrationClass: MigrationClass,\n direction: \"up\" | \"down\",\n options: {\n dryRun?: boolean;\n record?: boolean;\n batch?: number;\n } = {},\n ): Promise<MigrationResult> {\n const { dryRun = false, record = true } = options;\n const startTime = Date.now();\n let success = true;\n let error: string | undefined;\n\n const migration = new MigrationClass();\n const name = MigrationClass.migrationName;\n\n log.info(\n \"database\",\n \"migration\",\n `${direction === \"up\" ? \"Migrating\" : \"Rolling back\"}: ${colors.magenta(name)}...`,\n );\n\n try {\n if (!dryRun) {\n // The migration runs against its declared data source (default: the runner's)\n // and is recorded in THAT source's migrations table.\n const dataSource = this.resolveDataSource(migration.dataSource);\n const driver = this.getMigrationDriver(dataSource);\n migration.setDriver(driver);\n migration.setMigrationDefaults(dataSource.migrationDefaults);\n\n // ============================================================================\n // TRANSACTION RESOLUTION (3-tier hierarchy)\n // ============================================================================\n // 1. Migration-level explicit override (instance or static)\n // 2. CONCURRENTLY statements (cannot run in a transaction block)\n // 3. Config-level global override\n // 4. Driver default (PostgreSQL: true, MongoDB: false)\n // Resolved below, once the statements are known.\n\n // ============================================================================\n // EXECUTE WITH OR WITHOUT TRANSACTION\n // ============================================================================\n\n // Collect the requested direction's operations\n if (direction === \"up\") {\n await migration.up();\n } else {\n await migration.down();\n }\n\n const databaseDriver = dataSource.driver;\n\n // SQL-capable drivers serialize the queued operations to SQL strings;\n // drivers without SQL serialization (MongoDB) keep them queued and\n // execute them directly through the migration driver.\n const directExecution = databaseDriver.supportsSqlSerialization === false;\n const steps: MigrationStep[] = directExecution\n ? []\n : (migration.toSteps?.() ?? migration.toSQL());\n const sqlStatements = steps.filter((step): step is string => typeof step === \"string\");\n const shouldUseTransaction = this.resolveTransactional(\n MigrationClass,\n migration,\n dataSource,\n sqlStatements,\n );\n\n const applyMigration = async (): Promise<void> => {\n if (directExecution) {\n await migration.execute();\n return;\n }\n\n // Execute generated SQL statements sequentially (no phase-sorting here since it's single execution)\n for (const step of steps) {\n if (typeof step === \"string\") await databaseDriver.query(step);\n else await step.data();\n }\n };\n\n if (shouldUseTransaction && databaseDriver.transaction) {\n // Transactional execution\n await databaseDriver.transaction(async () => {\n await applyMigration();\n\n // Record migration tracking\n if (record) {\n if (direction === \"up\") {\n const batch = options.batch ?? (await this.getNextBatchNumber(dataSource));\n await this.recordMigration(\n name,\n batch,\n MigrationClass.createdAt ? parseCreatedAt(MigrationClass.createdAt) : new Date(),\n dataSource,\n );\n } else {\n await this.removeMigrationRecord(name, dataSource);\n }\n }\n });\n } else {\n // Non-transactional execution\n await applyMigration();\n\n if (record) {\n if (direction === \"up\") {\n const batch = options.batch ?? (await this.getNextBatchNumber(dataSource));\n await this.recordMigration(\n name,\n batch,\n MigrationClass.createdAt ? parseCreatedAt(MigrationClass.createdAt) : new Date(),\n dataSource,\n );\n } else {\n await this.removeMigrationRecord(name, dataSource);\n }\n }\n }\n }\n } catch (err) {\n success = false;\n error = err instanceof Error ? err.message : String(err);\n log.error(\"database\", \"migration\", `${colors.magenta(name)}: ✗ Failed: ${error}`);\n throw err;\n }\n\n const durationMs = Date.now() - startTime;\n\n if (success) {\n log.success(\n \"database\",\n \"migration\",\n `${direction == \"up\" ? \"Migrated\" : \"Rolled back\"}: ${colors.magenta(name)} successfully (${durationMs}ms)`,\n );\n }\n\n return {\n name,\n table: migration.table,\n direction,\n success,\n error,\n durationMs,\n executedAt: new Date(),\n };\n }\n\n /**\n * Create, configure, and return a ready-to-use migration instance.\n *\n * Centralises the repeated \"new + setDriver + setMigrationDefaults\" boilerplate\n * that all batch/single execution paths need.\n *\n * @internal\n */\n private createMigrationInstance(MigrationClass: MigrationClass): Migration {\n const migration = new MigrationClass();\n const dataSource = this.resolveDataSource(migration.dataSource);\n migration.setDriver(this.getMigrationDriver(dataSource));\n migration.setMigrationDefaults(dataSource.migrationDefaults);\n return migration;\n }\n\n /**\n * Format an ordered array of TaggedSQL into a human-readable SQL file string.\n *\n * Consecutive statements that belong to the same (phase, migration) group share\n * a single block comment at the top, avoiding the noisy per-statement repetition.\n *\n * Example output:\n * ```sql\n * /* Phase 3 [create-users] *\\/\n * ALTER TABLE \"users\" ADD COLUMN \"name\" TEXT NOT NULL;\n * ALTER TABLE \"users\" ADD COLUMN \"email\" TEXT NOT NULL;\n *\n * /* Phase 4 [create-users] *\\/\n * CREATE UNIQUE INDEX ...;\n * ```\n *\n * @internal\n */\n private formatSQLForExport(statements: TaggedSQL[], compact: boolean = false): string {\n const lines: string[] = [];\n\n if (compact) {\n // Just output raw statements, no grouping, no blank lines\n for (const stmt of statements) {\n lines.push(`${stmt.sql};`);\n }\n return lines.join(\"\\n\");\n }\n\n // Group statements by their phase and migration name\n const grouped = new Map<string, string[]>();\n\n for (const stmt of statements) {\n const groupKey = `Phase ${stmt.phase} [${stmt.migrationName}]`;\n if (!grouped.has(groupKey)) {\n grouped.set(groupKey, []);\n }\n grouped.get(groupKey)!.push(stmt.sql);\n }\n\n // Format each group\n for (const [groupKey, sqls] of grouped.entries()) {\n if (lines.length > 0) lines.push(\"\"); // blank line between groups\n lines.push(`/* ${groupKey} */`);\n for (const sql of sqls) {\n lines.push(`${sql};`);\n }\n }\n\n return lines.join(\"\\n\");\n }\n\n /**\n * Get pending (not executed) registered migrations, in the order they would\n * execute.\n *\n * ⚠️ \"Registered\" is load-bearing. This filters `this.migrations`, which is\n * populated only by `register()` / `registerMany()`. A caller that has not\n * registered anything gets `[]` — indistinguishable from a database with\n * nothing pending. Anything reporting this set to a human MUST register\n * migrations first, or it will print a confident all-clear over an unknown.\n *\n * @see listPendingMigrations\n */\n public async getPendingMigrations(\n options: { readOnly?: boolean } = {},\n ): Promise<MigrationClass[]> {\n // \"Executed\" is judged in each migration's own data source's migrations table.\n const executedNames = new Map<DataSource, Set<string>>();\n for (const dataSource of this.getSources()) {\n const executed = await this.getExecutedMigrations(dataSource, options);\n executedNames.set(dataSource, new Set(executed.map((r) => r.name)));\n }\n\n const migrations = this.migrations.filter(\n (m) => !executedNames.get(this.sourceOf(m))?.has(m.migrationName),\n );\n\n return migrations.sort(sortMigrations);\n }\n\n /**\n * Get migrations to rollback, newest-first.\n *\n * A rollback must undo migrations in the exact inverse of the order `up`\n * applied them, or a `down()` will hit schema its predecessor already\n * removed — dropping a table before dropping the column added to it, say.\n *\n * The sort has to be explicitly **descending**. Reversing the executed list\n * is not enough: `getExecutedMigrations` orders by `batch, name`, so the\n * input is alphabetical rather than chronological, and reversing it only\n * yields reverse-alphabetical order. (Sorting *ascending* here — which is\n * what this method used to do after a `.reverse()` — silently restored the\n * forward `up` order and made the reverse dead code.)\n */\n private async getMigrationsToRollback(\n batches: number,\n options: { pruneMissing?: boolean; readOnly?: boolean } = {},\n ): Promise<MigrationClass[]> {\n const migrations: MigrationClass[] = [];\n const batchOf = new Map<MigrationClass, number>();\n const orphans: Array<{ name: string; dataSource: DataSource }> = [];\n\n // Batches are numbered per data source (each has its own migrations table).\n for (const dataSource of this.getSources()) {\n const executed = await this.getExecutedMigrations(dataSource, {\n readOnly: options.readOnly,\n });\n if (executed.length === 0) continue;\n\n const batchNumbers = [...new Set(executed.map((r) => r.batch))]\n .sort((a, b) => b - a)\n .slice(0, batches);\n\n for (const record of executed) {\n if (!batchNumbers.includes(record.batch)) continue;\n\n const MigrationClass = this.migrations.find(\n (m) => m.migrationName === record.name && this.sourceOf(m) === dataSource,\n );\n if (MigrationClass) {\n migrations.push(MigrationClass);\n batchOf.set(MigrationClass, record.batch);\n } else {\n orphans.push({ name: record.name, dataSource });\n }\n }\n }\n\n if (orphans.length > 0) {\n if (!options.pruneMissing) {\n throw new Error(\n `Cannot roll back: ${orphans.length} executed migration(s) have no registered file: ` +\n `${orphans.map((o) => o.name).join(\", \")}. ` +\n `They were renamed, deleted, or not matched by the migration pattern. ` +\n `Restore the file(s), or pass pruneMissing (--prune-missing) to delete those records.`,\n );\n }\n\n if (!options.readOnly) {\n for (const orphan of orphans) {\n await this.removeMigrationRecord(orphan.name, orphan.dataSource);\n log.warn(\"database\", \"migration\", `Pruned orphaned migration record: ${orphan.name}`);\n }\n }\n }\n\n // Newest batch first, then newest migration first within a batch.\n return migrations.sort(\n (a, b) => (batchOf.get(b) ?? 0) - (batchOf.get(a) ?? 0) || sortMigrationsForRollback(a, b),\n );\n }\n\n /**\n * Get executed migration records.\n */\n public async getExecutedMigrations(\n dataSource: DataSource = this.getDataSource(),\n options: { readOnly?: boolean } = {},\n ): Promise<MigrationRecord[]> {\n const driver = dataSource.driver;\n const migrationDriver = this.getMigrationDriver(dataSource);\n\n if (options.readOnly) {\n // Dry runs and listings must not create the migrations table.\n if (!(await migrationDriver.tableExists(this.migrationsTable))) return [];\n } else {\n // A missing table is created here; every other error (connection,\n // permission…) propagates instead of looking like \"nothing executed\".\n await migrationDriver.ensureMigrationsTable(this.migrationsTable);\n }\n\n const queryBuilder = driver.queryBuilder<MigrationRecord>(this.migrationsTable);\n const records = await queryBuilder.orderBy(\"batch\", \"asc\").orderBy(\"name\", \"asc\").get();\n\n // The Mongo lock document lives in this collection; it is not a migration.\n return records.filter((record) => record.name !== MIGRATION_LOCK_NAME);\n }\n\n /**\n * Record a migration.\n */\n private async recordMigration(\n name: string,\n batch: number,\n createdAt?: Date,\n dataSource: DataSource = this.getDataSource(),\n ): Promise<void> {\n const driver = dataSource.driver;\n const migrationDriver = this.getMigrationDriver(dataSource);\n\n // Ensure migrations table exists\n await migrationDriver.ensureMigrationsTable(this.migrationsTable);\n\n await driver.insert(this.migrationsTable, {\n name,\n batch,\n executedAt: new Date(),\n createdAt,\n });\n }\n\n /**\n * Remove a migration record.\n */\n private async removeMigrationRecord(\n name: string,\n dataSource: DataSource = this.getDataSource(),\n ): Promise<void> {\n const driver = dataSource.driver;\n await driver.delete(this.migrationsTable, { name });\n }\n\n /**\n * Get next batch number.\n */\n private async getNextBatchNumber(\n dataSource: DataSource = this.getDataSource(),\n readOnly = false,\n ): Promise<number> {\n const executed = await this.getExecutedMigrations(dataSource, { readOnly });\n if (executed.length === 0) return 1;\n return Math.max(...executed.map((r) => r.batch)) + 1;\n }\n}\n\nexport const migrationRunner = new MigrationRunner();\n"],"mappings":";;;;;;;;;;;AAqFA,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;AAC3B,MAAM,wBAAwB;AAC9B,MAAM,yBAAyB;AAC/B,MAAM,0BAA0B;AAsBhC,MAAM,SAAS,OAAe,IAAI,SAAe,YAAY,WAAW,SAAS,EAAE,CAAC;;;;;;AAOpF,SAAgB,mBAA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