viborm 1.16.0 → 1.17.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 (403) hide show
  1. package/dist/adapter-internals-Dz2nNEF5.mjs +2 -0
  2. package/dist/adapter-internals-Dz2nNEF5.mjs.map +1 -0
  3. package/dist/adapter-namespace-C1SUkH2U.mjs +2 -0
  4. package/dist/{adapter-namespace-DwFnfpED.mjs.map → adapter-namespace-C1SUkH2U.mjs.map} +1 -1
  5. package/dist/adapters.d.mts +50 -94
  6. package/dist/adapters.mjs +1 -1
  7. package/dist/{args-7WgBFd_f.mjs → args-DsGRkPRw.mjs} +2 -2
  8. package/dist/{args-7WgBFd_f.mjs.map → args-DsGRkPRw.mjs.map} +1 -1
  9. package/dist/{array-literal-BOzj0E2u.mjs → array-literal-U6SeastY.mjs} +1 -1
  10. package/dist/{array-literal-BOzj0E2u.mjs.map → array-literal-U6SeastY.mjs.map} +1 -1
  11. package/dist/auto-names-GpcDfhaw.mjs +2 -0
  12. package/dist/auto-names-GpcDfhaw.mjs.map +1 -0
  13. package/dist/batch-refs-BuICt2tu.mjs +2 -0
  14. package/dist/{batch-refs-Bd8HvwUc.mjs.map → batch-refs-BuICt2tu.mjs.map} +1 -1
  15. package/dist/better-auth.d.mts +1 -1
  16. package/dist/better-auth.mjs +2 -2
  17. package/dist/bun-sql.d.mts +1 -1
  18. package/dist/bun-sql.mjs +1 -1
  19. package/dist/bun-sqlite.d.mts +1 -1
  20. package/dist/bun-sqlite.mjs +1 -1
  21. package/dist/cache/cloudflare-kv.d.mts +1 -1
  22. package/dist/cache/cloudflare-kv.mjs +1 -1
  23. package/dist/cache/memory.d.mts +1 -1
  24. package/dist/cache/memory.mjs +1 -1
  25. package/dist/cache.d.mts +2 -2
  26. package/dist/cache.mjs +1 -1
  27. package/dist/call-D2E7dPCd.mjs +2 -0
  28. package/dist/{call-0bd_B9Vp.mjs.map → call-D2E7dPCd.mjs.map} +1 -1
  29. package/dist/cli.mjs +6 -6
  30. package/dist/cli.mjs.map +1 -1
  31. package/dist/client-Cq_VcF43.d.mts +183 -0
  32. package/dist/client-DkNRAOuH.mjs +2 -0
  33. package/dist/client-DkNRAOuH.mjs.map +1 -0
  34. package/dist/{planner-C-zjj19U.d.mts → client-driver-DuQy6lsN.d.mts} +3 -3
  35. package/dist/client-rIiFOn1W.mjs +9 -0
  36. package/dist/client-rIiFOn1W.mjs.map +1 -0
  37. package/dist/client.d.mts +2 -2
  38. package/dist/client.mjs +1 -1
  39. package/dist/config.d.mts +2 -2
  40. package/dist/config.mjs +1 -1
  41. package/dist/{confine-CyI9IwjC.mjs → confine-FIfjlAHp.mjs} +2 -2
  42. package/dist/{confine-CyI9IwjC.mjs.map → confine-FIfjlAHp.mjs.map} +1 -1
  43. package/dist/{object-store-C4qmW7xf.d.mts → conformance-C1JveA8y.d.mts} +5 -60
  44. package/dist/conformance-C4JYA0JG.mjs +2 -0
  45. package/dist/conformance-C4JYA0JG.mjs.map +1 -0
  46. package/dist/contract-BBone8RD.mjs +2 -0
  47. package/dist/contract-BBone8RD.mjs.map +1 -0
  48. package/dist/coordination-BxMskOgi.mjs +1 -1
  49. package/dist/d1.d.mts +1 -1
  50. package/dist/d1.mjs +1 -1
  51. package/dist/{database-adapter-BMjJiBFm.d.mts → database-adapter-cW0nmWM6.d.mts} +1 -1
  52. package/dist/datetime-physical-codec-Ci0dyOot.mjs +2 -0
  53. package/dist/datetime-physical-codec-Ci0dyOot.mjs.map +1 -0
  54. package/dist/datetime-values-D_G6m5_o.mjs +2 -0
  55. package/dist/datetime-values-D_G6m5_o.mjs.map +1 -0
  56. package/dist/decimal-D4DRlT2y.mjs +2 -0
  57. package/dist/decimal-D4DRlT2y.mjs.map +1 -0
  58. package/dist/{defaults-DAPb-tJ4.mjs → defaults-BrXUK350.mjs} +2 -2
  59. package/dist/{defaults-DAPb-tJ4.mjs.map → defaults-BrXUK350.mjs.map} +1 -1
  60. package/dist/{document-CHaVF7Vn.d.mts → document-B8ClXlb7.d.mts} +1 -1
  61. package/dist/{driver-kiIQS_Fd.mjs → driver-BOsmU3kz.mjs} +2 -2
  62. package/dist/{driver-kiIQS_Fd.mjs.map → driver-BOsmU3kz.mjs.map} +1 -1
  63. package/dist/{driver-BvTixv-m.d.mts → driver-KgGMnfz8.d.mts} +1 -1
  64. package/dist/{driver-lShUkDmf.mjs → driver-PkP_1p80.mjs} +2 -2
  65. package/dist/{driver-lShUkDmf.mjs.map → driver-PkP_1p80.mjs.map} +1 -1
  66. package/dist/{driver-diagnostics-aQ54bArn.mjs → driver-diagnostics-sSpge6kv.mjs} +1 -1
  67. package/dist/{driver-diagnostics-aQ54bArn.mjs.map → driver-diagnostics-sSpge6kv.mjs.map} +1 -1
  68. package/dist/driver.d.mts +1 -1
  69. package/dist/driver.mjs +1 -1
  70. package/dist/durable-object.d.mts +1 -1
  71. package/dist/durable-object.mjs +2 -2
  72. package/dist/error-mapping-B9rSvgG9.mjs +1 -1
  73. package/dist/every-tAZuZ50K.mjs +2 -0
  74. package/dist/{every-JpbiHdMb.mjs.map → every-tAZuZ50K.mjs.map} +1 -1
  75. package/dist/execution-context-couU2tgh.mjs +1 -1
  76. package/dist/{exports-DYnTfvQo.d.mts → exports-reE3GioL.d.mts} +1 -1
  77. package/dist/extension-Bf4vO5mp.mjs +2 -0
  78. package/dist/extension-Bf4vO5mp.mjs.map +1 -0
  79. package/dist/facts-Bjnzv3j-.mjs +2 -0
  80. package/dist/facts-Bjnzv3j-.mjs.map +1 -0
  81. package/dist/{fs-estate-n-QpsFqb.mjs → fs-estate-C3ahNKmi.mjs} +2 -2
  82. package/dist/{fs-estate-n-QpsFqb.mjs.map → fs-estate-C3ahNKmi.mjs.map} +1 -1
  83. package/dist/geo-area-codec-CBdiCOzj.mjs +2 -0
  84. package/dist/{geo-area-codec-Bti2PA2i.mjs.map → geo-area-codec-CBdiCOzj.mjs.map} +1 -1
  85. package/dist/geo-point-DCV0eO1p.mjs +2 -0
  86. package/dist/geo-point-DCV0eO1p.mjs.map +1 -0
  87. package/dist/id-domain-Cj6MnMxg.mjs +2 -0
  88. package/dist/{id-domain-Cg65TLZ-.mjs.map → id-domain-Cj6MnMxg.mjs.map} +1 -1
  89. package/dist/identifier-BdLx66pi.mjs +2 -0
  90. package/dist/identifier-BdLx66pi.mjs.map +1 -0
  91. package/dist/identifier-conversion-CMKVatU4.mjs +3 -0
  92. package/dist/identifier-conversion-CMKVatU4.mjs.map +1 -0
  93. package/dist/{identifiers-BxOf57qy.mjs → identifiers-BAZ_S6Lk.mjs} +1 -1
  94. package/dist/{identifiers-BxOf57qy.mjs.map → identifiers-BAZ_S6Lk.mjs.map} +1 -1
  95. package/dist/{identity-CJlRQA-m.mjs → identity-nPArhpsD.mjs} +2 -2
  96. package/dist/{identity-CJlRQA-m.mjs.map → identity-nPArhpsD.mjs.map} +1 -1
  97. package/dist/index.d.mts +2 -2
  98. package/dist/index.mjs +1 -1
  99. package/dist/index.mjs.map +1 -1
  100. package/dist/instrumentation.d.mts +1 -1
  101. package/dist/instrumentation.mjs +1 -1
  102. package/dist/introspect-dyBpdr2L.mjs +2 -0
  103. package/dist/{introspect-q3Rf_Xv8.mjs.map → introspect-dyBpdr2L.mjs.map} +1 -1
  104. package/dist/json-DvvrTWUw.mjs +2 -0
  105. package/dist/{json-CsAdz9pg.mjs.map → json-DvvrTWUw.mjs.map} +1 -1
  106. package/dist/{json-number-C09rsm1g.mjs → json-number-Guh-5rff.mjs} +1 -1
  107. package/dist/{json-number-C09rsm1g.mjs.map → json-number-Guh-5rff.mjs.map} +1 -1
  108. package/dist/{json-parameter-D7hDrVKw.mjs → json-parameter-DtHhEfyE.mjs} +1 -1
  109. package/dist/{json-parameter-D7hDrVKw.mjs.map → json-parameter-DtHhEfyE.mjs.map} +1 -1
  110. package/dist/judge-words-CqNdnbou.mjs +2 -0
  111. package/dist/judge-words-CqNdnbou.mjs.map +1 -0
  112. package/dist/{key-BDH6oTyC.mjs → key-v4k7Cqb6.mjs} +2 -2
  113. package/dist/{key-BDH6oTyC.mjs.map → key-v4k7Cqb6.mjs.map} +1 -1
  114. package/dist/{keys-CIal55WQ.mjs → keys-BLWaO_YM.mjs} +1 -1
  115. package/dist/{keys-CIal55WQ.mjs.map → keys-BLWaO_YM.mjs.map} +1 -1
  116. package/dist/keys-o4Pl6Vsg.mjs +2 -0
  117. package/dist/{keys-DZdKAd4n.mjs.map → keys-o4Pl6Vsg.mjs.map} +1 -1
  118. package/dist/libsql-C0iMZifz.mjs +3 -0
  119. package/dist/libsql-C0iMZifz.mjs.map +1 -0
  120. package/dist/libsql.d.mts +1 -1
  121. package/dist/libsql.mjs +1 -1
  122. package/dist/light-reLULeHN.mjs +2 -0
  123. package/dist/{light-D2wNSbzY.mjs.map → light-reLULeHN.mjs.map} +1 -1
  124. package/dist/memory-DtTuFo-h.mjs +2 -0
  125. package/dist/memory-DtTuFo-h.mjs.map +1 -0
  126. package/dist/methods-part-Dsi0DBNU.mjs +2 -0
  127. package/dist/{methods-part-BaNx3o7b.mjs.map → methods-part-Dsi0DBNU.mjs.map} +1 -1
  128. package/dist/migrations/mysql/runtime.d.mts +7 -0
  129. package/dist/migrations/mysql/runtime.mjs +2 -0
  130. package/dist/migrations/mysql/runtime.mjs.map +1 -0
  131. package/dist/migrations/mysql.d.mts +7 -5
  132. package/dist/migrations/mysql.mjs +1 -1
  133. package/dist/migrations/mysql.mjs.map +1 -1
  134. package/dist/migrations/postgres/runtime.d.mts +7 -0
  135. package/dist/migrations/postgres/runtime.mjs +2 -0
  136. package/dist/migrations/postgres/runtime.mjs.map +1 -0
  137. package/dist/migrations/postgres.d.mts +7 -5
  138. package/dist/migrations/postgres.mjs +1 -1
  139. package/dist/migrations/postgres.mjs.map +1 -1
  140. package/dist/migrations/snowflake.d.mts +7 -5
  141. package/dist/migrations/snowflake.mjs +1 -1
  142. package/dist/migrations/snowflake.mjs.map +1 -1
  143. package/dist/migrations/sqlite/runtime.d.mts +7 -0
  144. package/dist/migrations/sqlite/runtime.mjs +2 -0
  145. package/dist/migrations/sqlite/runtime.mjs.map +1 -0
  146. package/dist/migrations/sqlite.d.mts +7 -5
  147. package/dist/migrations/sqlite.mjs +1 -1
  148. package/dist/migrations/sqlite.mjs.map +1 -1
  149. package/dist/migrations/storage/durable-object.d.mts +1 -1
  150. package/dist/migrations/storage/durable-object.mjs +1 -1
  151. package/dist/migrations/storage/fs.d.mts +1 -1
  152. package/dist/migrations/storage/fs.mjs +1 -1
  153. package/dist/migrations/storage/r2.d.mts +1 -1
  154. package/dist/migrations/storage/r2.mjs +1 -1
  155. package/dist/migrations/surrealdb.d.mts +7 -5
  156. package/dist/migrations/surrealdb.mjs +1 -1
  157. package/dist/migrations/surrealdb.mjs.map +1 -1
  158. package/dist/migrations/tenant.d.mts +4 -3
  159. package/dist/migrations/tenant.mjs +1 -1
  160. package/dist/migrations/tenant.mjs.map +1 -1
  161. package/dist/migrations.d.mts +7 -5
  162. package/dist/migrations.mjs +1 -1
  163. package/dist/migrations.mjs.map +1 -1
  164. package/dist/model-ByktcCGW.mjs +2 -0
  165. package/dist/model-ByktcCGW.mjs.map +1 -0
  166. package/dist/mysql-DPYi1p_g.mjs +4 -0
  167. package/dist/mysql-DPYi1p_g.mjs.map +1 -0
  168. package/dist/mysql-adapter-6gVm5PHp.mjs +2 -0
  169. package/dist/{mysql-adapter-BFWYPoM0.mjs.map → mysql-adapter-6gVm5PHp.mjs.map} +1 -1
  170. package/dist/mysql2.d.mts +1 -1
  171. package/dist/mysql2.mjs +1 -1
  172. package/dist/{named-statements-CkOOD__I.mjs → named-statements-CswIc5m1.mjs} +2 -2
  173. package/dist/{named-statements-CkOOD__I.mjs.map → named-statements-CswIc5m1.mjs.map} +1 -1
  174. package/dist/native-types-BUkcVedc.mjs +2 -0
  175. package/dist/native-types-BUkcVedc.mjs.map +1 -0
  176. package/dist/neon-http.d.mts +1 -1
  177. package/dist/neon-http.mjs +1 -1
  178. package/dist/normalized-result-D7nVkF36.mjs +1 -1
  179. package/dist/{object-store-Chq1PMYz.mjs → object-store-DnrLNxz_.mjs} +2 -2
  180. package/dist/{object-store-Chq1PMYz.mjs.map → object-store-DnrLNxz_.mjs.map} +1 -1
  181. package/dist/object-store-j4kgh61D.d.mts +59 -0
  182. package/dist/{on-ZkOVmE4-.mjs → on-nOenqmgP.mjs} +2 -2
  183. package/dist/{on-ZkOVmE4-.mjs.map → on-nOenqmgP.mjs.map} +1 -1
  184. package/dist/on.d.mts +1 -1
  185. package/dist/on.mjs +1 -1
  186. package/dist/ordering/keys.mjs +1 -1
  187. package/dist/ordering.d.mts +1 -1
  188. package/dist/ordering.mjs +2 -2
  189. package/dist/pending-operation-B5o-zhES.mjs +2 -0
  190. package/dist/{pending-operation-D4gUKMxD.mjs.map → pending-operation-B5o-zhES.mjs.map} +1 -1
  191. package/dist/permissions.d.mts +1 -1
  192. package/dist/permissions.mjs +1 -1
  193. package/dist/pg.d.mts +2 -2
  194. package/dist/pg.mjs +1 -1
  195. package/dist/pglite.d.mts +1 -1
  196. package/dist/pglite.mjs +1 -1
  197. package/dist/{physical-DO4PEYcc.mjs → physical-BheMRPY0.mjs} +2 -2
  198. package/dist/{physical-DO4PEYcc.mjs.map → physical-BheMRPY0.mjs.map} +1 -1
  199. package/dist/{pinned-session-Y7-2pRBJ.mjs → pinned-session-eNyd0dkT.mjs} +2 -2
  200. package/dist/{pinned-session-Y7-2pRBJ.mjs.map → pinned-session-eNyd0dkT.mjs.map} +1 -1
  201. package/dist/planetscale.d.mts +1 -1
  202. package/dist/planetscale.mjs +1 -1
  203. package/dist/postgres-CEGFOi8D.mjs +27 -0
  204. package/dist/postgres-CEGFOi8D.mjs.map +1 -0
  205. package/dist/postgres-adapter-B-im38AE.mjs +2 -0
  206. package/dist/postgres-adapter-B-im38AE.mjs.map +1 -0
  207. package/dist/{postgres-adapter-BpLizOaK.mjs → postgres-adapter-OoqoBdhb.mjs} +2 -2
  208. package/dist/{postgres-adapter-BpLizOaK.mjs.map → postgres-adapter-OoqoBdhb.mjs.map} +1 -1
  209. package/dist/{postgres-result-133boRW-.mjs → postgres-result-D-bqmofR.mjs} +1 -1
  210. package/dist/{postgres-result-133boRW-.mjs.map → postgres-result-D-bqmofR.mjs.map} +1 -1
  211. package/dist/postgres.d.mts +2 -2
  212. package/dist/postgres.mjs +1 -1
  213. package/dist/provider-limits-DvcCUw7l.mjs +2 -0
  214. package/dist/provider-limits-DvcCUw7l.mjs.map +1 -0
  215. package/dist/{provider-parameter-snapshot-cyTUDutH.mjs → provider-parameter-snapshot-DnJ6Av9y.mjs} +2 -2
  216. package/dist/{provider-parameter-snapshot-cyTUDutH.mjs.map → provider-parameter-snapshot-DnJ6Av9y.mjs.map} +1 -1
  217. package/dist/push-fingerprint-CegYVFFp.mjs +18 -0
  218. package/dist/push-fingerprint-CegYVFFp.mjs.map +1 -0
  219. package/dist/{quantized-BKBs0joq.mjs → quantized-DLD2cd6q.mjs} +1 -1
  220. package/dist/{quantized-BKBs0joq.mjs.map → quantized-DLD2cd6q.mjs.map} +1 -1
  221. package/dist/query-DSEMPA7r.mjs +2 -0
  222. package/dist/query-DSEMPA7r.mjs.map +1 -0
  223. package/dist/query-backend-CzwVfrQ6.mjs +2 -0
  224. package/dist/{query-backend-TisPjCPF.mjs.map → query-backend-CzwVfrQ6.mjs.map} +1 -1
  225. package/dist/{query-inspection-DwYBKSDG.mjs → query-inspection-CvtTL5Fs.mjs} +2 -2
  226. package/dist/{query-inspection-DwYBKSDG.mjs.map → query-inspection-CvtTL5Fs.mjs.map} +1 -1
  227. package/dist/raw-B8cNef_V.mjs +2 -0
  228. package/dist/{raw-DqEb71JZ.mjs.map → raw-B8cNef_V.mjs.map} +1 -1
  229. package/dist/{relation-bound-CSNKLyDy.mjs → relation-bound-DHP5cpTE.mjs} +1 -1
  230. package/dist/{relation-bound-CSNKLyDy.mjs.map → relation-bound-DHP5cpTE.mjs.map} +1 -1
  231. package/dist/{result-parsing-BbffueEX.mjs → result-parsing-DfwBAXY2.mjs} +1 -1
  232. package/dist/{result-parsing-BbffueEX.mjs.map → result-parsing-DfwBAXY2.mjs.map} +1 -1
  233. package/dist/{rows-of-Bgl9GVtK.mjs → rows-of-UeSasWGq.mjs} +2 -2
  234. package/dist/{rows-of-Bgl9GVtK.mjs.map → rows-of-UeSasWGq.mjs.map} +1 -1
  235. package/dist/rule-words-ojG0-vSf.mjs +2 -0
  236. package/dist/{rule-words-DMbQuvD2.mjs.map → rule-words-ojG0-vSf.mjs.map} +1 -1
  237. package/dist/runtime-BAqlANG_.mjs +10 -0
  238. package/dist/runtime-BAqlANG_.mjs.map +1 -0
  239. package/dist/runtime-D0oaIS1E.mjs +2 -0
  240. package/dist/runtime-D0oaIS1E.mjs.map +1 -0
  241. package/dist/runtime-Dfkv59_p.mjs +15 -0
  242. package/dist/runtime-Dfkv59_p.mjs.map +1 -0
  243. package/dist/runtime-client-CvGGOOFd.d.mts +38 -0
  244. package/dist/runtime-client-xeiXA_1m.mjs +2 -0
  245. package/dist/runtime-client-xeiXA_1m.mjs.map +1 -0
  246. package/dist/scalar-BTYxpiP_.mjs +4 -0
  247. package/dist/scalar-BTYxpiP_.mjs.map +1 -0
  248. package/dist/schema/introspect.d.mts +2 -2
  249. package/dist/schema/introspect.mjs +1 -1
  250. package/dist/schema/json.d.mts +2 -2
  251. package/dist/schema/json.mjs +1 -1
  252. package/dist/schema-BzkBJTF-.mjs +2 -0
  253. package/dist/{schema-DDkAUfOb.mjs.map → schema-BzkBJTF-.mjs.map} +1 -1
  254. package/dist/schema-D7MyYTjA.mjs +2 -0
  255. package/dist/{schema-DqR_Kcje.mjs.map → schema-D7MyYTjA.mjs.map} +1 -1
  256. package/dist/{schema-introspection-Bbo4DN_d.mjs → schema-introspection-b4xPGPfu.mjs} +4 -4
  257. package/dist/{schema-introspection-Bbo4DN_d.mjs.map → schema-introspection-b4xPGPfu.mjs.map} +1 -1
  258. package/dist/schema.d.mts +1 -1
  259. package/dist/schema.mjs +1 -1
  260. package/dist/{select-assembly-CEpNu-Gw.mjs → select-assembly-B01JtBRm.mjs} +2 -2
  261. package/dist/{select-assembly-CEpNu-Gw.mjs.map → select-assembly-B01JtBRm.mjs.map} +1 -1
  262. package/dist/serializer-CIhcZMxs.mjs +7 -0
  263. package/dist/serializer-CIhcZMxs.mjs.map +1 -0
  264. package/dist/{settle-Pui-1tfJ.mjs → settle-CIbvnLED.mjs} +1 -1
  265. package/dist/{settle-Pui-1tfJ.mjs.map → settle-CIbvnLED.mjs.map} +1 -1
  266. package/dist/{settled-DYYPcaBX.mjs → settled-Clanz_kI.mjs} +2 -2
  267. package/dist/{settled-DYYPcaBX.mjs.map → settled-Clanz_kI.mjs.map} +1 -1
  268. package/dist/snowflake-C1dqbche.mjs +2 -0
  269. package/dist/{snowflake-BfF8xwfP.mjs.map → snowflake-C1dqbche.mjs.map} +1 -1
  270. package/dist/snowflake.d.mts +2 -2
  271. package/dist/snowflake.mjs +2 -2
  272. package/dist/snowflake.mjs.map +1 -1
  273. package/dist/soft-delete.d.mts +1 -1
  274. package/dist/soft-delete.mjs +1 -1
  275. package/dist/{spans-DwDXMvyd.mjs → spans-CVl3RKUR.mjs} +1 -1
  276. package/dist/{spans-DwDXMvyd.mjs.map → spans-CVl3RKUR.mjs.map} +1 -1
  277. package/dist/sql-AHN2niBz.mjs +2 -0
  278. package/dist/{sql-Bu63iAfT.mjs.map → sql-AHN2niBz.mjs.map} +1 -1
  279. package/dist/sql-control-Cdp0_Mwy.mjs +2 -0
  280. package/dist/sql-control-Cdp0_Mwy.mjs.map +1 -0
  281. package/dist/{sql-statement-tokens-Z5Ta4iDB.mjs → sql-statement-tokens-BdVJnUQY.mjs} +2 -2
  282. package/dist/{sql-statement-tokens-Z5Ta4iDB.mjs.map → sql-statement-tokens-BdVJnUQY.mjs.map} +1 -1
  283. package/dist/sql-tegqTqGq.mjs +1 -1
  284. package/dist/sql.d.mts +1 -1
  285. package/dist/sqlite-adapter-B7r7w3CS.mjs +2 -0
  286. package/dist/sqlite-adapter-B7r7w3CS.mjs.map +1 -0
  287. package/dist/{sqlite-statement-classifier-JBHiQO6Q.mjs → sqlite-statement-classifier-CBmKy8Ta.mjs} +2 -2
  288. package/dist/{sqlite-statement-classifier-JBHiQO6Q.mjs.map → sqlite-statement-classifier-CBmKy8Ta.mjs.map} +1 -1
  289. package/dist/sqlite-storage-audit-D8nA9ylL.mjs +2 -0
  290. package/dist/sqlite-storage-audit-D8nA9ylL.mjs.map +1 -0
  291. package/dist/{sqlite-utils-Bfmtkt1b.mjs → sqlite-utils-BAUMCrok.mjs} +2 -2
  292. package/dist/{sqlite-utils-Bfmtkt1b.mjs.map → sqlite-utils-BAUMCrok.mjs.map} +1 -1
  293. package/dist/sqlite3.d.mts +1 -1
  294. package/dist/sqlite3.mjs +1 -1
  295. package/dist/{standard-sql-Bl2OHGfi.mjs → standard-sql-tpcKlArE.mjs} +2 -2
  296. package/dist/{standard-sql-Bl2OHGfi.mjs.map → standard-sql-tpcKlArE.mjs.map} +1 -1
  297. package/dist/surrealdb.d.mts +2 -2
  298. package/dist/surrealdb.mjs +1 -1
  299. package/dist/surrealdb.mjs.map +1 -1
  300. package/dist/surrealql-AyDLKSEQ.mjs +2 -0
  301. package/dist/surrealql-AyDLKSEQ.mjs.map +1 -0
  302. package/dist/time-step-BIdl2Iy7.mjs +2 -0
  303. package/dist/time-step-BIdl2Iy7.mjs.map +1 -0
  304. package/dist/transaction-operation-CaWzo7gE.mjs +1 -1
  305. package/dist/type-mapping-BYre7JQ1.mjs +3 -0
  306. package/dist/type-mapping-BYre7JQ1.mjs.map +1 -0
  307. package/dist/{types-Dy33vBdd.mjs → types-M-IdB4Mo.mjs} +1 -1
  308. package/dist/{types-Dy33vBdd.mjs.map → types-M-IdB4Mo.mjs.map} +1 -1
  309. package/dist/{unit-DUPX5Sdd.mjs → unit-Dnp2HIWg.mjs} +2 -2
  310. package/dist/{unit-DUPX5Sdd.mjs.map → unit-Dnp2HIWg.mjs.map} +1 -1
  311. package/dist/{unit-words-BXpLpyr2.mjs → unit-words-DjVhRXAQ.mjs} +2 -2
  312. package/dist/{unit-words-BXpLpyr2.mjs.map → unit-words-DjVhRXAQ.mjs.map} +1 -1
  313. package/dist/{utils-BHkJsduV.mjs → utils-BB_4NZQC.mjs} +2 -2
  314. package/dist/{utils-BHkJsduV.mjs.map → utils-BB_4NZQC.mjs.map} +1 -1
  315. package/dist/utils-DYrxwV_M.mjs +2 -0
  316. package/dist/utils-DYrxwV_M.mjs.map +1 -0
  317. package/dist/{v1-parse-shared-cJ-uD14P.mjs → v1-parse-shared-CNiFHAJF.mjs} +1 -1
  318. package/dist/{v1-parse-shared-cJ-uD14P.mjs.map → v1-parse-shared-CNiFHAJF.mjs.map} +1 -1
  319. package/dist/validation-CEnhYqhl.mjs +2 -0
  320. package/dist/{validation-BHjx13zG.mjs.map → validation-CEnhYqhl.mjs.map} +1 -1
  321. package/dist/validation.d.mts +1 -1
  322. package/dist/validation.mjs +1 -1
  323. package/dist/validator-CISkL46K.mjs +2 -0
  324. package/dist/validator-CISkL46K.mjs.map +1 -0
  325. package/dist/{values-Ch2cTlss.mjs → values-D0k60ei0.mjs} +2 -2
  326. package/dist/{values-Ch2cTlss.mjs.map → values-D0k60ei0.mjs.map} +1 -1
  327. package/dist/{client-Dlz3-2JC.d.mts → verify-v1-CJFrJ4lx.d.mts} +10 -183
  328. package/dist/version-nEOMCWfV.mjs +2 -0
  329. package/dist/{version-0BDwfy7C.mjs.map → version-nEOMCWfV.mjs.map} +1 -1
  330. package/dist/view-CmLQ0I6x.mjs +2 -0
  331. package/dist/{view-CHgjF2BO.mjs.map → view-CmLQ0I6x.mjs.map} +1 -1
  332. package/dist/write-sinks-BhwgQn_5.mjs +2 -0
  333. package/dist/{write-sinks-Bei5vFHP.mjs.map → write-sinks-BhwgQn_5.mjs.map} +1 -1
  334. package/package.json +27 -2
  335. package/dist/adapter-namespace-DwFnfpED.mjs +0 -2
  336. package/dist/batch-refs-Bd8HvwUc.mjs +0 -2
  337. package/dist/call-0bd_B9Vp.mjs +0 -2
  338. package/dist/client-D7sWgUt2.mjs +0 -2
  339. package/dist/client-D7sWgUt2.mjs.map +0 -1
  340. package/dist/client-DEfFqv4S.mjs +0 -9
  341. package/dist/client-DEfFqv4S.mjs.map +0 -1
  342. package/dist/datetime-physical-codec-DAF7WJpy.mjs +0 -2
  343. package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +0 -1
  344. package/dist/every-JpbiHdMb.mjs +0 -2
  345. package/dist/extension-Dh1ddrlA.mjs +0 -2
  346. package/dist/extension-Dh1ddrlA.mjs.map +0 -1
  347. package/dist/geo-area-codec-Bti2PA2i.mjs +0 -2
  348. package/dist/id-domain-Cg65TLZ-.mjs +0 -2
  349. package/dist/identifier-conversion-BTDxDwDB.mjs +0 -2
  350. package/dist/identifier-conversion-BTDxDwDB.mjs.map +0 -1
  351. package/dist/introspect-q3Rf_Xv8.mjs +0 -2
  352. package/dist/json-CsAdz9pg.mjs +0 -2
  353. package/dist/judge-words-k5GCc4cV.mjs +0 -2
  354. package/dist/judge-words-k5GCc4cV.mjs.map +0 -1
  355. package/dist/keys-DZdKAd4n.mjs +0 -2
  356. package/dist/libsql-DEZ0uhK2.mjs +0 -3
  357. package/dist/libsql-DEZ0uhK2.mjs.map +0 -1
  358. package/dist/light-D2wNSbzY.mjs +0 -2
  359. package/dist/memory-BaGWNdvk.mjs +0 -2
  360. package/dist/memory-BaGWNdvk.mjs.map +0 -1
  361. package/dist/methods-part-BaNx3o7b.mjs +0 -2
  362. package/dist/model-Dtd37Sky.mjs +0 -2
  363. package/dist/model-Dtd37Sky.mjs.map +0 -1
  364. package/dist/mysql-BFPF8xyv.mjs +0 -9
  365. package/dist/mysql-BFPF8xyv.mjs.map +0 -1
  366. package/dist/mysql-adapter-BFWYPoM0.mjs +0 -2
  367. package/dist/native-types-1ewJXVks.mjs +0 -2
  368. package/dist/native-types-1ewJXVks.mjs.map +0 -1
  369. package/dist/pending-operation-D4gUKMxD.mjs +0 -2
  370. package/dist/postgres-DQQE2ys_.mjs +0 -34
  371. package/dist/postgres-DQQE2ys_.mjs.map +0 -1
  372. package/dist/postgres-adapter-psTVfuw7.mjs +0 -2
  373. package/dist/postgres-adapter-psTVfuw7.mjs.map +0 -1
  374. package/dist/provider-limits-Bcsz0EJv.mjs +0 -2
  375. package/dist/provider-limits-Bcsz0EJv.mjs.map +0 -1
  376. package/dist/query-BTb6iakn.mjs +0 -2
  377. package/dist/query-BTb6iakn.mjs.map +0 -1
  378. package/dist/query-backend-TisPjCPF.mjs +0 -2
  379. package/dist/raw-DqEb71JZ.mjs +0 -2
  380. package/dist/rule-words-DMbQuvD2.mjs +0 -2
  381. package/dist/scalar-Dm9brvAU.mjs +0 -4
  382. package/dist/scalar-Dm9brvAU.mjs.map +0 -1
  383. package/dist/schema-DDkAUfOb.mjs +0 -2
  384. package/dist/schema-DqR_Kcje.mjs +0 -2
  385. package/dist/serializer-ettLu5xG.mjs +0 -33
  386. package/dist/serializer-ettLu5xG.mjs.map +0 -1
  387. package/dist/snowflake-BfF8xwfP.mjs +0 -2
  388. package/dist/sql-Bu63iAfT.mjs +0 -2
  389. package/dist/sqlite-adapter-Cb-SJw2f.mjs +0 -2
  390. package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +0 -1
  391. package/dist/surrealql-DY74AUeD.mjs +0 -2
  392. package/dist/surrealql-DY74AUeD.mjs.map +0 -1
  393. package/dist/time-step-DJaIhpAz.mjs +0 -2
  394. package/dist/time-step-DJaIhpAz.mjs.map +0 -1
  395. package/dist/validation-BHjx13zG.mjs +0 -2
  396. package/dist/validator-DMzH5Tz0.mjs +0 -2
  397. package/dist/validator-DMzH5Tz0.mjs.map +0 -1
  398. package/dist/version-0BDwfy7C.mjs +0 -2
  399. package/dist/view-CHgjF2BO.mjs +0 -2
  400. package/dist/write-sinks-Bei5vFHP.mjs +0 -2
  401. /package/dist/{contract-CxJn0_cV.d.mts → contract-CAoFgKSO.d.mts} +0 -0
  402. /package/dist/{named-statements-NF7Iycjk.d.mts → named-statements-CT4Gbd6t.d.mts} +0 -0
  403. /package/dist/{sql-C4_sFNDm.d.mts → sql-C-SBCGCx.d.mts} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-rIiFOn1W.mjs","names":["present","namespace"],"sources":["../src/migrations/check.ts","../src/migrations/catalog-probes.ts","../src/migrations/invert.ts","../src/migrations/compile.ts","../src/migrations/generate-input.ts","../src/migrations/public-view.ts","../src/migrations/push/format.ts","../src/migrations/push/planner.ts","../src/migrations/push-consent.ts","../src/migrations/live-reset.ts","../src/migrations/sql-assembly.ts","../src/migrations/push-plan.ts","../src/migrations/push-v1.ts","../src/migrations/generate-v1.ts","../src/migrations/down-input.ts","../src/migrations/reset-v1.ts","../src/migrations/operators.ts","../src/migrations/client.ts"],"sourcesContent":["/**\n * Offline estate check. CI-safe. Never creates control tables.\n */\n\nimport { loadMigrationGraph } from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport { resolveSnapshotArtifacts } from \"./snapshot-artifacts\";\nimport type { MigrationStorageReader } from \"./storage/contract\";\nimport { encodeSqlBlob, parseStateManifest } from \"./v1-parse\";\n\nexport interface CheckFinding {\n readonly code: string;\n readonly message: string;\n}\n\nexport interface CheckResult {\n readonly ok: boolean;\n readonly findings: readonly CheckFinding[];\n}\n\nexport async function checkEstate(\n storage: MigrationStorageReader\n): Promise<CheckResult> {\n const findings: CheckFinding[] = [];\n try {\n const graph = await loadMigrationGraph(storage);\n if (graph.leaves.length > 1) {\n findings.push({\n code: \"unresolved-branch\",\n message: `Estate has ${graph.leaves.length} leaves; apply requires an explicit target or via`,\n });\n }\n const referencedSnapshots = new Set<Sha256>([\n graph.emptySnapshotHash,\n ...graph.snapshotArtifacts.keys(),\n ]);\n const referencedSql = new Set<Sha256>();\n for (const state of graph.states.values()) {\n referencedSql.add(state.sqlHash);\n }\n const inventory = await storage.listSnapshots();\n await resolveSnapshotArtifacts(\n storage,\n inventory,\n new Map(graph.snapshotArtifacts)\n );\n for (const hash of inventory) {\n if (!referencedSnapshots.has(hash)) {\n findings.push({\n code: \"orphan-snapshot\",\n message: `Snapshot ${hash} is not referenced by any state`,\n });\n }\n }\n for (const hash of await storage.listSql()) {\n if (!referencedSql.has(hash)) {\n findings.push({\n code: \"orphan-sql\",\n message: `SQL blob ${hash} is not referenced by any state`,\n });\n }\n const bytes = await storage.readSql(hash);\n if (bytes && encodeSqlBlob(bytes) !== hash) {\n findings.push({\n code: \"corrupt-sql\",\n message: `SQL blob ${hash} does not match its bytes`,\n });\n }\n }\n for (const id of await storage.listStates()) {\n const bytes = await storage.readState(id);\n if (bytes) parseStateManifest(bytes, id);\n }\n } catch (error) {\n findings.push({\n code: \"invalid-estate\",\n message: error instanceof Error ? error.message : String(error),\n });\n }\n return {\n ok: findings.every((finding) => finding.code.startsWith(\"orphan-\")),\n findings,\n };\n}\n","import { renderQualifiedIdentifier } from \"../sql/identifiers\";\nimport {\n boundCatalogNamespace,\n type CatalogProbe,\n type CatalogProbeLifetime,\n driverNamespace as namespace,\n tableExistsProbe,\n} from \"./catalog-runtime\";\nimport type { MigrationDriver } from \"./drivers\";\nimport { RAW_INDEX_MARKER_PREFIX, rawIndexMarker } from \"./raw-index\";\nimport type {\n AutoViewObject,\n DiffOperation,\n ForeignKeyDef,\n IndexDef,\n} from \"./types\";\nimport type { MigrationParameterV1 } from \"./v1-types\";\n\nexport {\n boundNamespace,\n type CatalogProbe,\n type InvalidIndex,\n qualifiedName,\n readInvalidIndexes,\n tableExistsProbe,\n} from \"./catalog-runtime\";\n\nfunction stringParam(value: string): MigrationParameterV1 {\n return { kind: \"string\", value };\n}\n\nfunction mysqlNamespaceParam(\n driver: MigrationDriver,\n lifetime: CatalogProbeLifetime\n): MigrationParameterV1 {\n return lifetime === \"stored-artifact\"\n ? { kind: \"target-namespace\" }\n : stringParam(boundCatalogNamespace(driver));\n}\n\nconst PG_CLASS_NS =\n \"pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\";\nconst existsSql = (from: string, where: string) =>\n `SELECT EXISTS (SELECT 1 FROM ${from} WHERE ${where})`;\nconst strParams = (...values: string[]) => values.map(stringParam);\nconst pgParams = (driver: MigrationDriver, ...names: string[]) =>\n strParams(boundCatalogNamespace(driver), ...names);\nconst myParams = (\n driver: MigrationDriver,\n lifetime: CatalogProbeLifetime,\n ...names: string[]\n) => [mysqlNamespaceParam(driver, lifetime), ...strParams(...names)];\nconst sqliteMaster = (type: string) =>\n existsSql(\"sqlite_master\", `type = '${type}' AND name = ?`);\n\nconst existsProbe = (\n kind: string,\n name: string,\n exists: boolean,\n sql: string,\n parameters: readonly MigrationParameterV1[]\n): CatalogProbe => ({\n id: `${kind}:${exists ? \"exists\" : \"absent\"}:${name}`,\n sql,\n parameters,\n equals: exists,\n});\n\nconst probePair = (\n creating: boolean,\n make: (exists: boolean) => CatalogProbe\n): { pre: CatalogProbe; post: CatalogProbe } => ({\n pre: make(!creating),\n post: make(creating),\n});\n\nexport function viewExistsProbe(\n driver: MigrationDriver,\n viewName: string,\n exists: boolean,\n lifetime: CatalogProbeLifetime = \"live-command\",\n materialized = false\n): CatalogProbe {\n const kind = materialized ? \"materialized-view\" : \"view\";\n const d = driver.dialect;\n const [sql, params] =\n d === \"surrealql\"\n ? [\n \"RETURN [{ present: (INFO FOR DB STRUCTURE).tables.filter(|$t| $t.view != NONE).name CONTAINS $p1 }]\",\n strParams(viewName),\n ]\n : d === \"postgresql\"\n ? [\n existsSql(\n PG_CLASS_NS,\n `n.nspname = $1 AND c.relname = $2 AND c.relkind = '${materialized ? \"m\" : \"v\"}'`\n ),\n pgParams(driver, viewName),\n ]\n : d === \"mysql\"\n ? [\n existsSql(\n \"information_schema.views\",\n \"table_schema = ? AND table_name = ?\"\n ),\n myParams(driver, lifetime, viewName),\n ]\n : [sqliteMaster(\"view\"), strParams(viewName)];\n return existsProbe(kind, viewName, exists, sql, params);\n}\n\nexport function triggerExistsProbe(\n driver: MigrationDriver,\n table: string,\n triggerName: string,\n exists: boolean,\n lifetime: CatalogProbeLifetime = \"live-command\"\n): CatalogProbe {\n const d = driver.dialect;\n const [sql, params] =\n d === \"postgresql\"\n ? [\n existsSql(\n `pg_catalog.pg_trigger t JOIN ${PG_CLASS_NS} ON c.oid = t.tgrelid`,\n \"n.nspname = $1 AND c.relname = $2 AND t.tgname = $3\"\n ),\n pgParams(driver, table, triggerName),\n ]\n : d === \"mysql\"\n ? [\n existsSql(\n \"information_schema.triggers\",\n \"trigger_schema = ? AND trigger_name = ?\"\n ),\n myParams(driver, lifetime, triggerName),\n ]\n : [sqliteMaster(\"trigger\"), strParams(triggerName)];\n return existsProbe(\"trigger\", `${table}.${triggerName}`, exists, sql, params);\n}\n\nexport function columnExistsProbe(\n driver: MigrationDriver,\n tableName: string,\n columnName: string,\n exists: boolean,\n lifetime: CatalogProbeLifetime = \"live-command\"\n): CatalogProbe {\n const d = driver.dialect;\n const [sql, params] =\n d === \"postgresql\"\n ? [\n existsSql(\n `pg_catalog.pg_attribute a JOIN ${PG_CLASS_NS} ON c.oid = a.attrelid`,\n \"n.nspname = $1 AND c.relname = $2 AND a.attname = $3 AND a.attnum > 0 AND NOT a.attisdropped\"\n ),\n pgParams(driver, tableName, columnName),\n ]\n : d === \"mysql\"\n ? [\n existsSql(\n \"information_schema.columns\",\n \"table_schema = ? AND table_name = ? AND column_name = ?\"\n ),\n myParams(driver, lifetime, tableName, columnName),\n ]\n : [\n existsSql(\"pragma_table_info(?)\", \"name = ?\"),\n strParams(tableName, columnName),\n ];\n return existsProbe(\n \"column\",\n `${tableName}.${columnName}`,\n exists,\n sql,\n params\n );\n}\n\nexport function indexExistsProbe(\n driver: MigrationDriver,\n tableName: string,\n indexName: string,\n exists: boolean,\n lifetime: CatalogProbeLifetime = \"live-command\"\n): CatalogProbe {\n const d = driver.dialect;\n const [sql, params] =\n d === \"postgresql\"\n ? [\n existsSql(\n `${PG_CLASS_NS}${exists ? \" JOIN pg_catalog.pg_index x ON x.indexrelid = c.oid AND x.indisvalid\" : \"\"}`,\n \"n.nspname = $1 AND c.relname = $2 AND c.relkind = 'i'\"\n ),\n pgParams(driver, indexName),\n ]\n : d === \"mysql\"\n ? [\n existsSql(\n \"information_schema.statistics\",\n \"table_schema = ? AND table_name = ? AND index_name = ?\"\n ),\n myParams(driver, lifetime, tableName, indexName),\n ]\n : [sqliteMaster(\"index\"), strParams(indexName)];\n return existsProbe(\"index\", indexName, exists, sql, params);\n}\n\nexport function foreignKeyExistsProbe(\n driver: MigrationDriver,\n tableName: string,\n fkName: string,\n exists: boolean,\n lifetime: CatalogProbeLifetime = \"live-command\",\n validation?: \"validated\" | \"unvalidated\"\n): CatalogProbe {\n const d = driver.dialect;\n const suffix = validation ? `:${validation}` : \"\";\n const [sql, params] =\n d === \"postgresql\"\n ? [\n existsSql(\n `pg_catalog.pg_constraint con JOIN ${PG_CLASS_NS} ON c.oid = con.conrelid`,\n `n.nspname = $1 AND c.relname = $2 AND con.conname = $3 AND con.contype = 'f'${\n validation === \"validated\"\n ? \" AND con.convalidated\"\n : validation === \"unvalidated\"\n ? \" AND NOT con.convalidated\"\n : \"\"\n }`\n ),\n pgParams(driver, tableName, fkName),\n ]\n : [\n existsSql(\n \"information_schema.table_constraints\",\n \"table_schema = ? AND table_name = ? AND constraint_name = ? AND constraint_type = 'FOREIGN KEY'\"\n ),\n myParams(driver, lifetime, tableName, fkName),\n ];\n return existsProbe(\n `foreign-key${suffix}`,\n `${tableName}.${fkName}`,\n exists,\n sql,\n params\n );\n}\n\nexport function enumExistsProbe(\n driver: MigrationDriver,\n enumName: string,\n exists: boolean\n): CatalogProbe {\n return existsProbe(\n \"enum\",\n enumName,\n exists,\n existsSql(\n \"pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\",\n \"n.nspname = $1 AND t.typname = $2 AND t.typtype = 'e'\"\n ),\n pgParams(driver, enumName)\n );\n}\n\nexport function enumValueExistsProbe(\n driver: MigrationDriver,\n enumName: string,\n value: string,\n exists: boolean\n): CatalogProbe {\n return existsProbe(\n \"enum-value\",\n `${enumName}.${value}`,\n exists,\n existsSql(\n \"pg_catalog.pg_enum e JOIN pg_catalog.pg_type t ON t.oid = e.enumtypid JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\",\n \"n.nspname = $1 AND t.typname = $2 AND t.typtype = 'e' AND e.enumlabel = $3\"\n ),\n pgParams(driver, enumName, value)\n );\n}\n\nconst ADD_ENUM_VALUE = /\\bADD\\s+VALUE\\s+'((?:[^']|'')*)'/i;\n\nfunction rawIndexMarkerProbe(\n driver: MigrationDriver,\n index: IndexDef,\n present: boolean\n): CatalogProbe {\n return {\n id: `index-marker:${present ? \"present\" : \"absent\"}:${index.name}`,\n sql: existsSql(\n PG_CLASS_NS,\n \"n.nspname = $1 AND c.relname = $2 AND c.relkind = 'i' AND pg_catalog.obj_description(c.oid, 'pg_class') IS NOT DISTINCT FROM $3\"\n ),\n parameters: pgParams(\n driver,\n index.name,\n RAW_INDEX_MARKER_PREFIX + rawIndexMarker(index)\n ),\n equals: present,\n };\n}\n\n/** The raw index whose marker a `COMMENT ON INDEX` statement writes. */\nfunction commentedRawIndex(\n operation: DiffOperation,\n statement: string\n): IndexDef | undefined {\n const indexes =\n operation.type === \"createIndex\"\n ? [operation.index]\n : operation.type === \"createTable\"\n ? operation.table.indexes\n : [];\n return indexes.find(\n (index) =>\n index.raw !== undefined &&\n statement.includes(\n (RAW_INDEX_MARKER_PREFIX + rawIndexMarker(index)).replaceAll(\"'\", \"''\")\n )\n );\n}\n\nconst CREATE_INDEX_HEADER =\n /^\\s*CREATE\\s+(?:UNIQUE\\s+|SPATIAL\\s+|FULLTEXT\\s+)?INDEX\\s+(?:CONCURRENTLY\\s+)?(?:IF\\s+NOT\\s+EXISTS\\s+)?(\"(?:[^\"]|\"\")+\"|`(?:[^`]|``)+`|[\\w$]+)\\s+ON\\b/i;\n\n/** The trigger a `CREATE TRIGGER` or `DROP TRIGGER` statement names, unquoted. */\nconst TRIGGER_HEADER =\n /^(?:CREATE|DROP) TRIGGER (?:IF EXISTS )?(?:(?:\"(?:[^\"]|\"\")+\"|`(?:[^`]|``)+`)\\.)?(\"(?:[^\"]|\"\")+\"|`(?:[^`]|``)+`)/;\n\n/**\n * The probes of one statement of a view kept by triggers, created or\n * dropped: its table's, its body view's, each trigger's, and each index its\n * creation carries. Its function, its marker and its rows have none: they\n * stand with the table on a transactional dialect, and MySQL's filling is\n * written again whole by its next run.\n */\nfunction autoViewProbes(\n driver: MigrationDriver,\n view: string,\n objects: readonly AutoViewObject[],\n indexes: readonly IndexDef[],\n statement: string,\n creating: boolean\n): { pre: CatalogProbe; post: CatalogProbe } | null {\n const text = statement.trimStart();\n // A creation's drops are of what a hand left: none is proven.\n if (creating && text.startsWith(\"DROP \")) return null;\n const pair = (probe: (exists: boolean) => CatalogProbe) =>\n probePair(creating, probe);\n if (text.startsWith(\"CREATE TABLE \") || text.startsWith(\"DROP TABLE \"))\n return pair((exists) =>\n tableExistsProbe(driver, view, exists, \"stored-artifact\")\n );\n const trigger = TRIGGER_HEADER.exec(text)?.[1];\n if (trigger !== undefined) {\n const name = trigger\n .slice(1, -1)\n .replaceAll(trigger[0]! + trigger[0], trigger[0]!);\n const object = objects.find(\n (candidate) => candidate.kind === \"trigger\" && candidate.name === name\n );\n return object\n ? pair((exists) =>\n triggerExistsProbe(\n driver,\n object.table!,\n name,\n exists,\n \"stored-artifact\"\n )\n )\n : null;\n }\n const body = objects.find((object) => object.kind === \"view\");\n if (\n body &&\n (text.startsWith(\"CREATE VIEW \") || text.startsWith(\"DROP VIEW \"))\n )\n return pair((exists) =>\n viewExistsProbe(driver, body.name, exists, \"stored-artifact\")\n );\n return creating ? createdIndexProbes(driver, view, indexes, statement) : null;\n}\n\n/** A view's own creation, materialized or not, as the SQL drivers write it. */\nconst VIEW_CREATION = /^CREATE (?:MATERIALIZED )?VIEW /;\n\n/** The name a `CREATE INDEX` statement gives its index, unquoted. */\nfunction createdIndexName(statement: string): string | undefined {\n const name = CREATE_INDEX_HEADER.exec(statement)?.[1];\n if (name === undefined) return undefined;\n const quote = name[0];\n return quote === '\"' || quote === \"`\"\n ? name.slice(1, -1).replaceAll(quote + quote, quote)\n : name;\n}\n\n/**\n * The probes of a `CREATE INDEX` statement that an operation creating a\n * relation runs after it (a table, a materialized view): the index named in\n * its header, neither one whose name it extends (`by_email_b`) nor a column\n * it indexes.\n */\nconst ADD_FOREIGN_KEY_HEADER =\n /^\\s*ALTER\\s+TABLE\\s+[\\s\\S]*?\\bADD\\s+CONSTRAINT\\s+(\"(?:[^\"]|\"\")+\"|`(?:[^`]|``)+`|[\\w$]+)\\s+FOREIGN\\s+KEY\\b/i;\n\nfunction unquoteHeaderIdentifier(token: string): string {\n const quote = token[0];\n if (quote === '\"' || quote === \"`\") {\n return token.slice(1, -1).replaceAll(quote + quote, quote);\n }\n return token;\n}\n\nfunction createdForeignKeyProbes(\n driver: MigrationDriver,\n tableName: string,\n foreignKeys: readonly ForeignKeyDef[],\n statement: string\n): { pre: CatalogProbe; post: CatalogProbe } | null {\n if (driver.dialect !== \"postgresql\" && driver.dialect !== \"mysql\") {\n return null;\n }\n const match = ADD_FOREIGN_KEY_HEADER.exec(statement);\n if (!match) return null;\n const name = unquoteHeaderIdentifier(match[1]!);\n const fk = foreignKeys.find((item) => item.name === name);\n if (!fk) return null;\n if (driver.dialect === \"postgresql\") {\n const notValid = statement.trim().toUpperCase().endsWith(\"NOT VALID\");\n return {\n pre: foreignKeyExistsProbe(\n driver,\n tableName,\n fk.name,\n false,\n \"stored-artifact\"\n ),\n post: foreignKeyExistsProbe(\n driver,\n tableName,\n fk.name,\n true,\n \"stored-artifact\",\n notValid ? undefined : \"validated\"\n ),\n };\n }\n return probePair(true, (exists) =>\n foreignKeyExistsProbe(driver, tableName, fk.name, exists, \"stored-artifact\")\n );\n}\n\nfunction createdIndexProbes(\n driver: MigrationDriver,\n relation: string,\n indexes: readonly IndexDef[],\n statement: string\n): { pre: CatalogProbe; post: CatalogProbe } | null {\n const text = statement.trim().toUpperCase();\n if (!(text.startsWith(\"CREATE \") && text.includes(\"INDEX\"))) return null;\n const created = createdIndexName(statement);\n const index = indexes.find((item) => item.name === created);\n return index\n ? probePair(true, (exists) =>\n indexExistsProbe(\n driver,\n relation,\n index.name,\n exists,\n \"stored-artifact\"\n )\n )\n : null;\n}\n\nexport function probeForGeneratedStatement(\n driver: MigrationDriver,\n operation: DiffOperation,\n statement: string\n): { pre: CatalogProbe; post: CatalogProbe } | null {\n // An operation here is several statements, and they run in the one transaction.\n if (driver.dialect === \"surrealql\") return null;\n if (\n (driver.dialect === \"postgresql\" || driver.dialect === \"mysql\") &&\n namespace(driver) === undefined\n ) {\n return null;\n }\n const text = statement.trim().toUpperCase();\n if (\n text.startsWith(\"PRAGMA\") ||\n text.startsWith(\"INSERT \") ||\n text.startsWith(\"--\")\n ) {\n return null;\n }\n if (text.startsWith(\"COMMENT ON INDEX\")) {\n const index = commentedRawIndex(operation, statement);\n return index === undefined\n ? null\n : probePair(true, (present) =>\n rawIndexMarkerProbe(driver, index, present)\n );\n }\n switch (operation.type) {\n case \"createTable\":\n return text.startsWith(\"CREATE TABLE\")\n ? probePair(true, (exists) =>\n tableExistsProbe(\n driver,\n operation.table.name,\n exists,\n \"stored-artifact\"\n )\n )\n : (createdIndexProbes(\n driver,\n operation.table.name,\n operation.table.indexes,\n statement\n ) ??\n createdForeignKeyProbes(\n driver,\n operation.table.name,\n operation.table.foreignKeys,\n statement\n ));\n case \"dropTable\":\n return probePair(false, (exists) =>\n tableExistsProbe(driver, operation.tableName, exists, \"stored-artifact\")\n );\n case \"addColumn\": {\n const pre = columnExistsProbe(\n driver,\n operation.tableName,\n operation.column.name,\n false,\n \"stored-artifact\"\n );\n const required =\n !operation.column.nullable &&\n operation.column.default === undefined &&\n !operation.column.autoIncrement;\n const table = renderQualifiedIdentifier(\n (name) => driver.escapeIdentifier(name),\n driver.dialect === \"postgresql\" ? namespace(driver) : undefined,\n operation.tableName\n );\n return {\n pre: required\n ? {\n ...pre,\n id: `column:absent-and-empty-table:${operation.tableName}.${operation.column.name}`,\n sql: `SELECT (${pre.sql.slice(\"SELECT \".length)}) OR EXISTS (SELECT 1 FROM ${table} LIMIT 1)`,\n }\n : pre,\n post: columnExistsProbe(\n driver,\n operation.tableName,\n operation.column.name,\n true,\n \"stored-artifact\"\n ),\n };\n }\n case \"dropColumn\":\n return probePair(false, (exists) =>\n columnExistsProbe(\n driver,\n operation.tableName,\n operation.columnName,\n exists,\n \"stored-artifact\"\n )\n );\n case \"createIndex\":\n return probePair(true, (exists) =>\n indexExistsProbe(\n driver,\n operation.tableName,\n operation.index.name,\n exists,\n \"stored-artifact\"\n )\n );\n case \"dropIndex\":\n return probePair(false, (exists) =>\n indexExistsProbe(\n driver,\n operation.tableName,\n operation.indexName,\n exists,\n \"stored-artifact\"\n )\n );\n case \"addForeignKey\": {\n if (\n (driver.dialect !== \"postgresql\" && driver.dialect !== \"mysql\") ||\n !text.startsWith(\"ALTER TABLE\")\n ) {\n return null;\n }\n if (driver.dialect === \"postgresql\") {\n if (text.includes(\"VALIDATE CONSTRAINT\")) {\n return {\n pre: foreignKeyExistsProbe(\n driver,\n operation.tableName,\n operation.fk.name,\n true,\n \"stored-artifact\",\n \"unvalidated\"\n ),\n post: foreignKeyExistsProbe(\n driver,\n operation.tableName,\n operation.fk.name,\n true,\n \"stored-artifact\",\n \"validated\"\n ),\n };\n }\n return {\n pre: foreignKeyExistsProbe(\n driver,\n operation.tableName,\n operation.fk.name,\n false,\n \"stored-artifact\"\n ),\n post: foreignKeyExistsProbe(\n driver,\n operation.tableName,\n operation.fk.name,\n true,\n \"stored-artifact\",\n text.endsWith(\"NOT VALID\") ? undefined : \"validated\"\n ),\n };\n }\n return probePair(true, (exists) =>\n foreignKeyExistsProbe(\n driver,\n operation.tableName,\n operation.fk.name,\n exists,\n \"stored-artifact\"\n )\n );\n }\n case \"dropForeignKey\":\n if (\n (driver.dialect !== \"postgresql\" && driver.dialect !== \"mysql\") ||\n !text.startsWith(\"ALTER TABLE\")\n ) {\n return null;\n }\n return probePair(false, (exists) =>\n foreignKeyExistsProbe(\n driver,\n operation.tableName,\n operation.fkName,\n exists,\n \"stored-artifact\"\n )\n );\n case \"createEnum\":\n if (driver.dialect !== \"postgresql\" || !text.startsWith(\"CREATE TYPE\")) {\n return null;\n }\n return probePair(true, (exists) =>\n enumExistsProbe(driver, operation.enumDef.name, exists)\n );\n case \"dropEnum\":\n if (driver.dialect !== \"postgresql\" || !text.startsWith(\"DROP TYPE\")) {\n return null;\n }\n return probePair(false, (exists) =>\n enumExistsProbe(driver, operation.enumName, exists)\n );\n case \"alterEnum\": {\n if (driver.dialect !== \"postgresql\" || !text.startsWith(\"ALTER TYPE\")) {\n return null;\n }\n const match = ADD_ENUM_VALUE.exec(statement);\n if (!match) return null;\n const value = match[1]!.replaceAll(\"''\", \"'\");\n if (!operation.addValues?.includes(value)) return null;\n return probePair(true, (exists) =>\n enumValueExistsProbe(driver, operation.enumName, value, exists)\n );\n }\n case \"createView\":\n if (operation.view.auto)\n return autoViewProbes(\n driver,\n operation.view.name,\n operation.view.auto.objects,\n operation.view.indexes ?? [],\n statement,\n true\n );\n // A materialized view's creation is followed by its indexes.\n if (!VIEW_CREATION.test(text))\n return createdIndexProbes(\n driver,\n operation.view.name,\n operation.view.indexes ?? [],\n statement\n );\n return probePair(true, (exists) =>\n viewExistsProbe(\n driver,\n operation.view.name,\n exists,\n \"stored-artifact\",\n operation.view.materialized\n )\n );\n case \"dropView\":\n if (operation.auto)\n return autoViewProbes(\n driver,\n operation.viewName,\n operation.auto.objects,\n [],\n statement,\n false\n );\n return probePair(false, (exists) =>\n viewExistsProbe(\n driver,\n operation.viewName,\n exists,\n \"stored-artifact\",\n operation.materialized\n )\n );\n default:\n return null;\n }\n}\n","/**\n * Inverse owner for generated DiffOperation programs.\n * Empty programs invert to an empty schema rollback. Missing inverses are\n * irreversible. This is the only place that answers that question.\n */\n\nimport { applyNativeRename } from \"./native-rename\";\nimport type { DiffOperation, SchemaSnapshot, TableDef } from \"./types\";\nimport { defaultGeneratedPrimaryKeyName } from \"./utils\";\n\nexport interface InvertedOperations {\n operations: DiffOperation[];\n warnings: string[];\n}\n\nexport function invertOperations(\n operations: DiffOperation[],\n previousSnapshot: SchemaSnapshot,\n projectRename: typeof applyNativeRename = applyNativeRename,\n primaryKeyName: typeof defaultGeneratedPrimaryKeyName = defaultGeneratedPrimaryKeyName\n): InvertedOperations {\n const warnings: string[] = [];\n const inverted: DiffOperation[] = [];\n // At the inverse of operation i, every rename that preceded i in the up\n // program is still active and every rename that followed it has already been\n // inverted. Keep the previous definitions at each exact prefix so a restored\n // FK targets the identity that exists at that point — neither always-old nor\n // always-new is correct.\n let previousAtOperationIdentity = previousSnapshot;\n const previousIdentityBefore: SchemaSnapshot[] = [];\n // A key the up program drops by itself (PostgreSQL/MySQL drop every key of\n // a dropped table first) comes back through that drop's own inverse, which\n // runs after every recreated table exists. The recreated table leaves it\n // out: restored inline it would name a table not yet recreated, and then be\n // added a second time.\n const keysRestoredByTheirOwnInverse = new Set<string>();\n for (const op of operations) {\n previousIdentityBefore.push(previousAtOperationIdentity);\n if (op.type === \"dropForeignKey\") {\n keysRestoredByTheirOwnInverse.add(\n foreignKeyIdentity(op.tableName, op.fkName)\n );\n }\n if (op.type === \"renameTable\" || op.type === \"renameColumn\") {\n previousAtOperationIdentity = projectRename(\n previousAtOperationIdentity,\n op\n );\n }\n }\n\n for (let i = operations.length - 1; i >= 0; i--) {\n const op = operations[i]!;\n const previousAtIdentity = previousIdentityBefore[i] ?? previousSnapshot;\n const findPrevTable = (name: string): TableDef | undefined =>\n previousAtIdentity.tables.find((table) => table.name === name);\n const inverse = invertOperation(\n op,\n previousSnapshot,\n findPrevTable,\n keysRestoredByTheirOwnInverse,\n warnings,\n primaryKeyName\n );\n if (inverse) inverted.push(...inverse);\n }\n\n return { operations: inverted, warnings };\n}\n\nconst foreignKeyIdentity = (tableName: string, fkName: string) =>\n `${tableName}\\u0000${fkName}`;\n\nfunction missingPrevious(warnings: string[], target: string): null {\n warnings.push(`Cannot invert ${target}: missing from previous snapshot.`);\n return null;\n}\n\nfunction invertOperation(\n op: DiffOperation,\n previousSnapshot: SchemaSnapshot,\n findPrevTable: (name: string) => TableDef | undefined,\n keysRestoredByTheirOwnInverse: ReadonlySet<string>,\n warnings: string[],\n primaryKeyName: typeof defaultGeneratedPrimaryKeyName\n): DiffOperation[] | null {\n switch (op.type) {\n case \"createTable\":\n warnings.push(\n `createTable \"${op.table.name}\" inverts to dropTable. No data is preserved.`\n );\n return [{ type: \"dropTable\", tableName: op.table.name }];\n\n case \"dropTable\": {\n const table = findPrevTable(op.tableName);\n if (!table)\n return missingPrevious(warnings, `dropTable \"${op.tableName}\"`);\n warnings.push(\n `dropTable \"${op.tableName}\" rollback restores schema only.`\n );\n const foreignKeys = table.foreignKeys.filter(\n (fk) =>\n !keysRestoredByTheirOwnInverse.has(\n foreignKeyIdentity(table.name, fk.name)\n )\n );\n return [{ type: \"createTable\", table: { ...table, foreignKeys } }];\n }\n\n case \"renameTable\":\n return [{ type: \"renameTable\", from: op.to, to: op.from }];\n\n case \"addColumn\":\n return [\n {\n type: \"dropColumn\",\n tableName: op.tableName,\n columnName: op.column.name,\n },\n ];\n\n case \"dropColumn\": {\n const table = findPrevTable(op.tableName);\n const column = table?.columns.find((c) => c.name === op.columnName);\n if (!column)\n return missingPrevious(\n warnings,\n `dropColumn \"${op.tableName}.${op.columnName}\"`\n );\n warnings.push(\n `dropColumn \"${op.tableName}.${op.columnName}\" rollback restores column only.`\n );\n return [{ type: \"addColumn\", tableName: op.tableName, column }];\n }\n\n case \"renameColumn\":\n return [\n {\n type: \"renameColumn\",\n tableName: op.tableName,\n from: op.to,\n to: op.from,\n },\n ];\n\n case \"alterColumn\":\n return [\n {\n type: \"alterColumn\",\n tableName: op.tableName,\n columnName: op.columnName,\n from: op.to,\n to: op.from,\n },\n ];\n\n case \"createIndex\":\n return [\n {\n type: \"dropIndex\",\n tableName: op.tableName,\n indexName: op.index.name,\n ...(op.index.raw ? { raw: true } : {}),\n },\n ];\n\n case \"dropIndex\": {\n // A materialized view holds indexes too; renames never reach its name.\n const index = (\n findPrevTable(op.tableName) ??\n previousSnapshot.views?.find((view) => view.name === op.tableName)\n )?.indexes?.find((i) => i.name === op.indexName);\n if (!index)\n return missingPrevious(\n warnings,\n `dropIndex \"${op.indexName}\" on \"${op.tableName}\"`\n );\n return [{ type: \"createIndex\", tableName: op.tableName, index }];\n }\n\n case \"addForeignKey\":\n return [\n { type: \"dropForeignKey\", tableName: op.tableName, fkName: op.fk.name },\n ];\n\n case \"dropForeignKey\": {\n const table = findPrevTable(op.tableName);\n const fk = table?.foreignKeys.find((f) => f.name === op.fkName);\n if (!fk)\n return missingPrevious(\n warnings,\n `dropForeignKey \"${op.fkName}\" on \"${op.tableName}\"`\n );\n return [{ type: \"addForeignKey\", tableName: op.tableName, fk }];\n }\n\n case \"addUniqueConstraint\":\n return [\n {\n type: \"dropUniqueConstraint\",\n tableName: op.tableName,\n constraintName: op.constraint.name,\n },\n ];\n\n case \"dropUniqueConstraint\": {\n const table = findPrevTable(op.tableName);\n const constraint = table?.uniqueConstraints.find(\n (u) => u.name === op.constraintName\n );\n if (!constraint)\n return missingPrevious(\n warnings,\n `dropUniqueConstraint \"${op.constraintName}\" on \"${op.tableName}\"`\n );\n return [\n { type: \"addUniqueConstraint\", tableName: op.tableName, constraint },\n ];\n }\n\n case \"addPrimaryKey\":\n return [\n {\n type: \"dropPrimaryKey\",\n tableName: op.tableName,\n constraintName: primaryKeyName(op.tableName, op.primaryKey.name),\n },\n ];\n\n case \"dropPrimaryKey\": {\n const table = findPrevTable(op.tableName);\n if (!table?.primaryKey)\n return missingPrevious(warnings, `dropPrimaryKey on \"${op.tableName}\"`);\n return [\n {\n type: \"addPrimaryKey\",\n tableName: op.tableName,\n primaryKey: table.primaryKey,\n },\n ];\n }\n\n case \"createView\":\n return [\n {\n type: \"dropView\",\n viewName: op.view.name,\n ...(op.view.materialized ? { materialized: true } : {}),\n ...(op.view.auto ? { auto: op.view.auto } : {}),\n },\n ];\n\n case \"dropView\": {\n const view = previousSnapshot.views?.find(\n (item) => item.name === op.viewName\n );\n if (!view) return missingPrevious(warnings, `dropView \"${op.viewName}\"`);\n return [{ type: \"createView\", view }];\n }\n\n case \"createEnum\":\n return [{ type: \"dropEnum\", enumName: op.enumDef.name }];\n\n case \"dropEnum\": {\n const enumDef = previousSnapshot.enums?.find(\n (e) => e.name === op.enumName\n );\n if (!enumDef)\n return missingPrevious(warnings, `dropEnum \"${op.enumName}\"`);\n return [{ type: \"createEnum\", enumDef }];\n }\n\n case \"alterEnum\": {\n const prevEnum = previousSnapshot.enums?.find(\n (e) => e.name === op.enumName\n );\n if (!prevEnum)\n return missingPrevious(warnings, `alterEnum \"${op.enumName}\"`);\n if (op.removeValues?.length) {\n warnings.push(\n `alterEnum \"${op.enumName}\" removed [${op.removeValues.join(\", \")}]: rollback restores values only.`\n );\n }\n if (op.addValues?.length) {\n warnings.push(\n `alterEnum \"${op.enumName}\" rollback removes [${op.addValues.join(\", \")}]: remap rows manually.`\n );\n }\n return [\n {\n type: \"alterEnum\",\n enumName: op.enumName,\n addValues: op.removeValues,\n removeValues: op.addValues,\n newValues: prevEnum.values,\n dependentColumns: op.dependentColumns,\n },\n ];\n }\n\n default:\n warnings.push(\"Cannot invert an unknown generated operation.\");\n return null;\n }\n}\n","import { isDestructiveOperation } from \"./differ\";\n/**\n * One compiler: DiffOperation and manual Sql become structured operations\n * that share one SQL blob. No delimiter split.\n */\n\nimport type { Sql } from \"@sql\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { canonicalDecimalText } from \"../validation/primitives/decimal-value\";\nimport { encodeBase64 } from \"./base64\";\nimport {\n type CatalogProbe,\n probeForGeneratedStatement,\n} from \"./catalog-probes\";\nimport type { DDLContext, MigrationDriver } from \"./drivers\";\nimport { invertOperations } from \"./invert\";\nimport type { SqlAssembly } from \"./sql-assembly\";\nimport { runsConcurrently } from \"./statement-safety\";\nimport type { DiffOperation, SchemaSnapshot } from \"./types\";\nimport { encodeTransitionHash } from \"./v1-parse\";\n\nexport {\n assertTransactionalBoundaryHonored,\n classifyStoredAtomicity,\n decodeParameter,\n groupContiguousAtomicity,\n refuseSqliteStepwise,\n stepStatements,\n tableRewrites,\n} from \"./runtime-dispatch\";\n\nimport type {\n AtomicityClass,\n MigrationApprovalV1,\n MigrationBooleanCheckV1,\n MigrationCheckInput,\n MigrationDispatchV1,\n MigrationOperationV1,\n MigrationParameterV1,\n MigrationParentTransitionV1,\n MigrationRollbackV1,\n MigrationStepV1,\n} from \"./v1-types\";\n\nexport interface CompiledTransition {\n readonly operations: readonly MigrationOperationV1[];\n readonly rollback: MigrationRollbackV1;\n readonly originChecks: readonly MigrationBooleanCheckV1[];\n readonly requestedForwardBoundary: \"transactional\" | \"stepwise\" | null;\n readonly atomicity: AtomicityClass;\n readonly warnings?: readonly string[];\n}\n\n/**\n * The context a generated statement compiles in. `lowLock` asks PostgreSQL\n * for the form of a step that blocks no write while it reads the table (T5b):\n * `\"add\"` builds an index `CONCURRENTLY` or adds a foreign key `NOT VALID`,\n * `\"validate\"` validates that key. Only `generate({ lowLock: true })` sets\n * it, and only on a table that existed before the migration.\n */\nexport type LowLockContext = DDLContext & {\n readonly lowLock?: \"add\" | \"validate\";\n};\n\n/** One state of a generated program split at its low-lock steps. */\nexport interface LowLockState {\n readonly operations: readonly DiffOperation[];\n /** The schema the state reaches. */\n readonly snapshot: SchemaSnapshot;\n /** Whether it validates the keys an earlier state added `NOT VALID`. */\n readonly validates: boolean;\n}\n\n/**\n * Splits a generated PostgreSQL program into the states that give each\n * low-lock step its own commit (T5b), or returns `undefined` when it has none\n * to give. A step is an index built on, or a foreign key added to, a table\n * the program does not create (a table it creates is empty). Each index build\n * is a state of its own: `CREATE INDEX CONCURRENTLY` runs outside any\n * transaction, and an interrupted build is then one unfinished single-step\n * attempt that `resolve` repairs either way. The keys are added `NOT VALID`\n * with the last state, and a final state validates them in a commit of its\n * own; a failed validation rolls back alone and `apply` resumes from the\n * marker.\n *\n * The schemas between states are the target's with the later states' effects\n * undone, so only an index build, an index drop or a key may follow the first\n * build; otherwise, or when a dropped index cannot be read back from the\n * origin, the program is not split and keeps its blocking forms.\n */\nexport function lowLockStates(\n operations: readonly DiffOperation[],\n current: SchemaSnapshot,\n desired: SchemaSnapshot\n): { states: LowLockState[]; steps: ReadonlySet<DiffOperation> } | undefined {\n const steps = lowLockSteps(operations, desired);\n if (steps.size === 0) return;\n const first = operations.findIndex(\n (op) => op.type === \"createIndex\" && steps.has(op)\n );\n const tail = first < 0 ? [] : operations.slice(first);\n const renames = operations.some(\n (op) => op.type === \"renameTable\" || op.type === \"renameColumn\"\n );\n if (\n !tail.every((op) =>\n op.type === \"createIndex\"\n ? steps.has(op)\n : op.type === \"addForeignKey\" || (op.type === \"dropIndex\" && !renames)\n )\n ) {\n return;\n }\n const ends: number[] = [];\n for (const [index, op] of operations.entries()) {\n if (op.type === \"createIndex\" && steps.has(op)) {\n if (index > (ends.at(-1) ?? 0)) ends.push(index);\n ends.push(index + 1);\n }\n }\n if (ends.at(-1) !== operations.length) ends.push(operations.length);\n const states: LowLockState[] = [];\n for (const [index, end] of ends.entries()) {\n const snapshot = withoutEffects(desired, current, operations.slice(end));\n if (!snapshot) return;\n states.push({\n operations: operations.slice(ends[index - 1] ?? 0, end),\n snapshot,\n validates: false,\n });\n }\n const keys = operations.filter(\n (op) => op.type === \"addForeignKey\" && steps.has(op)\n );\n if (keys.length > 0) {\n states.push({ operations: keys, snapshot: desired, validates: true });\n }\n return { states, steps };\n}\n\n/**\n * The index builds and keys of `operations` on tables it does not create. A\n * raw index is not one: its text is the author's, and it is built blocking.\n * Nor is an index of a materialized view: no write waits for its build, only\n * a refresh.\n */\nexport function lowLockSteps(\n operations: readonly DiffOperation[],\n desired: SchemaSnapshot\n): ReadonlySet<DiffOperation> {\n const inPlace = new Set([\n ...operations.flatMap((op) =>\n op.type === \"createTable\" ? op.table.name : []\n ),\n ...(desired.views ?? []).map((view) => view.name),\n ]);\n return new Set(\n operations.filter(\n (op) =>\n ((op.type === \"createIndex\" && !op.index.raw) ||\n op.type === \"addForeignKey\") &&\n !inPlace.has(op.tableName)\n )\n );\n}\n\n/** `desired` before `later`: an index build, an index drop or a key. */\nfunction withoutEffects(\n desired: SchemaSnapshot,\n current: SchemaSnapshot,\n later: readonly DiffOperation[]\n): SchemaSnapshot | undefined {\n let readable = later.every(\n (op) =>\n \"tableName\" in op &&\n desired.tables.some((table) => table.name === op.tableName)\n );\n const tables = desired.tables.map((table) => {\n const own = later.filter(\n (op) => \"tableName\" in op && op.tableName === table.name\n );\n if (own.length === 0) return table;\n const built = new Set(\n own.flatMap((op) => (op.type === \"createIndex\" ? op.index.name : []))\n );\n const keys = new Set(\n own.flatMap((op) => (op.type === \"addForeignKey\" ? op.fk.name : []))\n );\n const restored = own.flatMap((op) => {\n if (op.type !== \"dropIndex\") return [];\n const index = current.tables\n .find((origin) => origin.name === table.name)\n ?.indexes.find((item) => item.name === op.indexName);\n if (!index) readable = false;\n return index ?? [];\n });\n return {\n ...table,\n indexes: [\n ...table.indexes.filter((index) => !built.has(index.name)),\n ...restored,\n ],\n foreignKeys: table.foreignKeys.filter((key) => !keys.has(key.name)),\n };\n });\n return readable ? { ...desired, tables } : undefined;\n}\n\nexport function compileGeneratedTransition(\n operations: readonly DiffOperation[],\n driver: MigrationDriver,\n destination: DDLContext[\"destination\"],\n currentSchema: SchemaSnapshot,\n desiredSchema: SchemaSnapshot,\n assembly: SqlAssembly,\n lowLock: ReadonlySet<DiffOperation> = new Set()\n): CompiledTransition {\n const compiled = operations\n .map((operation, index) =>\n compileGeneratedOperation(\n operation,\n driver,\n destination,\n currentSchema,\n operations,\n index,\n assembly,\n lowLock.has(operation) ? \"add\" : undefined\n )\n )\n .filter((operation) => operation.steps.length > 0);\n const inverse = invertOperations(\n [...operations],\n currentSchema,\n driver.projectNativeRename.bind(driver),\n driver.generatedPrimaryKeyName.bind(driver)\n );\n const missingBackfill = inverse.operations.find(\n (operation) =>\n operation.type === \"addColumn\" &&\n !operation.column.nullable &&\n operation.column.default === undefined\n );\n const irreversibleReason =\n missingBackfill && missingBackfill.type === \"addColumn\"\n ? `Rollback cannot restore required \"${missingBackfill.tableName}.${missingBackfill.column.name}\" without backfill; author manual rollback.`\n : inverse.operations\n .map((operation) => driver.getIrreversibleRollbackReason(operation))\n .find((reason) => reason !== undefined);\n const rollback: MigrationRollbackV1 =\n inverse.operations.length === 0 && operations.length === 0\n ? { kind: \"schema\", operations: [] }\n : irreversibleReason !== undefined\n ? { kind: \"irreversible\", reason: irreversibleReason }\n : inverse.operations.length === 0\n ? {\n kind: \"irreversible\",\n reason:\n inverse.warnings[0] ??\n \"Generated operations have no automatic inverse\",\n }\n : {\n kind: \"schema\",\n operations: inverse.operations\n .map((operation, index) =>\n compileGeneratedOperation(\n operation,\n driver,\n destination,\n desiredSchema,\n inverse.operations,\n index,\n assembly\n )\n )\n .filter((operation) => operation.steps.length > 0),\n };\n return {\n operations: compiled,\n rollback,\n warnings: inverse.warnings,\n originChecks: [],\n requestedForwardBoundary: null,\n atomicity: classifyGeneratedAtomicity(driver, operations),\n };\n}\n\n/**\n * The state that validates the foreign keys an earlier state added `NOT VALID`\n * (T5b). Undoing it is nothing: the keys stay, as their state declares them.\n */\nexport function compileValidationTransition(\n keys: readonly DiffOperation[],\n driver: MigrationDriver,\n currentSchema: SchemaSnapshot,\n assembly: SqlAssembly\n): CompiledTransition {\n return {\n operations: keys.map((key, index) =>\n compileGeneratedOperation(\n key,\n driver,\n \"artifact\",\n currentSchema,\n keys,\n index,\n assembly,\n \"validate\"\n )\n ),\n rollback: { kind: \"schema\", operations: [] },\n originChecks: [],\n requestedForwardBoundary: null,\n atomicity: \"transactional\",\n };\n}\n\nfunction compileGeneratedOperation(\n operation: DiffOperation,\n driver: MigrationDriver,\n destination: DDLContext[\"destination\"],\n currentSchema: SchemaSnapshot,\n batch: readonly DiffOperation[],\n index: number,\n assembly: SqlAssembly,\n lowLock?: LowLockContext[\"lowLock\"]\n): MigrationOperationV1 {\n const context: LowLockContext = {\n destination,\n currentSchema,\n precedingOperations: batch.slice(0, index),\n followingOperations: batch.slice(index + 1),\n ...(lowLock === undefined ? {} : { lowLock }),\n };\n const statements = driver.compileStatements(operation, context);\n const steps: MigrationStepV1[] = statements.map((statement) => {\n const probes = probeForGeneratedStatement(driver, operation, statement);\n const execute = addDispatch(assembly, statement, []);\n if (!probes) {\n return { retry: \"opaque\", execute };\n }\n return {\n retry: \"proven\",\n precheck: checkFromProbe(assembly, probes.pre),\n execute,\n postcheck: checkFromProbe(assembly, probes.post),\n };\n });\n return {\n id: `${operation.type}:${index}`,\n label: operationLabel(operation),\n origin: \"generated\",\n risk: isDestructiveOperation(operation) ? \"destructive\" : \"safe\",\n steps,\n };\n}\n\nfunction operationLabel(operation: DiffOperation): string {\n if (operation.type === \"createView\")\n return `createView ${operation.view.name}`;\n if (operation.type === \"dropView\") return `dropView ${operation.viewName}`;\n return \"tableName\" in operation\n ? `${operation.type} ${operation.tableName}${\"columnName\" in operation ? `.${operation.columnName}` : \"column\" in operation ? `.${operation.column.name}` : \"\"}`\n : operation.type;\n}\n\nconst invalidEstate = (message: string) =>\n new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_ESTATE);\nconst unsupportedProvider = (message: string, meta?: Record<string, unknown>) =>\n new MigrationError(\n message,\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER,\n meta ? { meta } : undefined\n );\n\nexport function compileManualTransition(\n up: readonly Sql[],\n rollback:\n | {\n readonly kind: \"manual\";\n readonly execution: AtomicityClass;\n readonly sql: readonly Sql[];\n }\n | { readonly kind: \"irreversible\"; readonly reason: string },\n dialect: \"postgresql\" | \"mysql\" | \"sqlite\",\n requested: AtomicityClass,\n originChecks: readonly MigrationCheckInput[] | undefined,\n assembly: SqlAssembly\n): CompiledTransition {\n const operations = compileManualOperations(\n up,\n dialect,\n assembly,\n \"forward\",\n requested\n );\n if (rollback.kind === \"irreversible\" && rollback.reason.trim().length === 0)\n throw invalidEstate(\"Irreversible rollback needs non-empty reason\");\n const compiledRollback: MigrationRollbackV1 =\n rollback.kind === \"irreversible\"\n ? rollback\n : {\n kind: \"manual\",\n requestedBoundary: rollback.execution,\n operations: compileManualOperations(\n rollback.sql,\n dialect,\n assembly,\n \"rollback\",\n rollback.execution\n ),\n };\n return {\n operations,\n rollback: compiledRollback,\n originChecks: (originChecks ?? []).map((check, index) =>\n compileTrustedCheck(check, dialect, assembly, `origin:${index}`)\n ),\n requestedForwardBoundary: requested,\n atomicity: requested,\n };\n}\n\nexport function assertManualStepwiseProof(\n compiled: CompiledTransition,\n destinationChecks: readonly MigrationBooleanCheckV1[]\n): void {\n const forwardStepwise = compiled.requestedForwardBoundary === \"stepwise\";\n const rollbackStepwise =\n compiled.rollback.kind === \"manual\" &&\n compiled.rollback.requestedBoundary === \"stepwise\";\n if (!(forwardStepwise || rollbackStepwise)) return;\n if (compiled.originChecks.length === 0 || destinationChecks.length === 0)\n throw invalidEstate(\n \"Stepwise manual requires origin and destination checks\"\n );\n}\n\nfunction compileManualOperations(\n fragments: readonly Sql[],\n dialect: \"postgresql\" | \"mysql\" | \"sqlite\",\n assembly: SqlAssembly,\n prefix: string,\n execution: AtomicityClass\n): MigrationOperationV1[] {\n if (fragments.length === 0)\n throw invalidEstate(`Manual ${prefix} requires >= 1 dispatch`);\n if (execution === \"stepwise\" && dialect === \"sqlite\")\n throw unsupportedProvider(\n `SQLite does not support stepwise manual ${prefix}; use \"transactional\".`,\n { dialect, feature: \"stepwise execution\" }\n );\n return fragments.map((fragment, index) => {\n const text = fragment.toStatement(dialect === \"postgresql\" ? \"$n\" : \"?\");\n if (text.trim().length === 0)\n throw invalidEstate(`Manual ${prefix} dispatch ${index} is empty`);\n if (\n execution === \"transactional\" &&\n dialect === \"postgresql\" &&\n runsConcurrently(text)\n )\n throw invalidEstate(\n `Manual ${prefix} dispatch ${index} uses CONCURRENTLY; requires \"stepwise\".`\n );\n const parameters = fragment.values.map((value) => encodeParameter(value));\n return {\n id: `manual:${prefix}:${index}`,\n label: \"manual\",\n origin: \"manual\" as const,\n risk: \"opaque\" as const,\n steps: [\n {\n retry: \"opaque\" as const,\n execute: addDispatch(assembly, text, parameters),\n },\n ],\n };\n });\n}\n\nexport function compileTrustedCheck(\n input: MigrationCheckInput,\n dialect: \"postgresql\" | \"mysql\" | \"sqlite\",\n assembly: SqlAssembly,\n id: string\n): MigrationBooleanCheckV1 & { readonly kind: \"trusted-read\" } {\n const text = input.query.toStatement(dialect === \"postgresql\" ? \"$n\" : \"?\");\n const parameters = input.query.values.map((value) => encodeParameter(value));\n return {\n kind: \"trusted-read\" as const,\n id,\n query: addDispatch(assembly, text, parameters),\n equals: input.equals,\n };\n}\n\nexport function sealParent(\n fromState: string | null,\n compiled: CompiledTransition,\n approvals: readonly MigrationApprovalV1[] = [],\n adopts: readonly string[] = []\n): Omit<MigrationParentTransitionV1, \"transitionHash\"> {\n return {\n fromState,\n originChecks: compiled.originChecks,\n requestedForwardBoundary: compiled.requestedForwardBoundary,\n operations: compiled.operations,\n rollback: compiled.rollback,\n ...(approvals.length === 0 ? {} : { approvals }),\n ...(adopts.length === 0 ? {} : { adopts }),\n };\n}\n\nexport function hashParent(\n parent: Omit<MigrationParentTransitionV1, \"transitionHash\">\n): MigrationParentTransitionV1 {\n return { ...parent, transitionHash: encodeTransitionHash(parent) };\n}\n\nfunction addDispatch(\n assembly: SqlAssembly,\n text: string,\n parameters: readonly MigrationParameterV1[]\n): MigrationDispatchV1 {\n const index = assembly.add(text, parameters);\n return {\n dispatchId: \"0\".repeat(64),\n sqlHash: \"0\".repeat(64),\n offset: index,\n length: 0,\n parameters,\n };\n}\n\nfunction checkFromProbe(\n assembly: SqlAssembly,\n probe: CatalogProbe\n): MigrationBooleanCheckV1 {\n return {\n kind: \"driver\",\n id: probe.id,\n query: addDispatch(assembly, probe.sql, probe.parameters),\n equals: probe.equals,\n };\n}\n\nexport function rebindDispatches(\n operations: readonly MigrationOperationV1[],\n dispatches: readonly MigrationDispatchV1[]\n): MigrationOperationV1[] {\n return operations.map((operation) => ({\n ...operation,\n steps: operation.steps.map((step) => rebindStep(step, dispatches)),\n }));\n}\n\nfunction rebindStep(\n step: MigrationStepV1,\n dispatches: readonly MigrationDispatchV1[]\n): MigrationStepV1 {\n const execute = dispatchAt(dispatches, step.execute.offset);\n if (step.retry === \"opaque\") {\n return { retry: \"opaque\", execute };\n }\n return {\n retry: \"proven\",\n precheck: {\n ...step.precheck,\n query: dispatchAt(dispatches, step.precheck.query.offset),\n },\n execute,\n postcheck: {\n ...step.postcheck,\n query: dispatchAt(dispatches, step.postcheck.query.offset),\n },\n };\n}\n\n/** The sealed dispatch at an index the same assembly handed out. */\nexport function dispatchAt(\n dispatches: readonly MigrationDispatchV1[],\n index: number\n): MigrationDispatchV1 {\n const found = dispatches[index];\n if (!found) {\n throw new MigrationError(\n \"Compiled dispatch is missing from the SQL assembly\",\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n return found;\n}\n\nexport function rebindChecks(\n checks: readonly MigrationBooleanCheckV1[],\n dispatches: readonly MigrationDispatchV1[]\n): MigrationBooleanCheckV1[] {\n return checks.map((check) => ({\n ...check,\n query: dispatchAt(dispatches, check.query.offset),\n }));\n}\n\nexport function rebindRollback(\n rollback: MigrationRollbackV1,\n dispatches: readonly MigrationDispatchV1[]\n): MigrationRollbackV1 {\n if (rollback.kind === \"irreversible\") return rollback;\n return {\n ...rollback,\n operations: rebindDispatches(rollback.operations, dispatches),\n };\n}\n\nexport function classifyGeneratedAtomicity(\n driver: MigrationDriver,\n operations: readonly DiffOperation[],\n reset?: boolean\n): AtomicityClass {\n if (driver.dialect === \"mysql\" || driver.buildsApart?.(operations, reset))\n return \"stepwise\";\n if (\n operations.some(\n (operation) =>\n operation.type === \"alterEnum\" &&\n (operation.addValues?.length ?? 0) > 0 &&\n !driver.capabilities.supportsAddEnumValueInTransaction\n )\n ) {\n return \"stepwise\";\n }\n return \"transactional\";\n}\n\nexport function encodeParameter(value: unknown): MigrationParameterV1 {\n if (value === null || value === undefined) return { kind: \"null\" };\n if (typeof value === \"boolean\") return { kind: \"boolean\", value };\n if (typeof value === \"string\") return { kind: \"string\", value };\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw invalidEstate(\"SQL parameters refuse NaN and Infinity\");\n }\n return { kind: \"number\", value };\n }\n if (typeof value === \"bigint\")\n return { kind: \"bigint\", value: value.toString() };\n if (value instanceof Date)\n return { kind: \"date-time\", value: value.toISOString() };\n if (value instanceof Uint8Array) {\n return { kind: \"bytes\", value: encodeBase64(value) };\n }\n const decimal = canonicalDecimalText(value);\n if (decimal !== undefined) return { kind: \"decimal\", value: decimal };\n if (typeof value === \"function\" || typeof value === \"symbol\") {\n throw invalidEstate(\"SQL parameters refuse functions and symbols\");\n }\n return { kind: \"json\", value };\n}\n","/**\n * One hostile-input boundary for generation options and manual definitions.\n * It settles every caller-owned accessor before estate or provider access.\n */\n\nimport { Sql } from \"@sql\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport { snapshotExactArray, snapshotExactRecord } from \"./input-boundary\";\nimport type { ResolveCallback } from \"./types\";\nimport { ks } from \"./v1-parse-shared\";\nimport type {\n GenerateV1Options,\n ManualMigrationInput,\n ManualTransitionInput,\n MigrationCheckInput,\n} from \"./v1-types\";\n\nconst GEN_KEYS = ks(\n \"name from dryRun resolve skipValidation manualMigration lowLock adopt\"\n);\n\nexport function normalizeGenerateOptions(options: unknown): GenerateV1Options {\n const record = snapshotExactRecord(\n options,\n GEN_KEYS,\n \"generate options\",\n refuseGenerateOptions\n );\n const { name, from, resolve, manualMigration, adopt } = record;\n if (name !== undefined && typeof name !== \"string\")\n refuseGenerateOptions(\"generate name must be string\");\n if (from !== undefined && from !== null && typeof from !== \"string\")\n refuseGenerateOptions(\"generate from must be string or null\");\n const optBool = (key: string): boolean | undefined => {\n const v = record[key];\n if (v === undefined || typeof v === \"boolean\") return v;\n refuseGenerateOptions(`generate ${key} must be boolean`);\n };\n const dryRun = optBool(\"dryRun\");\n const skipValidation = optBool(\"skipValidation\");\n const lowLock = optBool(\"lowLock\");\n if (resolve !== undefined && !isResolveCallback(resolve))\n refuseGenerateOptions(\"generate resolve must be function\");\n return Object.freeze({\n ...(adopt === undefined ? {} : { adopt: snapshotAdopt(adopt) }),\n ...(name === undefined ? {} : { name }),\n ...(from === undefined ? {} : { from }),\n ...(dryRun === undefined ? {} : { dryRun }),\n ...(resolve === undefined ? {} : { resolve }),\n ...(skipValidation === undefined ? {} : { skipValidation }),\n ...(lowLock === undefined ? {} : { lowLock }),\n ...(manualMigration === undefined\n ? {}\n : { manualMigration: snapshotManualMigration(manualMigration) }),\n });\n}\n\n/** The physical table names `adopt` lists, detached, sorted, unrepeated. */\nfunction snapshotAdopt(value: unknown): readonly string[] {\n const names = snapshotExactArray(\n value,\n \"generate adopt\",\n refuseGenerateOptions\n );\n if (names.length === 0) {\n return refuseGenerateOptions(\"generate adopt must name at least one table\");\n }\n for (const [index, name] of names.entries()) {\n if (typeof name !== \"string\" || name.length === 0) {\n return refuseGenerateOptions(\n \"generate adopt must contain non-empty physical table names\"\n );\n }\n if (names.indexOf(name) !== index) {\n return refuseGenerateOptions(`generate adopt repeats \"${name}\"`);\n }\n }\n return Object.freeze([...(names as string[])].sort());\n}\n\nfunction snapshotManualMigration(value: unknown): ManualMigrationInput {\n const record = snapshotExactRecord(\n value,\n [\"transitions\", \"destinationChecks\"],\n \"manual migration\",\n refuseManualDefinition\n );\n const transitions = snapshotExactArray(\n record.transitions,\n \"manual migration transitions\",\n refuseManualDefinition\n ).map((transition, index) =>\n snapshotManualTransition(transition, `manual transition ${index}`)\n );\n if (transitions.length === 0) {\n return refuseManualDefinition(\n \"A manual migration must define at least one parent transition\"\n );\n }\n const destinationChecks =\n record.destinationChecks === undefined\n ? undefined\n : snapshotExactArray(\n record.destinationChecks,\n \"manual destination checks\",\n refuseManualDefinition\n ).map((check, index) =>\n snapshotManualCheck(check, `manual destination check ${index}`)\n );\n return Object.freeze({\n transitions: Object.freeze(transitions),\n ...(destinationChecks === undefined\n ? {}\n : { destinationChecks: Object.freeze(destinationChecks) }),\n });\n}\n\nfunction snapshotManualTransition(\n value: unknown,\n label: string\n): ManualTransitionInput {\n const record = snapshotExactRecord(\n value,\n [\"from\", \"execution\", \"up\", \"originChecks\", \"rollback\"],\n label,\n refuseManualDefinition\n );\n const { from, execution } = record;\n if (from !== null && typeof from !== \"string\") {\n return refuseManualDefinition(`${label}.from must be a state id or null`);\n }\n if (execution !== \"transactional\" && execution !== \"stepwise\") {\n return refuseManualDefinition(\n `${label}.execution must be transactional or stepwise`\n );\n }\n const up = snapshotSqlArray(record.up, `${label}.up`);\n const originChecks =\n record.originChecks === undefined\n ? undefined\n : snapshotExactArray(\n record.originChecks,\n `${label}.originChecks`,\n refuseManualDefinition\n ).map((check, index) =>\n snapshotManualCheck(check, `${label}.originChecks[${index}]`)\n );\n return Object.freeze({\n from,\n execution,\n up,\n ...(originChecks === undefined\n ? {}\n : { originChecks: Object.freeze(originChecks) }),\n rollback: snapshotManualRollback(record.rollback, `${label}.rollback`),\n });\n}\n\nfunction snapshotManualRollback(\n value: unknown,\n label: string\n): ManualTransitionInput[\"rollback\"] {\n const discriminant = snapshotExactRecord(\n value,\n [\"kind\", \"execution\", \"sql\", \"reason\"],\n label,\n refuseManualDefinition\n );\n if (discriminant.kind === \"irreversible\") {\n if (\n discriminant.execution !== undefined ||\n discriminant.sql !== undefined ||\n typeof discriminant.reason !== \"string\"\n ) {\n return refuseManualDefinition(\n `${label} has an invalid irreversible shape`\n );\n }\n return Object.freeze({\n kind: \"irreversible\",\n reason: discriminant.reason,\n });\n }\n if (discriminant.kind !== \"manual\") {\n return refuseManualDefinition(`${label}.kind is invalid`);\n }\n if (\n discriminant.reason !== undefined ||\n (discriminant.execution !== \"transactional\" &&\n discriminant.execution !== \"stepwise\")\n ) {\n return refuseManualDefinition(`${label} has an invalid manual shape`);\n }\n return Object.freeze({\n kind: \"manual\",\n execution: discriminant.execution,\n sql: snapshotSqlArray(discriminant.sql, `${label}.sql`),\n });\n}\n\nfunction snapshotManualCheck(\n value: unknown,\n label: string\n): MigrationCheckInput {\n const record = snapshotExactRecord(\n value,\n [\"kind\", \"query\", \"equals\"],\n label,\n refuseManualDefinition\n );\n if (record.kind !== \"trusted-read\" || typeof record.equals !== \"boolean\") {\n return refuseManualDefinition(`${label} has an invalid check shape`);\n }\n return Object.freeze({\n kind: \"trusted-read\",\n query: snapshotSql(record.query, `${label}.query`),\n equals: record.equals,\n });\n}\n\nfunction snapshotSqlArray(value: unknown, label: string): readonly Sql[] {\n const entries = snapshotExactArray(value, label, refuseManualDefinition);\n const sql: Sql[] = [];\n for (let index = 0; index < entries.length; index++) {\n sql.push(snapshotSql(entries[index], `${label}[${index}]`));\n }\n return Object.freeze(sql);\n}\n\nfunction snapshotSql(value: unknown, label: string): Sql {\n try {\n if (!(value instanceof Sql)) {\n return refuseManualDefinition(`${label} must be a Sql value`);\n }\n const rawStrings: unknown = Reflect.get(value, \"strings\");\n const rawValues: unknown = Reflect.get(value, \"values\");\n if (!(Array.isArray(rawStrings) && Array.isArray(rawValues))) {\n return refuseManualDefinition(\n `${label}.strings and ${label}.values must be arrays`\n );\n }\n const strings = Array.from(rawStrings);\n const values = Array.from(rawValues);\n if (!strings.every((entry) => typeof entry === \"string\")) {\n return refuseManualDefinition(`${label}.strings must contain strings`);\n }\n if (strings.length !== values.length + 1) {\n return refuseManualDefinition(\n `${label} has an invalid strings and values shape`\n );\n }\n return new Sql(Object.freeze(strings), Object.freeze(values));\n } catch (failure) {\n return refuseManualDefinition(\n `${label} could not be read`,\n errorCause(failure)\n );\n }\n}\n\nfunction isResolveCallback(value: unknown): value is ResolveCallback {\n return typeof value === \"function\";\n}\n\nfunction refuseGenerateOptions(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n\nfunction refuseManualDefinition(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_ESTATE, {\n cause,\n });\n}\n","/** Immutable, non-executable migration graph projections for public tooling. */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { MigrationGraph } from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport type { MigrationTarget } from \"./types\";\nimport type {\n MigrationApprovalV1,\n MigrationBooleanCheckV1,\n MigrationDispatchV1,\n MigrationOperationV1,\n MigrationParentTransitionV1,\n MigrationStateManifestV1,\n} from \"./v1-types\";\n\nexport interface MigrationStateListItem {\n readonly stateId: Sha256;\n readonly name: string;\n}\n\nexport interface MigrationStateMetadata extends MigrationStateListItem {\n readonly snapshotHash: Sha256;\n readonly sqlHash: Sha256;\n readonly root: boolean;\n readonly leaf: boolean;\n}\n\nexport type MigrationRollbackMetadata =\n | {\n readonly kind: \"schema\" | \"manual\";\n readonly operationCount: number;\n readonly stepCount: number;\n }\n | {\n readonly kind: \"irreversible\";\n readonly reason: string;\n readonly operationCount: 0;\n readonly stepCount: 0;\n };\n\nexport interface MigrationEdgeMetadata {\n readonly fromState: Sha256 | null;\n readonly toState: Sha256;\n readonly transitionHash: Sha256;\n readonly requestedBoundary: \"transactional\" | \"stepwise\" | null;\n readonly operationCount: number;\n readonly stepCount: number;\n readonly origins: readonly (\"generated\" | \"manual\")[];\n readonly risks: readonly (\"safe\" | \"destructive\" | \"opaque\")[];\n /** The destructive changes approved at `generate`; empty when none was asked. */\n readonly approvals: readonly MigrationApprovalV1[];\n /** The existing tables this edge adopts without DDL; empty when none. */\n readonly adopts: readonly string[];\n readonly rollback: MigrationRollbackMetadata;\n}\n\nexport interface MigrationStateDetails extends MigrationStateMetadata {\n readonly incoming: readonly MigrationEdgeMetadata[];\n readonly outgoing: readonly MigrationEdgeMetadata[];\n}\n\nexport interface GraphResult {\n readonly estateHash: Sha256;\n readonly target: MigrationTarget;\n readonly roots: readonly Sha256[];\n readonly leaves: readonly Sha256[];\n readonly states: readonly MigrationStateMetadata[];\n readonly edges: readonly MigrationEdgeMetadata[];\n}\n\nexport type ListResult = readonly MigrationStateListItem[];\nexport type ShowResult = MigrationStateDetails;\n\nexport function listMigrationStates(graph: MigrationGraph): ListResult {\n return Object.freeze(\n sortedStates(graph).map((state) =>\n Object.freeze({ stateId: state.stateId, name: state.name })\n )\n );\n}\n\nexport function showMigrationState(\n graph: MigrationGraph,\n stateId: Sha256\n): ShowResult {\n const state = graph.states.get(stateId);\n if (!state) {\n throw new MigrationError(\n \"Resolved migration state is absent from its graph\",\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n const edges = graphEdges(graph);\n return Object.freeze({\n ...stateMetadata(graph, state),\n incoming: Object.freeze(edges.filter((edge) => edge.toState === stateId)),\n outgoing: Object.freeze(edges.filter((edge) => edge.fromState === stateId)),\n });\n}\n\nexport function migrationGraphResult(graph: MigrationGraph): GraphResult {\n return Object.freeze({\n estateHash: graph.estateHash,\n target: migrationTarget(graph.descriptor.target),\n roots: Object.freeze([...graph.roots].sort()),\n leaves: Object.freeze([...graph.leaves].sort()),\n states: Object.freeze(\n sortedStates(graph).map((state) => stateMetadata(graph, state))\n ),\n edges: graphEdges(graph),\n });\n}\n\nfunction sortedStates(graph: MigrationGraph): MigrationStateManifestV1[] {\n return [...graph.states.values()].sort((left, right) =>\n left.stateId.localeCompare(right.stateId)\n );\n}\n\nfunction stateMetadata(\n graph: MigrationGraph,\n state: MigrationStateManifestV1\n): MigrationStateMetadata {\n return Object.freeze({\n stateId: state.stateId,\n name: state.name,\n snapshotHash: state.snapshotHash,\n sqlHash: state.sqlHash,\n root: graph.roots.includes(state.stateId),\n leaf: graph.leaves.includes(state.stateId),\n });\n}\n\nfunction graphEdges(graph: MigrationGraph): readonly MigrationEdgeMetadata[] {\n const edges: MigrationEdgeMetadata[] = [];\n for (const state of sortedStates(graph)) {\n for (const transition of state.parents) {\n edges.push(edgeMetadata(state.stateId, transition));\n }\n }\n edges.sort((left, right) => {\n const from = (left.fromState ?? \"\").localeCompare(right.fromState ?? \"\");\n return from === 0 ? left.toState.localeCompare(right.toState) : from;\n });\n return Object.freeze(edges);\n}\n\nfunction edgeMetadata(\n toState: Sha256,\n transition: MigrationParentTransitionV1\n): MigrationEdgeMetadata {\n return Object.freeze({\n fromState: transition.fromState,\n toState,\n transitionHash: transition.transitionHash,\n requestedBoundary: transition.requestedForwardBoundary,\n operationCount: transition.operations.length,\n stepCount: stepCount(transition.operations),\n origins: uniqueOperationValues(transition.operations, \"origin\"),\n risks: uniqueOperationValues(transition.operations, \"risk\"),\n approvals: Object.freeze(\n (transition.approvals ?? []).map((approval) =>\n Object.freeze({ ...approval })\n )\n ),\n adopts: Object.freeze([...(transition.adopts ?? [])]),\n rollback: rollbackMetadata(transition),\n });\n}\n\nfunction rollbackMetadata(\n transition: MigrationParentTransitionV1\n): MigrationRollbackMetadata {\n if (transition.rollback.kind === \"irreversible\") {\n return Object.freeze({\n kind: transition.rollback.kind,\n reason: transition.rollback.reason,\n operationCount: 0,\n stepCount: 0,\n });\n }\n const operations = transition.rollback.operations;\n return Object.freeze({\n kind: transition.rollback.kind,\n operationCount: operations.length,\n stepCount: stepCount(operations),\n });\n}\n\nfunction stepCount(operations: readonly MigrationOperationV1[]): number {\n let count = 0;\n for (const operation of operations) count += operation.steps.length;\n return count;\n}\n\nfunction uniqueOperationValues<K extends \"origin\" | \"risk\">(\n operations: readonly MigrationOperationV1[],\n key: K\n): readonly MigrationOperationV1[K][] {\n const values: MigrationOperationV1[K][] = [];\n for (const operation of operations) {\n const value = operation[key];\n if (!values.includes(value)) values.push(value);\n }\n return Object.freeze(values);\n}\n\nfunction migrationTarget(target: MigrationTarget): MigrationTarget {\n return target.dialect === \"postgresql\"\n ? Object.freeze({ dialect: target.dialect, namespace: target.namespace })\n : Object.freeze({ dialect: target.dialect });\n}\n\nconst LINE_BREAKS = /[\\r\\n\\u2028\\u2029]/g;\nconst oneLine = (text: string) => text.replace(LINE_BREAKS, \" \");\n\n/**\n * A labelled read-only projection; dispatch offsets remain the execution authority.\n * `approvalLabel` names the approvals: a preview made without a resolver lists\n * the ones publishing will need, not ones given.\n */\nexport function renderMigrationReview(\n parents: readonly MigrationParentTransitionV1[],\n destinationChecks: readonly MigrationBooleanCheckV1[],\n blob: Uint8Array,\n approvalLabel = \"Approved at generate\"\n): string {\n const lines = [\n \"-- VibORM review: forward, checks and rollback are separate sections.\",\n \"-- Execute authenticated states with migrate apply/down; this review is not an apply script.\",\n ];\n const emit = (label: string, dispatch: MigrationDispatchV1) => {\n lines.push(`-- ${oneLine(label)}`, `${sliceDispatch(blob, dispatch)};`);\n if (dispatch.parameters.length > 0)\n lines.push(`-- Parameters: ${JSON.stringify(dispatch.parameters)}`);\n };\n const operations = (\n direction: string,\n values: readonly MigrationOperationV1[]\n ) => {\n for (const operation of values)\n for (const step of operation.steps) {\n if (step.retry === \"proven\")\n emit(`${direction} precheck ${operation.label}`, step.precheck.query);\n emit(`${direction} execute ${operation.label}`, step.execute);\n if (step.retry === \"proven\")\n emit(\n `${direction} postcheck ${operation.label}`,\n step.postcheck.query\n );\n }\n };\n for (const parent of parents) {\n lines.push(`\\n-- Parent ${parent.fromState ?? \"empty\"}`);\n for (const table of parent.adopts ?? [])\n lines.push(\n `-- Adopts existing table ${oneLine(table)}: no DDL; apply proves its live shape equals the declaration`\n );\n for (const { operation, table, column } of parent.approvals ?? [])\n lines.push(\n `-- ${approvalLabel}: ${oneLine(`${operation} ${table}${column === null ? \"\" : `.${column}`}`)}`\n );\n for (const check of parent.originChecks)\n emit(`Origin check ${check.id}`, check.query);\n operations(\"FORWARD\", parent.operations);\n if (parent.rollback.kind === \"irreversible\")\n lines.push(`-- ROLLBACK unavailable: ${oneLine(parent.rollback.reason)}`);\n else operations(\"ROLLBACK\", parent.rollback.operations);\n }\n for (const check of destinationChecks)\n emit(`Destination check ${check.id}`, check.query);\n return `${lines.join(\"\\n\\n\")}\\n`;\n}\n","import type { AmbiguousChange, DiffOperation } from \"../types\";\n\n/**\n * Formats an operation for human-readable display.\n */\nexport function formatOperation(op: DiffOperation): string {\n switch (op.type) {\n case \"createTable\":\n return `+ Create table \"${op.table.name}\" with ${op.table.columns.length} columns`;\n case \"dropTable\":\n return `- Drop table \"${op.tableName}\"`;\n case \"renameTable\":\n return `~ Rename table \"${op.from}\" → \"${op.to}\"`;\n case \"addColumn\":\n return `+ Add column \"${op.column.name}\" (${op.column.type}) to \"${op.tableName}\"`;\n case \"dropColumn\":\n return `- Drop column \"${op.columnName}\" from \"${op.tableName}\"`;\n case \"renameColumn\":\n return `~ Rename column \"${op.from}\" → \"${op.to}\" in \"${op.tableName}\"`;\n case \"alterColumn\":\n return `~ Alter column \"${op.columnName}\" in \"${op.tableName}\"`;\n case \"createIndex\":\n return `+ Create index \"${op.index.name}\" on \"${op.tableName}\"`;\n case \"dropIndex\":\n return `- Drop index \"${op.indexName}\"`;\n case \"addForeignKey\":\n return `+ Add foreign key \"${op.fk.name}\" to \"${op.tableName}\"`;\n case \"dropForeignKey\":\n return `- Drop foreign key \"${op.fkName}\" from \"${op.tableName}\"`;\n case \"addUniqueConstraint\":\n return `+ Add unique constraint \"${op.constraint.name}\" to \"${op.tableName}\"`;\n case \"dropUniqueConstraint\":\n return `- Drop unique constraint \"${op.constraintName}\" from \"${op.tableName}\"`;\n case \"addPrimaryKey\":\n return `+ Add primary key to \"${op.tableName}\"`;\n case \"dropPrimaryKey\":\n return `- Drop primary key \"${op.constraintName}\" from \"${op.tableName}\"`;\n case \"createView\":\n if (op.view.auto)\n return `+ Create auto view \"${op.view.name}\" on \"${op.view.auto.storage?.source ?? op.view.dependsOn[0]}\" (recomputes rows during migration)`;\n return op.view.materialized\n ? `+ Create materialized view \"${op.view.name}\" (computed by CREATE; readers wait until commit)`\n : `+ Create view \"${op.view.name}\"`;\n case \"dropView\":\n if (op.auto)\n return `- Drop view \"${op.viewName}\" kept by triggers, and its triggers`;\n return `- Drop ${op.materialized ? \"materialized \" : \"\"}view \"${op.viewName}\"`;\n case \"createEnum\":\n return `+ Create enum \"${op.enumDef.name}\" with values [${op.enumDef.values.join(\", \")}]`;\n case \"dropEnum\":\n return `- Drop enum \"${op.enumName}\"`;\n case \"alterEnum\": {\n const parts: string[] = [];\n if (op.addValues?.length) parts.push(`add: ${op.addValues.join(\", \")}`);\n if (op.removeValues?.length) {\n parts.push(`remove: ${op.removeValues.join(\", \")}`);\n }\n return `~ Alter enum \"${op.enumName}\" (${parts.join(\"; \")})`;\n }\n default:\n return `Unknown operation: ${getOperationType(op)}`;\n }\n}\n\nexport function formatDestructiveOperation(op: DiffOperation): string {\n switch (op.type) {\n case \"dropTable\":\n return `[destructive] Drop table \"${op.tableName}\"`;\n case \"dropColumn\":\n return `[destructive] Drop column \"${op.columnName}\" from \"${op.tableName}\"`;\n case \"addColumn\":\n return `[destructive] Add required column \"${op.tableName}.${op.column.name}\" without a backfill default`;\n case \"alterColumn\":\n return `[destructive] Alter column \"${op.columnName}\" in \"${op.tableName}\"`;\n default:\n return `[destructive] ${getOperationType(op)}`;\n }\n}\n\nexport function formatAmbiguousChangeDescription(\n change: AmbiguousChange\n): string {\n if (change.type === \"ambiguousColumn\") {\n return `[ambiguous] Column \"${change.droppedColumn.name}\" → \"${change.addedColumn.name}\" in \"${change.tableName}\"`;\n }\n return `[ambiguous] Table \"${change.droppedTable}\" → \"${change.addedTable}\"`;\n}\n\nfunction getOperationType(operation: { type: string }): string {\n return operation.type;\n}\n","import type { AnyDriver } from \"../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport type { ResolvedRelationIndex } from \"../../schema/validation/relation-resolution\";\nimport { admitLiveMigrationCapability } from \"../admission\";\nimport { getPushMigrationDriver, type MigrationClient } from \"../client-driver\";\nimport {\n type DiffOptions,\n diff,\n type IndexPredicateCanonicalizer,\n isDestructiveOperation,\n} from \"../differ\";\nimport type { MigrationDriver } from \"../drivers\";\nimport { emptyManagedSnapshot } from \"../empty-snapshot\";\nimport { applyNativeRename } from \"../native-rename\";\nimport {\n alwaysAddDropResolver,\n ambiguousDropKey,\n ambiguousToResolveChange,\n approveDestructiveOperations,\n resolveAmbiguousChanges,\n validateResolveResult,\n} from \"../resolver\";\nimport { serializeResolvedModels } from \"../serializer\";\nimport type {\n AmbiguousChange,\n ChangeResolution,\n DiffOperation,\n DiffResult,\n ResolveCallback,\n Resolver,\n SchemaSnapshot,\n} from \"../types\";\nimport { prepareSchemaProgram, sortOperations } from \"../utils\";\nimport {\n applyForceEnumResolutions,\n applyResolvedEnumMappings,\n detectEnumValueRemovals,\n type EnumRemoval,\n resolveEnumValueRemovalMappings,\n} from \"./enum-removals\";\nimport {\n formatAmbiguousChangeDescription,\n formatDestructiveOperation,\n} from \"./format\";\n\nexport { getPushMigrationDriver, type MigrationClient } from \"../client-driver\";\n\nexport interface PushOptions {\n /** Planner-only auto-resolution; public V1 push does not expose this key. */\n force?: boolean;\n /**\n * Skip schema validation before pushing. Validation catches definition\n * errors that would otherwise corrupt data silently (e.g. two relation\n * pairs sharing one junction table) — only skip it when deliberately\n * pushing a shape the validator flags.\n */\n skipValidation?: boolean;\n /** Preview SQL without executing */\n dryRun?: boolean;\n /**\n * Rebuild from the empty snapshot. Public V1 requires preview consent before\n * executing the resulting force-reset plan.\n */\n forceReset?: boolean;\n /**\n * Unified callback for resolving changes that require user input.\n * Called once per change, allowing granular control over each decision.\n *\n * Each change has methods for valid resolutions:\n * - Destructive: `change.proceed()`, `change.reject()`\n * - Ambiguous: `change.rename()`, `change.addAndDrop()`, `change.reject()`\n * - Enum value removal: `change.mapValues({...})`, `change.useNull()`, `change.reject()`\n *\n * A change the callback leaves undecided (returns `undefined`) refuses the\n * plan with MIGRATION_DESTRUCTIVE_REJECTED. Public `migrations.push()` has no\n * `force`; only the planner-internal `force` above turns an undecided change\n * into add+drop, acceptance or NULL.\n *\n * @example\n * ```ts\n * // Accept dropping a column, refuse everything else\n * await migrations.push({\n * dryRun: true,\n * resolve: async (change) => {\n * if (change.type === \"destructive\" && change.operation === \"dropColumn\") {\n * return change.proceed();\n * }\n * return change.reject();\n * },\n * });\n * ```\n */\n resolve?: ResolveCallback;\n}\n\n// Push deliberately carries NO storage owner. Ordinary push and force-reset\n// synchronize the live namespace and nothing else: they read no journal, write\n// no journal or snapshot, and cannot rewrite an estate's history as a side\n// effect of a schema sync.\n\nexport interface PushPlan {\n operations: DiffOperation[];\n currentSchema: SchemaSnapshot;\n}\n\n/**\n * Introspects the current database schema without making any changes.\n * Useful for debugging or displaying current state.\n *\n * It changes nothing, but it READS live state, so it is a live migration\n * command and takes the one shared admission owner like every other one —\n * before any provider work. Without this gate an unbound MySQL client would\n * publish an inventory of whatever database its connection happened to default\n * to, which is exactly the ambient-default target §3.3 refuses to accept.\n * `push({ dryRun: true })` performs the same introspection behind the same\n * `read-only` admission; this entry point must not be the way around it.\n */\nexport async function introspect(\n client: MigrationClient\n): Promise<SchemaSnapshot> {\n const migrationDriver = getPushMigrationDriver(client);\n admitLiveMigrationCapability(migrationDriver, \"read-only\", \"introspect()\");\n return introspectSchema(client.$driver, migrationDriver);\n}\n\nexport async function introspectSchema(\n driver: AnyDriver,\n migrationDriver: MigrationDriver\n): Promise<SchemaSnapshot> {\n return migrationDriver.introspect((sql, params) =>\n driver._executeRaw(sql, params)\n );\n}\n\n/**\n * Hands the differ a way to ask the database for its own spelling of a declared\n * partial-index predicate (Decision 7.4). Returns undefined when nobody can\n * answer, and the differ then compares the two texts raw — the reading that\n * plans a drop and a create, which is the safe direction.\n *\n * The whole canonicalization runs inside ONE transaction, for two reasons that\n * both matter: it pins a single connection (the scratch objects it needs exist\n * only inside their transaction, and a pool hands out a different connection\n * per statement), and a failure anywhere rolls the scratch away instead of\n * leaving it attached to a table this push may be about to drop.\n */\nfunction buildIndexPredicateCanonicalizer(\n driver: AnyDriver,\n migrationDriver: MigrationDriver\n): IndexPredicateCanonicalizer | undefined {\n const canonicalize = migrationDriver.canonicalizeIndexPredicates;\n if (!(canonicalize && driver.supportsTransactions)) return;\n\n return async (tableName, predicates) => {\n try {\n return await driver.withTransaction((tx) =>\n canonicalize.call(\n migrationDriver,\n tableName,\n predicates,\n (sql, params) => tx._executeRaw(sql, params)\n )\n );\n } catch {\n // Fail closed, and stay out of the way. A predicate the database cannot\n // parse, a connection that refused, a dialect that changed under us —\n // none of it may make a push fail, and none of it may be read as \"these\n // two predicates are the same\". Answering nothing leaves the differ with\n // the raw texts, which is exactly the pre-7.4 behavior.\n return predicates.map(() => undefined);\n }\n };\n}\n\n/**\n * The COMPLETE empty-to-desired program, compiled before a force-reset entry.\n *\n * §6.2: \"Before entry, serialize and validate the desired schema, resolve its\n * relation index, compile the empty-to-desired DDL, and prove that program\n * contains no commit-boundary statement.\" Diffing against the LIVE database\n * would describe a program for a database this command is about to empty, so\n * the baseline is the empty snapshot — the state the clear produces.\n *\n * Nothing here reads live state, so it runs before the clear and its result is\n * what the one locked transaction executes.\n */\nexport async function planRebuildFromEmpty(\n client: MigrationClient,\n migrationDriver: MigrationDriver,\n options: PushOptions,\n relations: ResolvedRelationIndex\n): Promise<PushPlan> {\n const desired = serializeResolvedModels(\n client.$schema,\n migrationDriver,\n relations\n );\n const current = emptyManagedSnapshot();\n const diffOptions: DiffOptions = {\n projectRename: migrationDriver.projectNativeRename.bind(migrationDriver),\n refuseConstraintNameChurn:\n migrationDriver.capabilities.introspectionReadsConstraintNames,\n matchConstraintsByShape:\n !migrationDriver.capabilities.introspectionReadsConstraintNames,\n };\n const diffResult = await diff(current, desired, diffOptions);\n const operations = await resolvePushOperations(\n diffResult,\n desired,\n current,\n options,\n diffOptions\n );\n\n return {\n operations: prepareSchemaProgram(\n operations,\n current,\n desired,\n migrationDriver\n ),\n currentSchema: current,\n };\n}\n\nexport async function planPush(\n client: MigrationClient,\n migrationDriver: MigrationDriver,\n options: PushOptions,\n relations: ResolvedRelationIndex\n): Promise<PushPlan> {\n const desired = serializeResolvedModels(\n client.$schema,\n migrationDriver,\n relations\n );\n // Live introspection sees the private columns and index, but a text\n // discriminator cannot reveal historical public/stored member mappings.\n // Push therefore compares structure only. Stored-value history is owned by\n // file-based generate(), where both serialized snapshots are available.\n const current = withDeclaredViews(\n withDeclaredRawTemplates(\n await introspectSchema(client.$driver, migrationDriver),\n desired\n ),\n desired\n );\n const diffOptions: DiffOptions = {\n projectRename: migrationDriver.projectNativeRename.bind(migrationDriver),\n canonicalizeIndexPredicate: buildIndexPredicateCanonicalizer(\n client.$driver,\n migrationDriver\n ),\n // `current` was just introspected. Where that introspection cannot read a\n // constraint's name back, the name it carries is a synthesis and matching\n // on it would make every unchanged constraint read as a change.\n refuseConstraintNameChurn:\n migrationDriver.capabilities.introspectionReadsConstraintNames,\n matchConstraintsByShape:\n !migrationDriver.capabilities.introspectionReadsConstraintNames,\n };\n const diffResult = await diff(current, desired, diffOptions);\n const operations = await resolvePushOperations(\n diffResult,\n desired,\n current,\n options,\n diffOptions\n );\n\n return {\n operations: prepareSchemaProgram(\n operations,\n current,\n desired,\n migrationDriver\n ),\n currentSchema: current,\n };\n}\n\n/**\n * The live raw indexes with the templates the schema declares for them. A\n * database holds a raw index's rendered text and its marker, never the\n * template, and a statement that re-creates the index as it is (a SQLite table\n * rebuild, a SurrealDB table moved under a new name) renders that template. A\n * template is the declared one when its index has the same name and hash.\n */\nfunction withDeclaredRawTemplates(\n current: SchemaSnapshot,\n desired: SchemaSnapshot\n): SchemaSnapshot {\n const templates = new Map<string, string>();\n for (const table of desired.tables)\n for (const index of table.indexes)\n if (index.raw?.template !== undefined)\n templates.set(`${index.name}\\0${index.raw.hash}`, index.raw.template);\n if (templates.size === 0) return current;\n return {\n ...current,\n tables: current.tables.map((table) => ({\n ...table,\n indexes: table.indexes.map((index) => {\n if (!index.raw) return index;\n const { hash } = index.raw;\n const template = templates.get(`${index.name}\\0${hash}`);\n return template === undefined\n ? index\n : { ...index, raw: { hash, template } };\n }),\n })),\n };\n}\n\n/**\n * The live views with the definitions the schema declares for them. A\n * database holds a view's rewritten text and its marker, never the body it\n * was given, and MySQL and SQLite do not say what a view reads; a view whose\n * name and hash are declared is the declared one, body and reads included.\n * What the database holds stays the database's: a materialized view's indexes\n * are compared as they are.\n */\nfunction withDeclaredViews(\n current: SchemaSnapshot,\n desired: SchemaSnapshot\n): SchemaSnapshot {\n if (current.views === undefined || desired.views === undefined)\n return current;\n const declared = new Map(\n desired.views.map((view) => [`${view.name}\\0${view.hash}`, view])\n );\n return {\n ...current,\n views: current.views.map((view) => {\n const kept = declared.get(`${view.name}\\0${view.hash}`);\n const { sql, dependsOn } = kept ?? view;\n // A view kept by triggers keeps the objects the database holds, and\n // takes how it is stored from its declaration.\n const storage = kept?.auto?.storage;\n return {\n ...view,\n sql,\n dependsOn,\n ...(view.auto && storage ? { auto: { ...view.auto, storage } } : {}),\n };\n }),\n };\n}\n\nasync function resolvePushOperations(\n diffResult: DiffResult,\n desired: SchemaSnapshot,\n current: SchemaSnapshot,\n options: PushOptions,\n diffOptions: DiffOptions\n): Promise<DiffOperation[]> {\n const force = options.force ?? false;\n const allEnumRemovals = detectEnumValueRemovals(\n diffResult.operations,\n current\n );\n\n if (options.resolve) {\n return resolveWithCallback(\n diffResult,\n current,\n desired,\n diffOptions,\n allEnumRemovals,\n options.resolve,\n force\n );\n }\n\n if (force) {\n const resolvedOperations = await resolveAmbiguousChanges(\n diffResult,\n current,\n desired,\n alwaysAddDropResolver,\n diffOptions\n );\n return applyForceEnumResolutions(resolvedOperations, allEnumRemovals);\n }\n\n rejectUnresolvedChanges(diffResult, allEnumRemovals);\n return [...diffResult.operations];\n}\n\nasync function resolveWithCallback(\n diffResult: DiffResult,\n current: SchemaSnapshot,\n desired: SchemaSnapshot,\n diffOptions: DiffOptions,\n enumRemovals: EnumRemoval[],\n resolve: ResolveCallback,\n force = false\n): Promise<DiffOperation[]> {\n const admittedAmbiguousDrops = new Set<string>();\n const ambiguityResolver: Resolver = async (changes) => {\n const resolutions = new Map<AmbiguousChange, ChangeResolution>();\n for (const change of changes) {\n const resolveChange = ambiguousToResolveChange(change);\n const result = validateResolveResult(\n \"ambiguous\",\n resolveChange,\n await resolve(resolveChange)\n );\n\n if (result === \"reject\") {\n throw new MigrationError(\n `Change rejected: ${resolveChange.description}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n if (result === undefined) {\n if (force) {\n resolutions.set(change, { type: \"addAndDrop\" });\n admittedAmbiguousDrops.add(ambiguousDropKey(change));\n continue;\n }\n const advice =\n change.type === \"ambiguousTable\"\n ? `Exclude \"${change.droppedTable}\" via migrations.tables or return change.rename() / change.addAndDrop().`\n : \"Return change.rename() or change.addAndDrop().\";\n throw new MigrationError(\n `Unresolved ambiguous change: ${resolveChange.description}\\n${advice}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n resolutions.set(change, {\n type: result === \"rename\" ? \"rename\" : \"addAndDrop\",\n });\n if (result !== \"rename\") {\n admittedAmbiguousDrops.add(ambiguousDropKey(change));\n }\n }\n return resolutions;\n };\n\n const resolvedOperations = await resolveAmbiguousChanges(\n diffResult,\n current,\n desired,\n ambiguityResolver,\n diffOptions\n );\n const resolvedEnumRemovals = retargetEnumRemovals(\n enumRemovals,\n current,\n resolvedOperations,\n diffOptions.projectRename\n );\n await approveDestructiveOperations(\n resolvedOperations,\n resolve,\n force,\n admittedAmbiguousDrops\n );\n const finalOperations: DiffOperation[] = resolvedOperations.filter(\n (op) => op.type !== \"alterEnum\"\n );\n const enumColumnMappings = await resolveEnumValueRemovalMappings(\n resolvedEnumRemovals,\n resolve,\n force\n );\n\n finalOperations.push(\n ...applyResolvedEnumMappings(resolvedOperations, enumColumnMappings)\n );\n\n return sortOperations(finalOperations);\n}\n\nfunction retargetEnumRemovals(\n removals: EnumRemoval[],\n current: SchemaSnapshot,\n operations: DiffOperation[],\n projectRename: typeof applyNativeRename = applyNativeRename\n): EnumRemoval[] {\n let renamedCurrent = current;\n for (const operation of operations) {\n if (operation.type === \"renameTable\" || operation.type === \"renameColumn\") {\n renamedCurrent = projectRename(renamedCurrent, operation);\n }\n }\n\n return removals.map((removal) => {\n const tablePosition = current.tables.findIndex(\n (table) => table.name === removal.tableName\n );\n const currentTable = current.tables[tablePosition];\n const columnPosition = currentTable?.columns.findIndex(\n (column) => column.name === removal.columnName\n );\n const table = renamedCurrent.tables[tablePosition];\n const column =\n columnPosition === undefined ? undefined : table?.columns[columnPosition];\n if (!(currentTable && table && column)) {\n throw new MigrationError(\n `Cannot retarget enum removal for \"${removal.tableName}.${removal.columnName}\" through the accepted renames.`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n return { ...removal, tableName: table.name, columnName: column.name };\n });\n}\n\nfunction rejectUnresolvedChanges(\n diffResult: {\n operations: DiffOperation[];\n ambiguousChanges: AmbiguousChange[];\n },\n enumRemovalsNeedingResolution: EnumRemoval[]\n): void {\n const destructiveOps = diffResult.operations.filter(isDestructiveOperation);\n const hasAmbiguous = diffResult.ambiguousChanges.length > 0;\n\n if (\n destructiveOps.length === 0 &&\n !hasAmbiguous &&\n enumRemovalsNeedingResolution.length === 0\n ) {\n return;\n }\n\n const descriptions: string[] = [];\n\n for (const op of destructiveOps) {\n descriptions.push(formatDestructiveOperation(op));\n }\n\n for (const change of diffResult.ambiguousChanges) {\n descriptions.push(formatAmbiguousChangeDescription(change));\n }\n\n for (const removal of enumRemovalsNeedingResolution) {\n descriptions.push(\n `[enumValueRemoval] \"${removal.tableName}.${removal.columnName}\" uses enum \"${removal.enumName}\" - removing values: ${removal.removedValues.join(\", \")} (non-nullable)`\n );\n }\n\n throw new MigrationError(\n `Changes require resolution:\\n${descriptions.join(\"\\n\")}\\n\\nProvide a resolve callback.`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n}\n","/**\n * Hostile admission for push options and inert consent.\n *\n * Consent is not authority. A forged or stale value can only refuse\n * execution. Apply replans under the lock and compares this closed shape.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { canonicalizeJsonText } from \"./canonical-json\";\nimport { isSha256, type Sha256 } from \"./identity\";\nimport { snapshotExactArray, snapshotExactRecord } from \"./input-boundary\";\nimport { freezeDeep } from \"./push-fingerprint\";\nimport type { ResolveCallback } from \"./types\";\nimport { ks } from \"./v1-parse-shared\";\nimport type {\n PushConsent,\n PushResolution,\n PushTargetIdentity,\n} from \"./v1-types\";\n\ninterface ConsentedPlan {\n readonly mode: PushConsent[\"mode\"];\n readonly validation: PushConsent[\"validation\"];\n readonly target: PushTargetIdentity;\n readonly sourceFingerprint: Sha256;\n readonly planHash: Sha256;\n readonly resolutions: readonly PushResolution[];\n}\n\nexport interface ParsedPlanningOptions {\n readonly forceReset: boolean;\n readonly skipValidation: boolean;\n readonly resolve: ResolveCallback | undefined;\n readonly dryRun: boolean;\n}\n\nconst PLAN_KEYS = ks(\"dryRun forceReset resolve skipValidation\");\nconst PUSH_KEYS = [\"consent\", ...PLAN_KEYS];\nconst CONSENT_KEYS = ks(\"format mode planHash resolutions target validation\");\nconst TARGET_KEYS = ks(\"database dialect location namespace\");\n\nexport function snapshotPushOptions(\n value: unknown\n): Readonly<Record<string, unknown>> {\n return snapshotExactRecord(value, PUSH_KEYS, \"push options\", invalidOptions);\n}\n\nexport function parsePlanningOptions(\n value: unknown,\n dryRun: boolean\n): ParsedPlanningOptions {\n return parseSnapshottedPlanningOptions(\n snapshotExactRecord(value, PLAN_KEYS, \"push options\", invalidOptions),\n dryRun\n );\n}\n\nexport function parseSnapshottedPlanningOptions(\n record: Readonly<Record<string, unknown>>,\n dryRun: boolean\n): ParsedPlanningOptions {\n for (const key of ks(\"dryRun forceReset skipValidation\")) {\n if (record[key] !== undefined && typeof record[key] !== \"boolean\")\n invalidOptions(`push options.${key} must be boolean`);\n }\n const candidate = record.resolve;\n if (candidate !== undefined && typeof candidate !== \"function\")\n invalidOptions(\"push options.resolve must be a function\");\n const resolve: ResolveCallback | undefined =\n typeof candidate === \"function\"\n ? (change) => Reflect.apply(candidate, undefined, [change])\n : undefined;\n return {\n dryRun: dryRun || record.dryRun === true,\n forceReset: record.forceReset === true,\n skipValidation: record.skipValidation === true,\n resolve,\n };\n}\n\nexport function parseConsent(value: unknown): PushConsent {\n const record = snapshotExactRecord(\n value,\n CONSENT_KEYS,\n \"push consent\",\n consentMismatch\n );\n if (record.format !== \"1\") consentMismatch(\"consent.format must be 1\");\n if (record.mode !== \"diff\" && record.mode !== \"force-reset\")\n consentMismatch(\"consent.mode invalid\");\n if (record.validation !== \"full\" && record.validation !== \"structural-only\")\n consentMismatch(\"consent.validation invalid\");\n if (!isSha256(record.planHash)) consentMismatch(\"consent.planHash invalid\");\n const resolutionEntries = snapshotExactArray(\n record.resolutions,\n \"consent.resolutions\",\n consentMismatch\n );\n const resolutions = resolutionEntries.map((resolution, index) => {\n const item = snapshotExactRecord(\n resolution,\n ks(\"decision id\"),\n `consent.resolutions[${index}]`,\n consentMismatch\n );\n if (typeof item.id !== \"string\" || typeof item.decision !== \"string\")\n consentMismatch(`consent.resolutions[${index}] invalid`);\n return { id: item.id, decision: item.decision };\n });\n return freezeDeep({\n format: \"1\",\n target: parseTarget(record.target),\n planHash: record.planHash,\n mode: record.mode,\n validation: record.validation,\n resolutions,\n });\n}\n\nexport function assertAcceptedPlan(\n accepted: ConsentedPlan,\n locked: ConsentedPlan\n): void {\n if (\n accepted.sourceFingerprint !== locked.sourceFingerprint ||\n accepted.planHash !== locked.planHash\n ) {\n throw new MigrationError(\n \"The live push plan changed before the locked replan\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH,\n {\n meta: {\n expectedChecksum: accepted.planHash,\n actualChecksum: locked.planHash,\n planHash: locked.planHash,\n expectedFingerprint: accepted.sourceFingerprint,\n actualFingerprint: locked.sourceFingerprint,\n },\n }\n );\n }\n}\n\nexport function assertConsent(consent: PushConsent, plan: ConsentedPlan): void {\n const targetMatches =\n canonicalizeJsonText(consent.target) === canonicalizeJsonText(plan.target);\n const resolutionsMatch =\n canonicalizeJsonText(consent.resolutions) ===\n canonicalizeJsonText(plan.resolutions);\n if (\n consent.mode !== plan.mode ||\n consent.validation !== plan.validation ||\n !targetMatches ||\n !resolutionsMatch ||\n consent.planHash !== plan.planHash\n ) {\n throw new MigrationError(\n \"Push consent does not match the locked live plan\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH,\n {\n meta: {\n expectedChecksum: consent.planHash,\n actualChecksum: plan.planHash,\n planHash: plan.planHash,\n fingerprint: plan.sourceFingerprint,\n },\n }\n );\n }\n}\n\nexport function hasConsent(\n options: Readonly<Record<string, unknown>>\n): options is Readonly<Record<string, unknown>> & {\n readonly consent: unknown;\n} {\n return \"consent\" in options;\n}\n\nfunction parseTarget(value: unknown): PushTargetIdentity {\n const record = snapshotExactRecord(\n value,\n TARGET_KEYS,\n \"consent.target\",\n consentMismatch\n );\n if (record.dialect === \"postgresql\") {\n refuseTargetKeys(record, ks(\"database dialect namespace\"));\n return {\n dialect: \"postgresql\",\n database: requiredString(record.database, \"consent.target.database\"),\n namespace: requiredString(record.namespace, \"consent.target.namespace\"),\n };\n }\n if (record.dialect === \"mysql\" || record.dialect === \"surrealql\") {\n refuseTargetKeys(record, ks(\"database dialect\"));\n return {\n dialect: record.dialect,\n database: requiredString(record.database, \"consent.target.database\"),\n };\n }\n if (record.dialect === \"sqlite\") {\n refuseTargetKeys(record, ks(\"dialect location\"));\n if (record.location !== null && typeof record.location !== \"string\")\n consentMismatch(\"consent.target.location invalid\");\n return { dialect: \"sqlite\", location: record.location };\n }\n consentMismatch(\"consent.target.dialect invalid\");\n}\n\nfunction refuseTargetKeys(\n target: Readonly<Record<string, unknown>>,\n allowed: readonly string[]\n): void {\n for (const key of Object.keys(target)) {\n if (!allowed.includes(key)) {\n consentMismatch(`consent.target contains unknown key ${key}`);\n }\n }\n}\n\nfunction requiredString(value: unknown, label: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n consentMismatch(`${label} must be a non-empty string`);\n }\n return value;\n}\n\nfunction invalidOptions(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n\nfunction consentMismatch(message: string, cause?: Error): never {\n throw new MigrationError(\n message,\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH,\n {\n cause,\n }\n );\n}\n","/**\n * The ONE live-namespace reset owner (§6.2).\n *\n * Three programs used to invent reset SQL: the CLI's own dynamic loop, the\n * dialect drivers' `generateResetSQL()`, and `push({ forceReset: true })`. They\n * disagreed — MySQL's dialect answer dropped nothing at all, and PostgreSQL's\n * enumerated `public` regardless of the estate — so this module replaces all\n * three. Migration `reset()` and force-reset push both keep the migration\n * control pair: a clear drops neither table.\n *\n * Containment is the point: the inventory is a bound catalog read scoped to the\n * configured namespace, foreign keys inside it are dropped explicitly rather\n * than cascaded away, and nothing here issues `DROP SCHEMA`, `DROP DATABASE`,\n * or `FOREIGN_KEY_CHECKS = 0`.\n *\n * {@link planLiveNamespaceReset} decides and renders the whole clear from\n * catalog reads, before the first effect. Every refusal lives there, so no\n * caller's commit-model reporter can restate a containment refusal as a failure\n * part-way through a program that never began.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport { CONTROL_TABLES } from \"./control\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { childrenBeforeParents, type TableReference } from \"./drop-order\";\nimport { introspectSchema } from \"./push/planner\";\nimport type { ForeignKeyDef, SchemaSnapshot } from \"./types\";\nimport { createQueryExecutor } from \"./utils\";\nimport { dropViewOperation, orderViews } from \"./view\";\n\n/** One table or view this reset drops, and the statement that drops it. */\ninterface PlannedTableDrop {\n readonly name: string;\n readonly sql: string;\n /** A materialized view, which its probes read as its own kind. */\n readonly materialized?: boolean;\n /**\n * A view kept by triggers: a table, which its probes read as one, and the\n * statements that drop what keeps it first (each skips what is gone).\n */\n readonly keepers?: readonly string[];\n /** What is left of one whose table a hand dropped: its keepers alone. */\n readonly tableless?: boolean;\n}\n\n/**\n * The COMPLETE clear, decided and rendered — and nothing executed.\n *\n * The split is the point (§6.2). Everything that can REFUSE the clear —\n * proving the namespace, reading the inventory, both containment refusals, the\n * drop order — is answered from catalog reads, so it belongs before the caller\n * enters a commit model at all. A refusal that has already been wrapped in\n * MySQL's partial-commit reporter tells the caller a database nothing touched\n * \"failed partway through\", and loses the metadata naming the constraint that\n * made it refuse.\n */\nexport interface LiveNamespaceResetPlan {\n /**\n * The views VibORM created in the estate, dependents first: they go before\n * anything they read (PostgreSQL drops a table without CASCADE).\n */\n readonly dropViews: readonly PlannedTableDrop[];\n /**\n * Every foreign key the estate owns, as an explicit drop, or SQLite's one\n * deferral of them all ({@link clearForeignKeys}).\n */\n readonly dropForeignKeys: string[];\n /** The tables this reset drops, in the order they will be dropped. */\n readonly dropTables: readonly PlannedTableDrop[];\n /** Managed enum drops, which run after the tables that use them. */\n readonly dropEnums: string[];\n /** The whole clear, in the order it runs: views, keys, tables, enums. */\n readonly clear: readonly string[];\n}\n\nexport interface LiveNamespaceInventory {\n /** The estate's dependency graph, as the catalog describes it. */\n readonly snapshot: SchemaSnapshot;\n /** Every table in the configured namespace. */\n readonly tables: string[];\n /** Every managed enum type, on dialects that have them. */\n readonly enums: string[];\n}\n\n/**\n * Proves the configured namespace and reads what a reset would touch.\n *\n * ONE owner for both consumers — the effectful reset and the dry run that\n * previews it — because a preview computed a different way is not a preview.\n * `introspect` is what proves the namespace exists before anything is\n * published, and it refuses a foreign key with exactly one side inside the\n * estate, so a cross-namespace dependency is refused BEFORE the first DDL\n * rather than discovered after half the estate is gone.\n *\n * The snapshot describes the GRAPH; the bound catalog read decides MEMBERSHIP,\n * because a table the snapshot cannot model is still a table in this namespace\n * and a reset that skipped it would leave the estate half-cleared. For the same\n * reason the membership read is the one provider result this owner refuses to\n * treat as advisory: see {@link readNames}.\n */\nexport async function inventoryLiveNamespace(\n driver: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<LiveNamespaceInventory> {\n const snapshot = await introspectSchema(driver, migrationDriver);\n\n const executor = createQueryExecutor(driver);\n const inventory = migrationDriver.generateInventoryTables();\n const tables = readNames(\n await executor(inventory.sql, inventory.params),\n \"table\"\n ).filter(\n (name) =>\n migrationDriver.target.tables === undefined ||\n migrationDriver.target.tables.includes(name)\n );\n\n const enumInventory = migrationDriver.generateInventoryEnums();\n const enums = enumInventory\n ? readNames(\n await executor(enumInventory.sql, enumInventory.params),\n \"managed enum\"\n )\n : [];\n\n return {\n snapshot,\n tables,\n enums:\n migrationDriver.target.tables === undefined\n ? enums\n : enums.filter((name) =>\n snapshot.enums?.some((item) => item.name === name)\n ),\n };\n}\n\n/**\n * Decides and renders the COMPLETE clear, without executing any of it.\n *\n * Namespace proof, inventory, both containment refusals, foreign-key\n * materialization and drop order all happen here, so every way this clear can\n * refuse is answered from catalog reads alone — before the caller enters a\n * transaction or a sequential program, and therefore before anything can\n * describe a refusal as a partial commit (§6.2). It is also what lets a dry run\n * preview the effectful path rather than a second computation of it.\n *\n * @param driver - the producer to read the catalog on; the caller has already\n * pinned and locked it where its dialect has a lock to take\n * @param migrationDriver - the estate-bound migration driver\n */\nexport async function planLiveNamespaceReset(\n driver: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<LiveNamespaceResetPlan> {\n const { snapshot, tables, enums } = await inventoryLiveNamespace(\n driver,\n migrationDriver\n );\n\n // MySQL is the one dialect whose DDL commits as it runs, and it cannot make\n // the tracking clear and the destructive DDL one transaction — so an inbound\n // foreign key to the declared tracking table has no safe order: dropping that\n // key first opens a window where the history rows are still there and their\n // schema is going away, and clearing or dropping the referenced table first\n // can simply be blocked.\n if (migrationDriver.target.dialect === \"mysql\") {\n assertNoInboundTrackingReference(snapshot, CONTROL_TABLES.state);\n }\n\n // The views VibORM marked go first, each before what it reads. A view\n // without the marker is not in the snapshot, and RESTRICT keeps it.\n const views = snapshot.views ?? [];\n const byName = new Map(views.map((view) => [view.name, view]));\n const dropViews: PlannedTableDrop[] = orderViews(\n new Set(byName.keys()),\n views,\n true\n ).map((name) => {\n const view = byName.get(name)!;\n const statements = migrationDriver.compileStatements(\n dropViewOperation(view),\n { destination: \"live\" }\n );\n if (view.auto?.tableless)\n return { name, sql: \"\", keepers: statements, tableless: true };\n return {\n name,\n materialized: view.materialized === true,\n sql: statements.at(-1)!,\n ...(view.auto ? { keepers: statements.slice(0, -1) } : {}),\n };\n });\n\n // Drop every foreign key the estate owns, explicitly, before any table\n // drop. This is what replaces `CASCADE` and `FOREIGN_KEY_CHECKS = 0`:\n // cycles and mutually-dropped tables are handled, and a dependency this\n // inventory does NOT represent aborts the operation instead of being\n // deleted with it.\n const dropForeignKeys = clearForeignKeys(\n migrationDriver,\n ownedForeignKeys(snapshot, tables)\n );\n\n // The control pair survives every clear: its structure is the history.\n const droppable = tables.filter(\n (name) => name !== CONTROL_TABLES.state && name !== CONTROL_TABLES.log\n );\n\n const dropTables: PlannedTableDrop[] = [];\n for (const table of dependencySafeOrder(droppable, snapshot)) {\n dropTables.push({\n name: table,\n sql: migrationDriver.generateDropTableSQL(table),\n });\n }\n\n // Managed enums go after their tables: a type still used by a column is\n // a dependency, and `RESTRICT` is the point.\n const dropEnums: string[] = [];\n for (const enumName of enums) {\n const statement = migrationDriver.generateDropEnumSQL(enumName);\n if (statement) {\n dropEnums.push(statement);\n }\n }\n\n return {\n dropViews,\n dropForeignKeys,\n dropTables,\n dropEnums,\n clear: [\n ...dropViews.flatMap((view) => [\n ...(view.keepers ?? []),\n ...(view.tableless ? [] : [view.sql]),\n ]),\n ...dropForeignKeys,\n ...dropTables.map((table) => table.sql),\n ...dropEnums,\n ],\n };\n}\n\n/**\n * The statements that take the owned keys out of the way of the table drops.\n *\n * A dialect that keeps keys inline in `CREATE TABLE` (SQLite) cannot drop one\n * short of rebuilding its table, and its `DROP TABLE` checks the keys of every\n * row it removes, which a cycle or a self-referencing `RESTRICT` fails in any\n * order. There one statement defers every key to the COMMIT, by which point\n * each table holding one is gone.\n */\nfunction clearForeignKeys(\n migrationDriver: BoundMigrationDriver,\n owned: Iterable<{ table: string; foreignKey: ForeignKeyDef }>\n): string[] {\n const statements: string[] = [];\n for (const { table, foreignKey } of owned) {\n if (!migrationDriver.capabilities.supportsAddForeignKeyViaAlter) {\n return [\"PRAGMA defer_foreign_keys = ON\"];\n }\n statements.push(\n migrationDriver.generateDDL(\n { type: \"dropForeignKey\", tableName: table, fkName: foreignKey.name },\n { destination: \"live\" }\n )\n );\n }\n return statements;\n}\n\n/** Every foreign key owned by a table this reset is about to drop. */\nfunction* ownedForeignKeys(\n snapshot: SchemaSnapshot,\n tables: readonly string[]\n): Generator<{ table: string; foreignKey: ForeignKeyDef }> {\n const inventoried = new Set(tables);\n for (const table of snapshot.tables) {\n if (!inventoried.has(table.name)) {\n continue;\n }\n for (const foreignKey of table.foreignKeys) {\n yield { table: table.name, foreignKey };\n }\n }\n}\n\n/**\n * Children before parents, with a stable fallback for cycles.\n *\n * Every foreign key inside the estate has already been dropped by the time\n * these run, so the order is defence rather than necessity: it keeps a\n * constraint the inventory could not see from turning a reset into a failure\n * that has already dropped half the estate. A cycle's keys are already\n * dropped too, so its tables go in inventory order rather than deadlocking.\n */\nfunction dependencySafeOrder(\n tables: readonly string[],\n snapshot: SchemaSnapshot\n): string[] {\n const references: TableReference[] = [];\n for (const table of snapshot.tables) {\n for (const foreignKey of table.foreignKeys) {\n if (foreignKey.referencedTable !== table.name) {\n references.push({ from: table.name, to: foreignKey.referencedTable });\n }\n }\n }\n const { ordered, blocked } = childrenBeforeParents(\n tables,\n (name) => name,\n references\n );\n return [...ordered, ...blocked];\n}\n\n/** Refuses an inbound foreign key to the declared tracking table. */\nfunction assertNoInboundTrackingReference(\n snapshot: SchemaSnapshot,\n trackingTableName: string\n): void {\n for (const table of snapshot.tables) {\n for (const foreignKey of table.foreignKeys) {\n if (foreignKey.referencedTable !== trackingTableName) {\n continue;\n }\n throw new MigrationError(\n `Table \"${table.name}\" FK \"${foreignKey.name}\" references tracking table \"${trackingTableName}\"; drop it first.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n table: table.name,\n constraint: foreignKey.name,\n referencedTable: trackingTableName,\n },\n }\n );\n }\n }\n}\n\nconst UNTRUSTED_INVENTORY = \"Untrusted reset inventory.\";\n\nfunction readNames(rows: readonly unknown[], inventory: string): string[] {\n const names: string[] = [];\n const seen = new Set<string>();\n for (const [index, row] of rows.entries()) {\n const name = readName(row, index, inventory);\n if (seen.has(name)) {\n throw new MigrationError(\n `Reset ${inventory} inventory repeated \"${name}\" at ${index}. ${UNTRUSTED_INVENTORY}`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: { type: \"duplicate-reset-inventory-name\", resultIndex: index },\n }\n );\n }\n seen.add(name);\n names.push(name);\n }\n return names;\n}\n\n/** The one object an inventory row names, or the refusal it earns. */\nfunction readName(row: unknown, index: number, inventory: string): string {\n const refuse = (reason: string, cause?: Error): MigrationError =>\n new MigrationError(\n `Reset ${inventory} row ${index} invalid: ${reason}. ${UNTRUSTED_INVENTORY}`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n cause,\n meta: { type: \"unreadable-reset-inventory\", resultIndex: index },\n }\n );\n\n // The executor's contract is `unknown[]`, so this is where a provider row\n // becomes an object at all. A driver's own result contract already refuses a\n // non-object row (`drivers/normalized-result.ts`), which is why no falsifier\n // reaches this line through a driver; what it decides is that the answer for\n // a row from anywhere else is a refusal rather than a shorter drop list.\n if (typeof row !== \"object\" || row === null) {\n throw refuse(`the row is ${row === null ? \"null\" : `a ${typeof row}`}`);\n }\n\n let name: unknown;\n try {\n // Reading a column off a provider's row runs the provider's code, and its\n // failure is still this inventory refusing to be read.\n //\n // OWN properties only, because this inventory names objects a CATALOG\n // reported and a catalog reports columns: a `name` reached through the\n // prototype chain is a carrier's property or `Object.prototype` pollution,\n // and honouring one puts an object on the DROP LIST that no catalog ever\n // named. Asking whether the row owns the column runs the provider's code\n // too — a proxy answers that with a trap — so the ownership test shares\n // this `try` and refuses identically. It is not a second read of the value:\n // it consults the descriptor, not the getter.\n name = Object.hasOwn(row, \"name\") ? Reflect.get(row, \"name\") : undefined;\n } catch (failure) {\n throw refuse(\"reading its `name` threw\", errorCause(failure));\n }\n\n if (typeof name !== \"string\") {\n throw refuse(\n `its \\`name\\` is ${name === undefined ? \"not a column of the row\" : `a ${typeof name}`}`\n );\n }\n // An empty name renders as a quoted nothing, so the statement it would\n // produce does not drop the object the provider meant to report.\n if (name.length === 0) {\n throw refuse(\"its `name` is the empty string\");\n }\n return name;\n}\n","/**\n * One SQL blob builder. Every check and effect dispatch in a state shares\n * one content-addressed blob. No second blob for rollback.\n */\n\nimport type { Sha256 } from \"./identity\";\nimport { composeSqlBlob, refuseMysqlDelimiter } from \"./sql-blob\";\nimport { encodeDispatchIdentity } from \"./v1-parse\";\nimport type { MigrationDispatchV1, MigrationParameterV1 } from \"./v1-types\";\n\ninterface PendingFragment {\n readonly text: string;\n readonly parameters: readonly MigrationParameterV1[];\n}\n\nexport class SqlAssembly {\n private readonly pending: PendingFragment[] = [];\n\n add(text: string, parameters: readonly MigrationParameterV1[] = []): number {\n refuseMysqlDelimiter(text);\n this.pending.push({ text, parameters });\n return this.pending.length - 1;\n }\n\n seal(): {\n readonly bytes: Uint8Array;\n readonly sqlHash: Sha256;\n readonly dispatches: readonly MigrationDispatchV1[];\n } {\n const blob = composeSqlBlob(this.pending.map((fragment) => fragment.text));\n const dispatches = this.pending.map((fragment, index) => {\n const range = blob.ranges[index]!;\n return {\n dispatchId: encodeDispatchIdentity(\n blob.sqlHash,\n range.offset,\n range.length,\n fragment.parameters\n ),\n sqlHash: blob.sqlHash,\n offset: range.offset,\n length: range.length,\n parameters: fragment.parameters,\n };\n });\n return { bytes: blob.bytes, sqlHash: blob.sqlHash, dispatches };\n }\n}\n","import { errorCause } from \"../errors/diagnostic-safety\";\nimport { isDestructiveOperation } from \"./differ\";\nimport { formatOperation } from \"./push/format\";\n/**\n * History-free push plan: live diff or force-reset rebuild, compiled\n * statements, and plan hash. This module does not execute SQL.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { ResolvedRelationIndex } from \"../schema/validation/relation-resolution\";\nimport { isRecord } from \"../validation/value-guards\";\nimport { canonicalizeJson, canonicalizeJsonText } from \"./canonical-json\";\nimport { classifyGeneratedAtomicity, dispatchAt } from \"./compile\";\nimport { introspectManaged, withoutControlTables } from \"./introspect-managed\";\n\nexport { introspectManaged } from \"./introspect-managed\";\n\nimport type {\n BoundMigrationDriver,\n DDLContext,\n MigrationDriver,\n} from \"./drivers\";\nimport { emptyManagedSnapshot } from \"./empty-snapshot\";\nimport { domainHash, HASH_DOMAIN, type Sha256 } from \"./identity\";\nimport {\n type LiveNamespaceResetPlan,\n planLiveNamespaceReset,\n} from \"./live-reset\";\nimport {\n type MigrationClient,\n type PushOptions as PlannerPushOptions,\n planPush,\n planRebuildFromEmpty,\n} from \"./push/planner\";\nimport type { ParsedPlanningOptions } from \"./push-consent\";\nimport {\n canonicalValue,\n fingerprintLive,\n freezeDeep,\n hashSnapshot,\n pushTargetIdentity,\n} from \"./push-fingerprint\";\nimport { serializeResolvedModels } from \"./serializer\";\nimport { SqlAssembly } from \"./sql-assembly\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport {\n type DiffOperation,\n type ResolveCallback,\n type ResolveChange,\n type ResolveResult,\n readEnumResolutionDecision,\n type SchemaSnapshot,\n} from \"./types\";\nimport type {\n AtomicityClass,\n MigrationDispatchV1,\n PushConsent,\n PushOperation,\n PushResolution,\n PushStatementPreview,\n PushTargetIdentity,\n} from \"./v1-types\";\n\nexport interface PlannedStatement {\n readonly kind: \"clear\" | \"effect\";\n readonly operationId: string;\n /** The index of the operation it is part of, in `operations`; none for a clear. */\n readonly operation?: number | undefined;\n readonly dispatch: MigrationDispatchV1;\n}\n\nexport interface InternalPushPlan {\n readonly mode: PushConsent[\"mode\"];\n readonly validation: PushConsent[\"validation\"];\n readonly target: PushTargetIdentity;\n readonly sourceFingerprint: Sha256;\n readonly desiredFingerprint: Sha256;\n readonly desiredSchema: SchemaSnapshot;\n readonly schemaHash: Sha256;\n readonly planHash: Sha256;\n readonly resolutions: readonly PushResolution[];\n readonly operations: readonly DiffOperation[];\n readonly reportedOperations: readonly PushOperation[];\n readonly statements: readonly PlannedStatement[];\n readonly previewStatements: readonly PushStatementPreview[];\n readonly sqlBlob: Uint8Array;\n readonly atomicity: AtomicityClass;\n readonly destructive: boolean;\n}\n\ntype ResolutionSource =\n | {\n readonly kind: \"record\";\n readonly callback: ResolveCallback | undefined;\n }\n | {\n readonly kind: \"replay\";\n readonly resolutions: readonly PushResolution[];\n };\n\ninterface ResolutionController {\n readonly callback: ResolveCallback;\n finish(): readonly PushResolution[];\n}\n\nexport async function buildPushPlan(\n client: MigrationClient,\n producer: AnyDriver,\n command: BoundMigrationDriver,\n relations: ResolvedRelationIndex,\n options: ParsedPlanningOptions,\n resolutionSource: ResolutionSource\n): Promise<InternalPushPlan> {\n const controller = resolutionController(resolutionSource);\n const plannerOptions: PlannerPushOptions = {\n skipValidation: options.skipValidation,\n resolve: controller.callback,\n };\n const planningDriver = managedPlanningDriver(command);\n const desired = serializeResolvedModels(\n client.$schema,\n planningDriver,\n relations\n );\n // The declared views wait for the live tables: a table this push manages\n // is its to replace by a view of the same name, which only the managed\n // snapshot says (below).\n const { views: declaredViews, ...declaredTables } = desired;\n await command.preflightSchemaRequirements(\n [declaredTables],\n (sql, params) => producer._executeRaw(sql, params),\n []\n );\n const mode: PushConsent[\"mode\"] = options.forceReset ? \"force-reset\" : \"diff\";\n\n let reset: LiveNamespaceResetPlan | undefined;\n let current: SchemaSnapshot;\n let operations: readonly DiffOperation[];\n if (options.forceReset) {\n current = await introspectManaged(producer, command);\n reset = await planLiveNamespaceReset(producer, command);\n const rebuild = await planRebuildFromEmpty(\n { $driver: producer, $schema: client.$schema },\n planningDriver,\n plannerOptions,\n relations\n );\n operations = rebuild.operations;\n } else {\n const planned = await planPush(\n { $driver: producer, $schema: client.$schema },\n planningDriver,\n plannerOptions,\n relations\n );\n current = planned.currentSchema;\n operations = await withEnumDependentChecks(\n producer,\n command,\n planned.operations\n );\n }\n if (declaredViews !== undefined)\n await command.preflightSchemaRequirements(\n [\n desired,\n // Its tables by name alone: a requirement is the declared schema's.\n {\n ...emptyManagedSnapshot(),\n tables: current.tables.map(({ name }) => ({\n name,\n columns: [],\n indexes: [],\n foreignKeys: [],\n uniqueConstraints: [],\n })),\n },\n ],\n (sql, params) => producer._executeRaw(sql, params),\n []\n );\n if (!options.forceReset)\n for (const operation of operations) {\n if (\n operation.type !== \"addColumn\" ||\n operation.column.nullable ||\n operation.column.default !== undefined ||\n operation.column.autoIncrement\n )\n continue;\n const tableName = liveTableName(operations, operation.tableName);\n if (!current.tables.some((table) => table.name === tableName)) continue;\n if (await command.tableHoldsRows(producer, tableName))\n throw new MigrationError(\n `Cannot add required \"${operation.tableName}.${operation.column.name}\" without default to populated table; add nullable, backfill, then SET NOT NULL.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n table: operation.tableName,\n column: operation.column.name,\n command: \"push\",\n hint: \"Backfill before making column required.\",\n },\n }\n );\n }\n if (!options.forceReset)\n await refuseOrphanedDiscriminators(\n producer,\n command,\n desired,\n current,\n operations\n );\n const resolutions = controller.finish();\n const target = await pushTargetIdentity(producer, command);\n const sourceFingerprint = await fingerprintLive(current, command, producer);\n const desiredFingerprint = await fingerprintLive(desired, command, producer);\n const schemaHash = hashSnapshot(desired);\n const compiled = compilePlanStatements(\n reset,\n operations,\n planningDriver,\n options.forceReset ? emptyManagedSnapshot() : current\n );\n await command.preflightSchemaRequirements(\n [],\n (sql, params) => producer._executeRaw(sql, params),\n compiled.statements.map((statement) =>\n sliceDispatch(compiled.bytes, statement.dispatch)\n ),\n // On Neki each statement commits alone.\n true\n );\n const reportedOperations: PushOperation[] = operations.map(\n (operation, index) => ({\n id: `${operation.type}:${index}`,\n label: formatOperation(operation),\n // A live table rename takes its old name from every other reader, and a\n // history-free push cannot prove that table was ever this schema's.\n risk:\n isDestructiveOperation(operation) || operation.type === \"renameTable\"\n ? \"destructive\"\n : \"safe\",\n })\n );\n const atomicity = classifyGeneratedAtomicity(command, operations, !!reset);\n const destructive =\n mode === \"force-reset\" ||\n reportedOperations.some((operation) => operation.risk === \"destructive\");\n const validation: PushConsent[\"validation\"] = options.skipValidation\n ? \"structural-only\"\n : \"full\";\n const planHash = hashPushPlan({\n mode,\n validation,\n target,\n sourceFingerprint,\n desiredFingerprint,\n schemaHash,\n resolutions,\n operations,\n statements: compiled.statements,\n atomicity,\n });\n\n return freezeDeep({\n mode,\n validation,\n target,\n sourceFingerprint,\n desiredFingerprint,\n desiredSchema: desired,\n schemaHash,\n planHash,\n resolutions,\n operations,\n reportedOperations,\n statements: compiled.statements,\n previewStatements: compiled.statements.map((statement) => ({\n sql: sliceDispatch(compiled.bytes, statement.dispatch),\n parameters: statement.dispatch.parameters,\n })),\n sqlBlob: compiled.bytes,\n atomicity,\n destructive,\n });\n}\n\nexport function compilePlanStatements(\n reset: LiveNamespaceResetPlan | undefined,\n operations: readonly DiffOperation[],\n driver: MigrationDriver,\n currentSchema: SchemaSnapshot\n): {\n readonly bytes: Uint8Array;\n readonly statements: readonly PlannedStatement[];\n} {\n const assembly = new SqlAssembly();\n const pending: Array<{\n readonly kind: PlannedStatement[\"kind\"];\n readonly operationId: string;\n readonly operation?: number;\n readonly index: number;\n }> = [];\n\n for (const [index, sql] of (reset?.clear ?? []).entries()) {\n pending.push({\n kind: \"clear\",\n operationId: `force-reset:clear:${index}`,\n index: assembly.add(sql),\n });\n }\n\n for (const [operationIndex, operation] of operations.entries()) {\n const context: DDLContext = {\n destination: \"live\",\n currentSchema,\n precedingOperations: operations.slice(0, operationIndex),\n followingOperations: operations.slice(operationIndex + 1),\n };\n const statements = driver.compileStatements(operation, context);\n for (const [statementIndex, sql] of statements.entries()) {\n pending.push({\n kind: \"effect\",\n operationId: `${operation.type}:${operationIndex}:${statementIndex}`,\n operation: operationIndex,\n index: assembly.add(sql),\n });\n }\n }\n\n const sealed = assembly.seal();\n return {\n bytes: sealed.bytes,\n statements: pending.map((statement) => ({\n kind: statement.kind,\n operationId: statement.operationId,\n operation: statement.operation,\n dispatch: dispatchAt(sealed.dispatches, statement.index),\n })),\n };\n}\n\nexport function hashPushPlan(input: {\n readonly mode: PushConsent[\"mode\"];\n readonly validation: PushConsent[\"validation\"];\n readonly target: PushTargetIdentity;\n readonly sourceFingerprint: Sha256;\n readonly desiredFingerprint: Sha256;\n readonly schemaHash: Sha256;\n readonly resolutions: readonly PushResolution[];\n readonly operations: readonly DiffOperation[];\n readonly statements: readonly PlannedStatement[];\n readonly atomicity: AtomicityClass;\n}): Sha256 {\n return domainHash(\n HASH_DOMAIN.plan,\n canonicalizeJson(\n canonicalValue({\n mode: input.mode,\n validation: input.validation,\n target: input.target,\n sourceFingerprint: input.sourceFingerprint,\n desiredFingerprint: input.desiredFingerprint,\n schemaHash: input.schemaHash,\n resolutions: input.resolutions,\n operations: input.operations,\n atomicity: input.atomicity,\n // Review SQL is intentionally absent. Dispatch identity authenticates\n // the sealed statement bytes, exact ranges, and typed parameters.\n statements: input.statements.map((statement) => ({\n kind: statement.kind,\n operationId: statement.operationId,\n dispatch: statement.dispatch,\n })),\n })\n )\n );\n}\n\nfunction managedPlanningDriver(\n driver: BoundMigrationDriver\n): BoundMigrationDriver {\n const managed: BoundMigrationDriver = Object.create(driver);\n Object.defineProperty(managed, \"introspect\", {\n value: async (\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ) => withoutControlTables(await driver.introspect(executeRaw)),\n });\n Object.freeze(managed);\n return managed;\n}\n\n/**\n * A schema snapshot models no CHECK constraint, so the ones on the columns an\n * enum change converts are read from the live catalog here and closed into its\n * operation: the preview shows their DROP and ADD, the plan hash covers them,\n * and the locked replan reads them again, so one added or changed after the\n * preview refuses its consent.\n */\nasync function withEnumDependentChecks(\n producer: AnyDriver,\n command: BoundMigrationDriver,\n operations: readonly DiffOperation[]\n): Promise<readonly DiffOperation[]> {\n const enumNames = operations.flatMap((operation) =>\n operation.type === \"alterEnum\" && operation.dependentColumns\n ? [operation.enumName]\n : []\n );\n if (!command.readEnumDependentChecks || enumNames.length === 0)\n return operations;\n const checks = await command.readEnumDependentChecks(\n enumNames,\n (sql, params) => producer._executeRaw(sql, params)\n );\n return operations.map((operation) => {\n if (operation.type !== \"alterEnum\") return operation;\n const dependentChecks = checks.flatMap(({ enumName, ...check }) =>\n enumName === operation.enumName ? [check] : []\n );\n return dependentChecks.length === 0\n ? operation\n : { ...operation, dependentChecks };\n });\n}\n\n/** The live name of a desired table: an accepted rename still reads the old one. */\nfunction liveTableName(\n operations: readonly DiffOperation[],\n tableName: string\n): string {\n const rename = operations.find(\n (candidate) =>\n candidate.type === \"renameTable\" && candidate.to === tableName\n );\n return rename?.type === \"renameTable\" ? rename.from : tableName;\n}\n\n/**\n * Push keeps no polymorphic history — `diff` refuses a stored-value change only\n * between authored snapshots — so the stored discriminators are that history:\n * a row whose discriminator the desired schema no longer declares would be\n * orphaned. Only a to-one slot stores its discriminator in rows; a collection\n * member's junction table is the member itself.\n */\nasync function refuseOrphanedDiscriminators(\n producer: AnyDriver,\n command: BoundMigrationDriver,\n desired: SchemaSnapshot,\n current: SchemaSnapshot,\n operations: readonly DiffOperation[]\n): Promise<void> {\n for (const slot of desired.polymorphicStorage ?? []) {\n if (slot.kind !== \"toOne\") continue;\n const tableName = liveTableName(operations, slot.ownerTable);\n const rename = operations.find(\n (candidate) =>\n candidate.type === \"renameColumn\" &&\n candidate.tableName === slot.ownerTable &&\n candidate.to === slot.storageRef\n );\n const columnName =\n rename?.type === \"renameColumn\" ? rename.from : slot.storageRef;\n const live = current.tables.find((table) => table.name === tableName);\n if (!live?.columns.some((column) => column.name === columnName)) continue;\n const orphan = await command.undeclaredValue(\n producer,\n tableName,\n columnName,\n slot.members.map((member) => member.storedType)\n );\n if (orphan)\n throw new MigrationError(\n `Polymorphic \"${slot.ownerTable}.${slot.relation}\" stores undeclared \"${String(orphan.stored)}\"; author a manual transition.`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED,\n {\n meta: {\n table: slot.ownerTable,\n relation: slot.relation,\n command: \"push\",\n },\n }\n );\n }\n}\n\nconst consentMismatch = (message: string, cause?: unknown) =>\n new MigrationError(\n message,\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH,\n cause === undefined ? undefined : { cause: errorCause(cause) }\n );\n\nfunction resolutionController(source: ResolutionSource): ResolutionController {\n if (source.kind === \"record\") {\n const recorded: PushResolution[] = [];\n return {\n callback: async (change) => {\n const result = source.callback\n ? await source.callback(change)\n : defaultResolution(change);\n const decision = closeResolution(change, result);\n if (decision) {\n recorded.push({ id: resolutionId(change), decision });\n }\n return result;\n },\n finish: () => freezeDeep([...recorded]),\n };\n }\n\n let cursor = 0;\n return {\n callback: (change) => {\n const expected = source.resolutions[cursor++];\n if (!expected || expected.id !== resolutionId(change)) {\n throw consentMismatch(\"Locked push requested different resolutions\");\n }\n return replayResolution(change, expected.decision);\n },\n finish: () => {\n if (cursor !== source.resolutions.length) {\n throw consentMismatch(\n \"Locked push no longer requests all consented resolutions\"\n );\n }\n return source.resolutions;\n },\n };\n}\n\nfunction defaultResolution(change: ResolveChange): ResolveResult | undefined {\n // Destructive operations have one interpretation. Closing `proceed` lets a\n // preview describe it, while exact plan consent remains mandatory.\n if (change.type === \"destructive\") return change.proceed();\n return undefined;\n}\n\nfunction closeResolution(\n change: ResolveChange,\n result: ResolveResult | undefined | void\n): string | undefined {\n if (result === undefined) return undefined;\n if (result === \"reject\") return \"reject\";\n if (change.type === \"destructive\") {\n if (result !== \"proceed\") invalidResolution(change);\n return \"proceed\";\n }\n if (change.type === \"ambiguous\") {\n if (result !== \"rename\" && result !== \"addAndDrop\") {\n invalidResolution(change);\n }\n return result;\n }\n if (result !== \"enumMapped\") invalidResolution(change);\n const decision = readEnumResolutionDecision(change);\n if (decision?.kind === \"mapValues\") {\n return `map:${canonicalizeJsonText(canonicalValue(decision.mappings))}`;\n }\n if (decision?.kind === \"useNull\") {\n if (!change.isNullable) {\n throw new MigrationError(\n \"A non-nullable enum column cannot resolve removed values to NULL\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n return \"useNull\";\n }\n invalidResolution(change);\n}\n\nfunction invalidResolution(change: ResolveChange): never {\n throw new MigrationError(\n `Invalid resolution for ${change.type} change; use change helper method.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { type: \"invalid-resolution-result\" } }\n );\n}\n\nfunction replayResolution(\n change: ResolveChange,\n decision: string\n): ResolveResult {\n if (change.type === \"destructive\" && decision === \"proceed\") {\n return change.proceed();\n }\n if (change.type === \"ambiguous\") {\n if (decision === \"rename\") return change.rename();\n if (decision === \"addAndDrop\") return change.addAndDrop();\n }\n if (change.type === \"enumValueRemoval\") {\n if (decision === \"useNull\" && change.isNullable) return change.useNull();\n if (decision.startsWith(\"map:\")) {\n return change.mapValues(parseResolutionMap(decision.slice(4)));\n }\n }\n throw consentMismatch(\"Push consent resolution invalid for locked request\");\n}\n\nfunction resolutionId(change: ResolveChange): string {\n const identity =\n change.type === \"enumValueRemoval\"\n ? {\n type: change.type,\n enumName: change.enumName,\n tableName: change.tableName,\n columnName: change.columnName,\n isNullable: change.isNullable,\n removedValues: change.removedValues,\n availableValues: change.availableValues,\n }\n : {\n type: change.type,\n operation: change.operation,\n table: change.table,\n column: change.column ?? null,\n oldName:\n change.type === \"ambiguous\" ? (change.oldName ?? null) : null,\n newName:\n change.type === \"ambiguous\" ? (change.newName ?? null) : null,\n oldType:\n change.type === \"ambiguous\" ? (change.oldType ?? null) : null,\n newType:\n change.type === \"ambiguous\" ? (change.newType ?? null) : null,\n };\n return domainHash(HASH_DOMAIN.plan, canonicalizeJson(identity));\n}\n\nfunction parseResolutionMap(text: string): Record<string, string | null> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (cause) {\n throw consentMismatch(\"Malformed enum resolution in push consent\", cause);\n }\n if (!isRecord(parsed) || canonicalizeJsonText(parsed) !== text) {\n throw consentMismatch(\"Non-canonical enum resolution in push consent\");\n }\n const result: Record<string, string | null> = {};\n for (const [key, value] of Object.entries(parsed)) {\n if (typeof value !== \"string\" && value !== null) {\n throw consentMismatch(\"Enum mappings must contain only strings or null\");\n }\n result[key] = value;\n }\n return result;\n}\n","/**\n * Authenticated, history-free push.\n *\n * A preview exposes review text and inert consent. The executable program stays\n * private, is rebuilt from the live catalog under the target lock, and is\n * dispatched only through the structured-statement compiler.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { hydrateSchemaNames } from \"../schema/hydration\";\nimport type { ResolvedRelationIndex } from \"../schema/validation/relation-resolution\";\nimport { allRules } from \"../schema/validation/rules\";\nimport {\n resolveSchemaOrThrow,\n validateResolvedSchemaOrThrow,\n} from \"../schema/validation/validator\";\nimport { admitLiveMigrationCapability } from \"./admission\";\nimport { canonicalizeJson } from \"./canonical-json\";\nimport { refuseIncompatibleHistory, unfinishedAttempts } from \"./control\";\nimport { diff } from \"./differ\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport {\n executeDispatch,\n executeDispatchGroup,\n rerunsRefusedCommits,\n} from \"./execute-dispatch\";\nimport { domainHash, HASH_DOMAIN, type Sha256 } from \"./identity\";\nimport {\n resolveCommandDriver,\n runProgram,\n withLockedMigrationProducer,\n} from \"./pinned-session\";\nimport { getPushMigrationDriver, type MigrationClient } from \"./push/planner\";\nimport {\n assertAcceptedPlan,\n assertConsent,\n hasConsent,\n parseConsent,\n parsePlanningOptions,\n parseSnapshottedPlanningOptions,\n snapshotPushOptions,\n} from \"./push-consent\";\nimport { fingerprintLive, freezeDeep } from \"./push-fingerprint\";\nimport {\n buildPushPlan,\n type InternalPushPlan,\n introspectManaged,\n} from \"./push-plan\";\nimport { readCommandControl } from \"./resume\";\nimport { assertMigrationDecimalDomainsFitProvider } from \"./serializer\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport type { DiffOperation } from \"./types\";\nimport type {\n PushApplyResult as BasePushApplyResult,\n PushPreview as BasePushPreview,\n ExactPushOptions,\n MigrationDispatchV1,\n PushConsent,\n PushOptionsV1,\n PushPlanningOptions,\n} from \"./v1-types\";\n\nexport type {\n ExactPushOptions,\n PushConsent,\n PushOperation,\n PushOptionsV1,\n PushOptionsV1 as PushOptions,\n PushPlanningOptions,\n PushResolution,\n PushStatementPreview,\n PushTargetIdentity,\n} from \"./v1-types\";\n\nexport interface PushAttestation {\n readonly pathHash: Sha256;\n readonly planHash: Sha256;\n readonly schemaHash: Sha256;\n readonly fingerprint: Sha256;\n}\n\nexport interface PushApplyResult extends BasePushApplyResult {\n readonly attestation: PushAttestation;\n}\n\nexport interface PushPreview extends BasePushPreview {\n readonly schemaHash: Sha256;\n readonly fingerprint: Sha256;\n}\n\nexport type PushResultFor<O> = [O] extends [{ readonly dryRun: true }]\n ? PushPreview\n : PushApplyResult;\n\n/**\n * Effect-free planning. It does not acquire a lock and never receives estate\n * storage. A force reset plans the empty-to-target rebuild rather than diffing\n * the desired schema from the live schema.\n */\nexport async function previewPush(\n client: MigrationClient,\n options: PushPlanningOptions = {}\n): Promise<PushPreview> {\n const parsed = parsePlanningOptions(options, true);\n const { relations, driver } = prepareSchema(client, parsed.skipValidation);\n admitLiveMigrationCapability(\n driver,\n \"read-only\",\n parsed.forceReset ? \"push({ forceReset: true })\" : \"push()\"\n );\n const command = await resolveCommandDriver(client.$driver, driver);\n const plan = await buildPushPlan(\n client,\n client.$driver,\n command,\n relations,\n parsed,\n { kind: \"record\", callback: parsed.resolve }\n );\n return publicPreview(plan);\n}\n\n/**\n * Replans and executes on one pinned producer under the target lock.\n *\n * Generic force is deliberately absent. Destructive diff work and every\n * force-reset plan require exact preview consent.\n */\nexport function pushV1<O extends PushOptionsV1>(\n client: MigrationClient,\n options?: ExactPushOptions<O>\n): Promise<PushResultFor<O>>;\nexport async function pushV1(\n client: MigrationClient,\n options?: PushOptionsV1\n): Promise<PushApplyResult | PushPreview> {\n const given = snapshotPushOptions(options ?? {});\n if (hasConsent(given)) {\n return applyWithConsent(client, parseConsent(given.consent));\n }\n\n const parsed = parseSnapshottedPlanningOptions(given, given.dryRun === true);\n if (parsed.dryRun) {\n return previewPush(client, parsed);\n }\n\n const { relations, driver } = prepareSchema(client, parsed.skipValidation);\n\n // A resolver may perform arbitrary user work. Run it only during an unlocked\n // read-only plan, then close its normalized answers for the locked replan.\n let accepted: InternalPushPlan | undefined;\n if (parsed.resolve) {\n admitLiveMigrationCapability(driver, \"read-only\", \"push()\");\n const command = await resolveCommandDriver(client.$driver, driver);\n accepted = await buildPushPlan(\n client,\n client.$driver,\n command,\n relations,\n parsed,\n { kind: \"record\", callback: parsed.resolve }\n );\n }\n\n admitLiveMigrationCapability(\n driver,\n \"effectful\",\n parsed.forceReset ? \"push({ forceReset: true })\" : \"push()\"\n );\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const plan = await buildPushPlan(\n client,\n pinned,\n command,\n relations,\n parsed,\n accepted\n ? { kind: \"replay\", resolutions: accepted.resolutions }\n : { kind: \"record\", callback: undefined }\n );\n if (accepted) assertAcceptedPlan(accepted, plan);\n await assertPushControlInterlock(pinned, command, plan);\n if (plan.destructive) {\n throw new MigrationError(\n \"Destructive or force-reset push requires consent from push({ dryRun: true }).\",\n VibORMErrorCode.MIGRATION_CONSENT_REQUIRED,\n {\n meta: {\n command: \"push\",\n dialect: plan.target.dialect,\n expectedChecksum: plan.planHash,\n expectedStatementCount: plan.statements.length,\n hint: \"Pass consent from push({ dryRun: true }) to push({ consent }).\",\n },\n }\n );\n }\n return executeLockedPlan(pinned, command, plan);\n }\n );\n}\n\nasync function applyWithConsent(\n client: MigrationClient,\n consent: PushConsent\n): Promise<PushApplyResult> {\n const skipValidation = consent.validation === \"structural-only\";\n const { relations, driver } = prepareSchema(client, skipValidation);\n admitLiveMigrationCapability(\n driver,\n \"effectful\",\n consent.mode === \"force-reset\"\n ? \"push({ consent: forceResetPreview.consent })\"\n : \"push({ consent })\"\n );\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const plan = await buildPushPlan(\n client,\n pinned,\n command,\n relations,\n {\n forceReset: consent.mode === \"force-reset\",\n skipValidation,\n resolve: undefined,\n dryRun: false,\n },\n { kind: \"replay\", resolutions: consent.resolutions }\n );\n assertConsent(consent, plan);\n await assertPushControlInterlock(pinned, command, plan);\n return executeLockedPlan(pinned, command, plan);\n }\n );\n}\n\nasync function executeLockedPlan(\n pinned: AnyDriver,\n command: BoundMigrationDriver,\n plan: InternalPushPlan\n): Promise<PushApplyResult> {\n // A plan with nothing to do still has a MySQL sequential program to run: the\n // interrupted-decimal-conversion recovery belongs to the LOCKED COMMAND, not\n // to having statements. A conversion interrupted after its MODIFY leaves the\n // column already carrying the target domain, so the differ sees no change\n // and the plan is empty — and the remnant CHECK, which no snapshot\n // vocabulary describes, would then survive every later push while refusing\n // values the declared domain admits.\n if (plan.statements.length === 0 && command.target.dialect !== \"mysql\") {\n return appliedResult(plan, plan.sourceFingerprint, \"noop\");\n }\n\n // A driver that makes one transaction of a batch, and runs it again when\n // refused at its commit (SurrealDB), creates new tables one operation per\n // transaction, each one request: a transaction around a whole schema stays\n // open for a round trip per statement, which the server refuses at its\n // commit the more often the longer it ran (SurrealDB Cloud). Part of such a\n // program leaves the operations before the one that failed, which the next\n // push, planning from them, completes; any other program keeps its one\n // transaction.\n const grouped =\n plan.atomicity === \"transactional\" &&\n createsTablesOnly(plan.operations) &&\n rerunsRefusedCommits(pinned)\n ? pinned\n : undefined;\n // In a transaction the destination is proven before its COMMIT, and the\n // lifted foreign-key bracket runs around it (its pragmas, sent again\n // inside, are no-ops there); otherwise once the statements ran — on MySQL\n // after its sequential program.\n const fingerprint = await runProgram(\n pinned,\n command,\n {\n transactional: plan.atomicity === \"transactional\" && !grouped,\n statements: plan.statements.map((statement) =>\n sliceDispatch(plan.sqlBlob, statement.dispatch)\n ),\n },\n async (producer, atomic) => {\n // Each statement alone or, grouped, each operation's statements\n // together: they are contiguous, and each names its operation.\n const groups: MigrationDispatchV1[][] = [];\n for (const [\n index,\n { operation, dispatch },\n ] of plan.statements.entries()) {\n if (grouped && operation === plan.statements[index - 1]?.operation)\n groups.at(-1)!.push(dispatch);\n else groups.push([dispatch]);\n }\n for (const group of groups) {\n await (grouped\n ? executeDispatchGroup(\n grouped,\n plan.sqlBlob,\n group,\n command.namespace\n )\n : executeDispatch(\n producer,\n plan.sqlBlob,\n group[0]!,\n command.namespace\n ));\n }\n return atomic ? attestFinalFingerprint(producer, command, plan) : null;\n }\n );\n if (plan.statements.length === 0) {\n return appliedResult(plan, plan.sourceFingerprint, \"noop\");\n }\n return appliedResult(\n plan,\n fingerprint ?? (await attestFinalFingerprint(pinned, command, plan)),\n \"applied\"\n );\n}\n\n/**\n * Whether `operations` create tables, and references to them, and touch\n * nothing else. A reference to a table created after its own waits for it in\n * an operation of its own (`extractForwardReferenceForeignKeys`), whose table\n * a push stopped between the two has already created.\n */\nfunction createsTablesOnly(operations: readonly DiffOperation[]): boolean {\n const created = new Set(\n operations.flatMap((operation) =>\n operation.type === \"createTable\" ? [operation.table.name] : []\n )\n );\n return operations.every(\n (operation) =>\n operation.type === \"createTable\" ||\n (operation.type === \"addForeignKey\" &&\n created.has(operation.fk.referencedTable))\n );\n}\n\nasync function attestFinalFingerprint(\n producer: AnyDriver,\n command: BoundMigrationDriver,\n plan: InternalPushPlan\n): Promise<Sha256> {\n const finalSnapshot = await introspectManaged(producer, command);\n const fingerprint = await fingerprintLive(finalSnapshot, command, producer);\n const expected = await fingerprintLive(plan.desiredSchema, command, producer);\n if (fingerprint !== expected) {\n throw new MigrationError(\n `Push final live fingerprint drifted from desired schema: ${JSON.stringify(await diff(finalSnapshot, plan.desiredSchema))}`,\n VibORMErrorCode.MIGRATION_DRIFT,\n {\n meta: {\n planHash: plan.planHash,\n schemaHash: plan.schemaHash,\n fingerprint,\n },\n }\n );\n }\n return fingerprint;\n}\n\nfunction appliedResult(\n plan: InternalPushPlan,\n fingerprint: Sha256,\n outcome: PushApplyResult[\"outcome\"]\n): PushApplyResult {\n const pathHash = domainHash(\n HASH_DOMAIN.path,\n canonicalizeJson({\n target: plan.target,\n sourceFingerprint: plan.sourceFingerprint,\n fingerprint,\n planHash: plan.planHash,\n schemaHash: plan.schemaHash,\n })\n );\n return freezeDeep({\n outcome,\n target: plan.target,\n planHash: plan.planHash,\n operations: plan.reportedOperations,\n statements: plan.previewStatements,\n attestation: {\n pathHash,\n planHash: plan.planHash,\n schemaHash: plan.schemaHash,\n fingerprint,\n },\n });\n}\n\nasync function assertPushControlInterlock(\n producer: AnyDriver,\n command: BoundMigrationDriver,\n plan: InternalPushPlan\n): Promise<void> {\n // A driver holding its own lock keeps no control tables to interlock with.\n if (command.holdLock) return;\n const control = await readCommandControl(producer, command);\n if (control.presence.kind !== \"present\") return;\n const { marker, ledger } = control;\n if (unfinishedAttempts(ledger).length > 0) {\n throw new MigrationError(\n \"An unfinished migration attempt is blocking push\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n }\n refuseIncompatibleHistory(marker, ledger);\n if (!marker) {\n return;\n }\n if (plan.operations.length > 0 || plan.mode === \"force-reset\") {\n throw new MigrationError(\n \"Non-empty push against migration marker refused; use generate/apply or reset.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { planHash: plan.planHash } }\n );\n }\n if (\n marker.snapshotHash !== plan.schemaHash ||\n plan.sourceFingerprint !== plan.desiredFingerprint\n ) {\n throw new MigrationError(\n \"No-op push drifted from marker/live/desired schema.\",\n VibORMErrorCode.MIGRATION_DRIFT,\n {\n meta: {\n planHash: plan.planHash,\n expectedChecksum: marker.snapshotHash,\n actualChecksum: plan.schemaHash,\n },\n }\n );\n }\n}\n\nfunction publicPreview(plan: InternalPushPlan): PushPreview {\n const consent: PushConsent = {\n format: \"1\",\n target: plan.target,\n planHash: plan.planHash,\n mode: plan.mode,\n validation: plan.validation,\n resolutions: plan.resolutions,\n };\n return freezeDeep({\n outcome: plan.statements.length === 0 ? \"noop\" : \"planned\",\n target: plan.target,\n planHash: plan.planHash,\n schemaHash: plan.schemaHash,\n fingerprint: plan.sourceFingerprint,\n destructive: plan.destructive,\n operations: plan.reportedOperations,\n statements: plan.previewStatements,\n consent,\n });\n}\n\nexport function prepareSchema(\n client: MigrationClient,\n skipValidation: boolean\n): {\n readonly relations: ResolvedRelationIndex;\n readonly driver: BoundMigrationDriver;\n} {\n hydrateSchemaNames(client.$schema);\n const relations = skipValidation\n ? resolveSchemaOrThrow(client.$schema)\n : validateResolvedSchemaOrThrow(client.$schema, allRules());\n const driver = getPushMigrationDriver(client);\n assertMigrationDecimalDomainsFitProvider(client.$schema, driver.dialect);\n return { relations, driver };\n}\n","/**\n * V1 generation: one new state from parent leaves, published atomically.\n * Snapshot and SQL are published before the state manifest.\n */\n\nimport type { SqlDialect } from \"../drivers/types\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport {\n assertManualStepwiseProof,\n type CompiledTransition,\n compileGeneratedTransition,\n compileManualTransition,\n compileTrustedCheck,\n compileValidationTransition,\n hashParent,\n type LowLockState,\n lowLockStates,\n lowLockSteps,\n rebindChecks,\n rebindDispatches,\n rebindRollback,\n sealParent,\n} from \"./compile\";\nimport { type DiffOptions, diff } from \"./differ\";\nimport { emptyManagedSnapshot } from \"./empty-snapshot\";\nimport { normalizeGenerateOptions } from \"./generate-input\";\nimport {\n loadMigrationGraph,\n type MigrationGraph,\n requireStateSnapshot,\n} from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport { renderMigrationReview } from \"./public-view\";\nimport {\n applyResolvedEnumMappings,\n detectEnumValueRemovals,\n resolveEnumValueRemovalMappings,\n} from \"./push/enum-removals\";\nimport type { getPushMigrationDriver, MigrationClient } from \"./push/planner\";\nimport { prepareSchema } from \"./push-v1\";\nimport {\n approveDestructiveOperations,\n callbackAsResolver,\n refuseUnusedDecisions,\n rejectAllResolver,\n resolveAmbiguousChanges,\n strictResolver,\n} from \"./resolver\";\nimport { serializeResolvedModels } from \"./serializer\";\nimport {\n type EncodedSnapshotArtifact,\n encodeSnapshotArtifact,\n} from \"./snapshot-artifacts\";\nimport { SqlAssembly } from \"./sql-assembly\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport { assertArtifactExecutionSafe } from \"./statement-safety\";\nimport type { MigrationStorageWriter } from \"./storage/contract\";\nimport { assertEstateTargetMatches } from \"./target\";\nimport type { DiffOperation, ResolveCallback, SchemaSnapshot } from \"./types\";\nimport { generateMigrationName, prepareSchemaProgram } from \"./utils\";\nimport {\n encodeEstateDescriptor,\n encodeSnapshot,\n encodeStateManifest,\n parseEstateDescriptor,\n} from \"./v1-parse\";\nimport type {\n GenerateV1Options,\n ManualMigrationInput,\n ManualTransitionInput,\n MigrationApprovalV1,\n MigrationBooleanCheckV1,\n MigrationParentTransitionV1,\n} from \"./v1-types\";\n\nexport interface GenerateV1Result {\n readonly outcome: \"published\" | \"preview\" | \"noop\";\n readonly stateId: Sha256 | null;\n readonly name: string | null;\n readonly estateHash: Sha256 | null;\n readonly snapshotHash: Sha256 | null;\n readonly sqlHash: Sha256 | null;\n readonly operations: readonly DiffOperation[];\n readonly warnings: readonly string[];\n readonly operationsByParent: readonly {\n readonly fromState: string | null;\n readonly operations: readonly DiffOperation[];\n }[];\n readonly sql: string;\n readonly reviewSql: string;\n}\n\nconst AUTHENTICATED_SNAPSHOT_DIFF_OPTIONS: DiffOptions = {\n compareDateTimeDeclarations: true,\n};\n\n/**\n * A dry run without a resolver previews the state as an approval would publish\n * it, as push's preview does; publishing still needs the resolver's answer.\n */\nconst previewApproval: ResolveCallback = (change) =>\n change.type === \"destructive\" ? change.proceed() : undefined;\n\nexport async function generateV1(\n client: MigrationClient,\n storage: MigrationStorageWriter,\n options: GenerateV1Options = {}\n): Promise<GenerateV1Result> {\n const request = normalizeGenerateOptions(options);\n const { relations, driver } = prepareSchema(\n client,\n request.skipValidation ?? false\n );\n // An estate's own format admits no dialect without a history.\n const dialect = driver.target.dialect as SqlDialect;\n const publishedEstate = await storage.readEstate();\n const estateBytes =\n publishedEstate ?? encodeEstateDescriptor(driver.target).bytes;\n const { estateHash, descriptor } = parseEstateDescriptor(estateBytes);\n assertEstateTargetMatches(descriptor.target, driver.target);\n const loaded = publishedEstate\n ? await loadMigrationGraph(storage)\n : emptyGraph(estateHash, descriptor);\n\n const desired = serializeResolvedModels(client.$schema, driver, relations);\n const desiredEncoded = encodeSnapshot(desired);\n const parents = resolveParents(loaded, request, desired);\n refuseUnprovedMerge(loaded, parents, request.manualMigration);\n const adopts = admitAdoption(request, loaded, desired, parents);\n const parentState =\n parents.length === 1 && parents[0]\n ? loaded.states.get(parents[0])\n : undefined;\n const parentSnapshot =\n parentState && loaded.snapshots.get(parentState.snapshotHash);\n const unchangedSnapshot =\n parentSnapshot !== undefined && sameSchema(parentSnapshot, desired);\n\n const assembly = new SqlAssembly();\n const parentBodies: Omit<MigrationParentTransitionV1, \"transitionHash\">[] =\n [];\n const reported: DiffOperation[] = [];\n const warnings: string[] = [];\n const operationsByParent: {\n fromState: string | null;\n operations: DiffOperation[];\n }[] = [];\n const destinationPlaceholders: MigrationBooleanCheckV1[] = [];\n // Each state a low-lock split publishes before this one, parent first.\n const stepStates: SealedLowLockState[] = [];\n const snapshotArtifacts = new Map(loaded.snapshotArtifacts);\n const snapshotFor = (\n snapshot: SchemaSnapshot,\n fromStates: readonly (Sha256 | null)[]\n ) => {\n const bases = fromStates.flatMap((from) => {\n if (from === null) return [];\n const manifest =\n loaded.states.get(from) ??\n stepStates.find((step) => step.encoded.stateId === from)!.encoded\n .manifest;\n return [manifest.snapshotArtifactHash ?? manifest.snapshotHash].filter(\n (hash) => snapshotArtifacts.has(hash)\n );\n });\n const encoded = encodeSnapshotArtifact(snapshot, snapshotArtifacts, bases);\n if (encoded.bytes) {\n snapshotArtifacts.set(encoded.artifactHash, {\n snapshot,\n snapshotHash: encoded.snapshotHash,\n depth: encoded.depth,\n bytes: encoded.bytes,\n ...(encoded.baseArtifactHash\n ? { baseArtifactHash: encoded.baseArtifactHash }\n : {}),\n });\n }\n return encoded;\n };\n\n if (request.manualMigration) {\n assertManualParents(loaded, request.manualMigration.transitions);\n for (const transition of request.manualMigration.transitions) {\n const compiled = compileManualTransition(\n transition.up,\n transition.rollback,\n dialect,\n transition.execution,\n transition.originChecks,\n assembly\n );\n parentBodies.push(sealParent(transition.from, compiled));\n }\n for (const [index, check] of (\n request.manualMigration.destinationChecks ?? []\n ).entries()) {\n destinationPlaceholders.push(\n compileTrustedCheck(check, dialect, assembly, `destination:${index}`)\n );\n }\n for (const compiled of parentBodies) {\n assertManualStepwiseProof(\n {\n operations: compiled.operations,\n rollback: compiled.rollback,\n originChecks: compiled.originChecks,\n requestedForwardBoundary: compiled.requestedForwardBoundary,\n atomicity: compiled.requestedForwardBoundary ?? \"transactional\",\n },\n destinationPlaceholders\n );\n }\n } else {\n for (const [index, from] of parents.entries()) {\n const current = requireStateSnapshot(loaded, from);\n const diffOptions = {\n ...AUTHENTICATED_SNAPSHOT_DIFF_OPTIONS,\n projectRename: driver.projectNativeRename.bind(driver),\n refuseConstraintNameChurn:\n driver.capabilities.introspectionReadsConstraintNames,\n };\n const diffed = await diff(current, desired, diffOptions);\n const admittedDrops = new Set<string>();\n const resolved = await resolveAmbiguousChanges(\n diffed,\n current,\n desired,\n request.resolve\n ? callbackAsResolver(request.resolve, admittedDrops)\n : strictResolver,\n diffOptions\n );\n const approvals = await approveDestructiveOperations(\n resolved,\n request.resolve ?? (request.dryRun ? previewApproval : undefined),\n false,\n admittedDrops\n );\n const enumMappings = await resolveEnumValueRemovalMappings(\n detectEnumValueRemovals(resolved, current),\n request.resolve ?? rejectAllResolver,\n false\n );\n const withEnumMappings = resolved.map((operation) =>\n operation.type === \"alterEnum\"\n ? applyResolvedEnumMappings([operation], enumMappings)[0]!\n : operation\n );\n const adoption = withoutAdoptedTables(\n withEnumMappings,\n adopts,\n desired,\n current\n );\n const staged = prepareSchemaProgram(\n adoption.operations,\n adoption.current,\n desired,\n driver\n );\n reported.push(...staged);\n operationsByParent.push({ fromState: from, operations: staged });\n // T2: the plan has asked every decision once its last parent is\n // planned, before a low-lock split publishes. A document already\n // published (a re-drive) asks none and stays a noop.\n if (index === parents.length - 1 && !unchangedSnapshot) {\n refuseUnusedDecisions(request.resolve);\n }\n // T5b, asked for with `lowLock`: one parent's PostgreSQL program gives\n // each low-lock step a commit of its own, as states published before\n // this one. Opt-in, because a step outside a transaction needs the\n // direct session a transaction pooler cannot give.\n const lowLock =\n request.lowLock === true && driver.dialect === \"postgresql\";\n const split =\n lowLock && parents.length === 1\n ? lowLockStates(staged, current, desired)\n : undefined;\n if (lowLock && !split && lowLockSteps(staged, desired).size > 0) {\n warnings.push(\n \"lowLock kept blocking index/FK forms (merge or trailing non-index/FK change); isolate indexes/FKs.\"\n );\n }\n let origin = { from, current: adoption.current, approvals };\n const before = split?.states.slice(0, -1) ?? [];\n for (const [index, state] of before.entries()) {\n const step = sealLowLockState(\n estateHash,\n driver,\n `${request.name?.trim() || generateMigrationName(staged)} (step ${index + 1} of ${before.length + 1})`,\n origin,\n state,\n split?.steps,\n snapshotFor\n );\n warnings.push(...step.warnings);\n stepStates.push(step);\n origin = {\n from: step.encoded.stateId,\n current: state.snapshot,\n approvals: [],\n };\n }\n const last = split?.states.at(-1);\n const compiled = last?.validates\n ? compileValidationTransition(\n last.operations,\n driver,\n origin.current,\n assembly\n )\n : compileGeneratedTransition(\n last?.operations ?? staged,\n driver,\n \"artifact\",\n origin.current,\n desired,\n assembly,\n split?.steps\n );\n warnings.push(...transitionWarnings(compiled));\n parentBodies.push(\n sealParent(origin.from, compiled, origin.approvals, adopts)\n );\n }\n }\n\n const named = request.name?.trim() || generateMigrationName(reported);\n const storedSnapshot = snapshotFor(\n desired,\n parentBodies.map((parent) => parent.fromState)\n );\n const { sealed, hashedParents, destinationChecks, encoded } = sealState(\n assembly,\n parentBodies,\n destinationPlaceholders,\n driver.target.dialect,\n estateHash,\n named,\n storedSnapshot\n );\n\n // Decision 8: field and model order is cosmetic, so a document that only\n // reorders them is a noop and publishes nothing.\n const emptyProgram = hashedParents.every((parent) =>\n parent.operations.every((operation) => operation.steps.length === 0)\n );\n if (!request.manualMigration && unchangedSnapshot && emptyProgram) {\n return {\n outcome: \"noop\",\n stateId: null,\n name: null,\n estateHash,\n snapshotHash: desiredEncoded.snapshotHash,\n sqlHash: null,\n operations: [],\n warnings: [],\n operationsByParent: [],\n sql: \"\",\n reviewSql: \"\",\n };\n }\n\n const final = { snapshot: storedSnapshot, sealed, encoded };\n const states = [...stepStates, final];\n const sqlText = states\n .map((state) => new TextDecoder().decode(state.sealed.bytes))\n .join(\"\\n\\n\");\n const reviewSql = [\n ...stepStates.map(({ review }) => review),\n renderMigrationReview(\n hashedParents,\n destinationChecks,\n sealed.bytes,\n request.resolve ? undefined : \"Needs approval at generate\"\n ),\n ].join(\"\\n\\n\");\n const candidate = {\n stateId: encoded.stateId,\n name: named,\n estateHash,\n snapshotHash: desiredEncoded.snapshotHash,\n sqlHash: sealed.sqlHash,\n operations: reported,\n warnings,\n operationsByParent,\n sql: sqlText,\n reviewSql,\n };\n if (request.dryRun) return { outcome: \"preview\", ...candidate };\n\n if (!publishedEstate) {\n await storage.publishEstate(estateBytes);\n }\n // Every state is complete before the first publishes. A low-lock split's\n // states publish parent first, each manifest after its snapshot and SQL.\n for (const { snapshot, sealed: sql, encoded: manifest } of states) {\n if (snapshot.bytes)\n await storage.publishSnapshot(snapshot.artifactHash, snapshot.bytes);\n await storage.publishSql(sql.sqlHash, sql.bytes);\n await storage.publishState(manifest.stateId, manifest.bytes);\n }\n return { outcome: \"published\", ...candidate };\n}\n\n/**\n * The tables `adopt` names, once each is admitted: declared by the desired\n * snapshot (which the serializer already keeps inside the client's list),\n * outside the estate's frozen list (a name there is managed already, so a raw\n * table of that name is drift), and absent from every parent's snapshot. An\n * estate without a list manages the whole database and adopts nothing, nor\n * does a manual, low-lock or checkpoint state.\n */\nfunction admitAdoption(\n request: GenerateV1Options,\n graph: MigrationGraph,\n desired: SchemaSnapshot,\n parents: readonly (Sha256 | null)[]\n): readonly string[] {\n const names = request.adopt ?? [];\n if (names.length === 0) return names;\n const refuse = (message: string): never => {\n throw new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_STATE);\n };\n if (request.manualMigration || request.lowLock)\n refuse(\"adopt cannot combine with manualMigration or lowLock\");\n if (request.from === null && graph.states.size > 0)\n refuse(\"checkpoint cannot adopt tables\");\n const frozen = graph.descriptor.target.tables;\n if (frozen === undefined) return refuse(\"adopt requires tables list\");\n for (const name of names) {\n if (!desired.tables.some((table) => table.name === name))\n refuse(`adopt \"${name}\" not in schema`);\n if (frozen.includes(name)) refuse(`adopt \"${name}\" already managed`);\n for (const parent of parents) {\n if (\n requireStateSnapshot(graph, parent).tables.some(\n (table) => table.name === name\n )\n )\n refuse(`adopt \"${name}\" already in parent ${parent ?? \"empty\"}`);\n }\n }\n return names;\n}\n\n/**\n * The program without what creates an adopted table: its CREATE TABLE, its\n * indexes and keys, and every enum an adopted table uses. That enum already\n * exists with the table (a PostgreSQL type is the database's, not the\n * table's), even where a new managed table of the same transition uses it\n * too, so it is never created, and a rollback, which drops only what the\n * program created, never drops it. It runs no DDL for them; the destination\n * proof proves the live table and the enum equal the declaration.\n *\n * The program's origin is the parent's schema plus those enums, because the\n * database already has them: the DDL of a new table naming one qualifies it\n * as it would an enum it created (`managedEnumNames`). The origin proof still\n * compares the parent's own snapshot.\n */\nfunction withoutAdoptedTables(\n operations: DiffOperation[],\n adopts: readonly string[],\n desired: SchemaSnapshot,\n current: SchemaSnapshot\n): { operations: DiffOperation[]; current: SchemaSnapshot } {\n if (adopts.length === 0) return { operations, current };\n const enumsOf = (tables: readonly SchemaSnapshot[\"tables\"][number][]) =>\n new Set(\n tables.flatMap((table) =>\n table.columns.map((column) =>\n column.type.endsWith(\"[]\") ? column.type.slice(0, -2) : column.type\n )\n )\n );\n const adoptedEnums = enumsOf(\n desired.tables.filter((table) => adopts.includes(table.name))\n );\n const broughtEnums = (desired.enums ?? []).filter(\n (enumDef) =>\n adoptedEnums.has(enumDef.name) &&\n !current.enums?.some(({ name }) => name === enumDef.name)\n );\n return {\n operations: operations.filter((operation) => {\n if (operation.type === \"createTable\") {\n return !adopts.includes(operation.table.name);\n }\n if (operation.type === \"createEnum\") {\n return !adoptedEnums.has(operation.enumDef.name);\n }\n return !(\n \"tableName\" in operation && adopts.includes(operation.tableName)\n );\n }),\n current:\n broughtEnums.length === 0\n ? current\n : { ...current, enums: [...(current.enums ?? []), ...broughtEnums] },\n };\n}\n\n/** Decision 8: two snapshots that differ only in field and model order. */\nfunction sameSchema(a: SchemaSnapshot, b: SchemaSnapshot): boolean {\n return (\n encodeSnapshot(orderFree(a)).snapshotHash ===\n encodeSnapshot(orderFree(b)).snapshotHash\n );\n}\n\n/** A snapshot with its tables, columns, keys, enums, views and indexes sorted by name. */\nfunction orderFree(snapshot: SchemaSnapshot): SchemaSnapshot {\n const byName = (a: { name: string }, b: { name: string }) =>\n a.name < b.name ? -1 : Number(a.name > b.name);\n return {\n ...snapshot,\n tables: snapshot.tables\n .map((table) => ({\n ...table,\n columns: [...table.columns].sort(byName),\n indexes: [...table.indexes].sort(byName),\n foreignKeys: [...table.foreignKeys].sort(byName),\n uniqueConstraints: [...table.uniqueConstraints].sort(byName),\n }))\n .sort(byName),\n enums: snapshot.enums && [...snapshot.enums].sort(byName),\n views: snapshot.views\n ?.map((view) =>\n view.indexes\n ? { ...view, indexes: [...view.indexes].sort(byName) }\n : view\n )\n .sort(byName),\n };\n}\n\n/**\n * Seals one state's manifest from its compiled parents: refuses unsafe SQL,\n * binds every check and dispatch to the sealed bytes and hashes each parent.\n */\nfunction sealState(\n assembly: SqlAssembly,\n parentBodies: readonly Omit<MigrationParentTransitionV1, \"transitionHash\">[],\n destinationPlaceholders: readonly MigrationBooleanCheckV1[],\n dialect: Parameters<typeof assertArtifactExecutionSafe>[1],\n estateHash: Sha256,\n name: string,\n snapshot: EncodedSnapshotArtifact\n) {\n const sealed = assembly.seal();\n assertArtifactExecutionSafe(\n sealed.dispatches.map((dispatch) => sliceDispatch(sealed.bytes, dispatch)),\n dialect,\n name\n );\n const hashedParents = parentBodies.map((parent) =>\n hashParent({\n ...parent,\n originChecks: rebindChecks(parent.originChecks, sealed.dispatches),\n operations: rebindDispatches(parent.operations, sealed.dispatches),\n rollback: rebindRollback(parent.rollback, sealed.dispatches),\n })\n );\n const destinationChecks = rebindChecks(\n destinationPlaceholders,\n sealed.dispatches\n );\n const encoded = encodeStateManifest({\n format: \"1\",\n estateHash,\n name,\n snapshotHash: snapshot.snapshotHash,\n ...(snapshot.artifactHash === snapshot.snapshotHash\n ? {}\n : { snapshotArtifactHash: snapshot.artifactHash }),\n sqlHash: sealed.sqlHash,\n destinationChecks,\n parents: hashedParents,\n });\n return { sealed, hashedParents, destinationChecks, encoded };\n}\n\ntype SealedLowLockState = ReturnType<typeof sealLowLockState>;\n\n/**\n * Seals one state a low-lock split puts before the generated one (T5b); it\n * becomes the next state's parent. Nothing publishes until every state of the\n * candidate is sealed.\n */\nfunction sealLowLockState(\n estateHash: Sha256,\n driver: ReturnType<typeof getPushMigrationDriver>,\n name: string,\n origin: {\n readonly from: Sha256 | null;\n readonly current: SchemaSnapshot;\n readonly approvals: readonly MigrationApprovalV1[];\n },\n state: LowLockState,\n steps: ReadonlySet<DiffOperation> | undefined,\n encode: (\n snapshot: SchemaSnapshot,\n fromStates: readonly (Sha256 | null)[]\n ) => EncodedSnapshotArtifact\n) {\n const assembly = new SqlAssembly();\n const compiled = compileGeneratedTransition(\n state.operations,\n driver,\n \"artifact\",\n origin.current,\n state.snapshot,\n assembly,\n steps\n );\n const snapshot = encode(state.snapshot, [origin.from]);\n const sealed = sealState(\n assembly,\n [sealParent(origin.from, compiled, origin.approvals)],\n [],\n driver.target.dialect,\n estateHash,\n name,\n snapshot\n );\n return {\n ...sealed,\n snapshot,\n review: renderMigrationReview(\n sealed.hashedParents,\n [],\n sealed.sealed.bytes\n ),\n warnings: transitionWarnings(compiled),\n };\n}\n\n/** What a compiled transition warns of: its own warnings, then irreversibility. */\nfunction transitionWarnings(compiled: CompiledTransition): string[] {\n return [\n ...(compiled.warnings ?? []),\n ...(compiled.rollback.kind === \"irreversible\"\n ? [compiled.rollback.reason]\n : []),\n ];\n}\n\nfunction assertManualParents(\n graph: MigrationGraph,\n transitions: readonly ManualTransitionInput[]\n): void {\n const seen = new Set<string>();\n for (const transition of transitions) {\n if (transition.from === null) {\n if (graph.states.size > 0) {\n throw new MigrationError(\n \"A second virtual-root transition is refused\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n } else if (!graph.states.has(transition.from)) {\n throw new MigrationError(\n `Unknown parent state ${transition.from}`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const key = transition.from ?? \"null\";\n if (seen.has(key)) {\n throw new MigrationError(\n \"A manual migration names a parent more than once\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n seen.add(key);\n }\n}\n\nfunction resolveParents(\n graph: MigrationGraph,\n options: GenerateV1Options,\n desired: SchemaSnapshot\n): Array<Sha256 | null> {\n if (options.from !== undefined) {\n if (options.from === null) {\n // Plan T4 (decision 11): on a populated estate `from: null` authors a\n // checkpoint, a second root restating the single leaf's schema, which\n // reanchor() can move a marker onto once prune() dropped what precedes it.\n const [leaf, ...more] = graph.leaves;\n if (\n leaf &&\n (more.length > 0 ||\n !sameSchema(requireStateSnapshot(graph, leaf), desired))\n ) {\n throw new MigrationError(\n \"A checkpoint (from: null) must restate the single leaf's schema.\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return [null];\n }\n if (!graph.states.has(options.from)) {\n throw new MigrationError(\n `Unknown parent state ${options.from}`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n return [options.from];\n }\n if (graph.states.size === 0) return [null];\n // `loadMigrationGraph` refuses a cycle, so a graph with states has a leaf.\n return [...graph.leaves];\n}\n\nfunction emptyGraph(\n estateHash: Sha256,\n descriptor: ReturnType<typeof parseEstateDescriptor>[\"descriptor\"]\n): MigrationGraph {\n const emptySnapshotHash = encodeSnapshot(emptyManagedSnapshot()).snapshotHash;\n return {\n estateHash,\n descriptor,\n states: new Map(),\n snapshots: new Map([[emptySnapshotHash, emptyManagedSnapshot()]]),\n snapshotArtifacts: new Map(),\n sql: new Map(),\n roots: [],\n leaves: [],\n emptySnapshotHash,\n };\n}\n\nfunction ancestryHasCustom(\n graph: MigrationGraph,\n stateId: Sha256 | null,\n seen: Set<string> = new Set()\n): boolean {\n if (stateId === null || seen.has(stateId)) return false;\n seen.add(stateId);\n // Every id here is a validated state or a validated parent edge's source.\n const state = graph.states.get(stateId)!;\n for (const transition of state.parents) {\n if (\n transition.operations.some(\n (operation) => operation.origin === \"manual\"\n ) ||\n transition.requestedForwardBoundary !== null\n ) {\n return true;\n }\n if (ancestryHasCustom(graph, transition.fromState, seen)) return true;\n }\n return false;\n}\n\nfunction refuseUnprovedMerge(\n graph: MigrationGraph,\n parents: Array<Sha256 | null>,\n manual: ManualMigrationInput | undefined\n): void {\n if (parents.length < 2 || manual) return;\n for (const parent of parents) {\n if (ancestryHasCustom(graph, parent)) {\n throw new MigrationError(\n \"Cannot structurally merge custom/data transition; supply manualMigration.\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n }\n}\n","/** One hostile-input boundary for the public down() selector. */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { snapshotExactRecord } from \"./input-boundary\";\nimport type { ResolveCallback } from \"./types\";\nimport type { StateSelector } from \"./v1-types\";\n\nexport interface NormalizedDownOptions {\n readonly steps: number;\n readonly to?: StateSelector;\n readonly dryRun: boolean;\n readonly expectRevision?: number;\n readonly resolve?: ResolveCallback;\n}\n\nexport function normalizeDownOptions(options: unknown): NormalizedDownOptions {\n const record = snapshotExactRecord(\n options,\n [\"steps\", \"to\", \"dryRun\", \"expectRevision\", \"resolve\"],\n \"down options\",\n refuseDownOptions\n );\n const { steps, to, dryRun, expectRevision, resolve } = record;\n if (steps !== undefined && to !== undefined) {\n return refuseDownOptions(\"down accepts either steps or to, not both\");\n }\n let normalizedSteps = 1;\n if (steps !== undefined) {\n if (\n typeof steps !== \"number\" ||\n !Number.isSafeInteger(steps) ||\n steps <= 0\n ) {\n return refuseDownOptions(\"down steps must be a positive safe integer\");\n }\n normalizedSteps = steps;\n }\n if (dryRun !== undefined && typeof dryRun !== \"boolean\") {\n return refuseDownOptions(\"down dryRun must be a boolean\");\n }\n if (\n expectRevision !== undefined &&\n (typeof expectRevision !== \"number\" ||\n !Number.isSafeInteger(expectRevision) ||\n expectRevision <= 0)\n ) {\n return refuseDownOptions(\n \"down expectRevision must be a positive safe integer\"\n );\n }\n if (resolve !== undefined && !isResolveCallback(resolve)) {\n return refuseDownOptions(\"down resolve must be a function\");\n }\n return Object.freeze({\n steps: normalizedSteps,\n ...(to === undefined ? {} : { to: normalizeStateSelector(to) }),\n dryRun: dryRun === true,\n ...(expectRevision === undefined ? {} : { expectRevision }),\n ...(resolve === undefined ? {} : { resolve }),\n });\n}\n\nfunction normalizeStateSelector(value: unknown): StateSelector {\n const record = snapshotExactRecord(\n value,\n [\"id\", \"prefix\", \"name\"],\n \"down to\",\n refuseDownOptions\n );\n const keys = Object.keys(record);\n if (keys.length !== 1) {\n return refuseDownOptions(\"down to must contain exactly one selector key\");\n }\n // The sole OWN key. `\"id\" in record` walks the prototype chain, so a polluted\n // Object.prototype.id made `down({ to: { name: \"baseline\" } })` select the\n // inherited id and roll back to the wrong state.\n const key = keys[0]!;\n const selected = record[key];\n if (typeof selected !== \"string\" || selected.length === 0) {\n return refuseDownOptions(`down to.${key} must be a non-empty string`);\n }\n if (key === \"id\") return { id: selected };\n if (key === \"prefix\") return { prefix: selected };\n return { name: selected };\n}\n\nfunction isResolveCallback(value: unknown): value is ResolveCallback {\n return typeof value === \"function\";\n}\n\nfunction refuseDownOptions(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n","/**\n * History-aware reset. One lock. Clear, replay from null, then one marker CAS.\n * Never re-enters applyV1.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { canonicalizeJson } from \"./canonical-json\";\nimport { tableExistsProbe, viewExistsProbe } from \"./catalog-probes\";\nimport {\n assertTransactionalBoundaryHonored,\n classifyStoredAtomicity,\n groupContiguousAtomicity,\n refuseSqliteStepwise,\n stepStatements,\n} from \"./compile\";\nimport {\n advanceMarker,\n appendLedger,\n attemptEvents,\n ensureControlTables,\n isTableMissing,\n ledgerEvent,\n markerFromPath,\n readControlState,\n refuseIncompatibleHistory,\n sameMarker,\n unfinishedAttempts,\n} from \"./control\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport {\n annotateMigrationFailure,\n assertAllChecks,\n executeExactSql,\n executeOperations,\n providerFacts,\n providerRefused,\n} from \"./execute-dispatch\";\nimport {\n loadMigrationGraph,\n type MigrationGraph,\n type RouteEdge,\n requireStateSnapshot,\n resolveStateSelector,\n routeEdges,\n selectRoute,\n} from \"./graph\";\nimport { domainHash, HASH_DOMAIN, type Sha256 } from \"./identity\";\nimport { introspectManaged } from \"./introspect-managed\";\nimport { planLiveNamespaceReset } from \"./live-reset\";\nimport {\n commitLockedTransaction,\n resolveCommandDriver,\n runProgram,\n withLockedMigrationProducer,\n} from \"./pinned-session\";\nimport { assertAdoptable, assertLockedSinceDecision, proveLive } from \"./proof\";\nimport type { MigrationClient } from \"./push/planner\";\nimport { fingerprintLive } from \"./push-fingerprint\";\nimport {\n confirmedPrefix,\n openCommand,\n readCommandControl,\n refuseAmbiguousNext,\n sliceOperations,\n} from \"./resume\";\nimport { encodeSqlText } from \"./sql-blob\";\nimport type { MigrationStorageWriter } from \"./storage/contract\";\nimport { managedTables, withManagedTables } from \"./target\";\nimport { encodeDispatchIdentity, encodeSqlBlob } from \"./v1-parse\";\nimport { corrupt } from \"./v1-parse-shared\";\nimport type {\n LedgerEventV1,\n MarkerPathEdgeV1,\n MigrationDispatchV1,\n MigrationMarkerV1,\n MigrationOperationV1,\n ResetPlanV1,\n ResetV1Options,\n} from \"./v1-types\";\n\nexport async function resetV1(\n client: MigrationClient,\n storage: MigrationStorageWriter,\n options: ResetV1Options = {}\n): Promise<{\n readonly preview: boolean;\n readonly path: readonly Sha256[];\n readonly tables?: readonly string[];\n}> {\n const graph = await loadMigrationGraph(storage);\n const target = resolveStateSelector(graph, options.to);\n const path = selectRoute(graph, null, target, options.via);\n const dryRun = options.dryRun === true;\n const driver = openCommand(\n client,\n graph,\n dryRun ? \"read-only\" : \"effectful\",\n \"reset()\",\n \"full\"\n );\n if (dryRun) {\n const command = await resolveCommandDriver(client.$driver, driver);\n // Without a list the whole namespace is cleared, and the marker is not read.\n const marker =\n graph.descriptor.target.tables === undefined\n ? null\n : (await readControlState(client.$driver, command, { ledger: \"open\" }))\n .marker;\n const plan = await planClear(client.$driver, command, graph, marker, path);\n await command.preflightSchemaRequirements(\n path.map((stateId) => requireStateSnapshot(graph, stateId)),\n (sql, params) => client.$driver._executeRaw(sql, params),\n resetProgram(\n plan,\n prepareResetReplay(\n client.$driver.supportsTransactions,\n command,\n graph,\n path\n )\n ),\n true\n );\n await assertAdoptable(client.$driver, command, graph, null, path);\n return {\n preview: true,\n path,\n tables: plan.dropTables.map((table) => table.name),\n };\n }\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const control = await readCommandControl(pinned, command, true);\n const { marker, ledger } = control;\n const needsBootstrap = control.presence.kind !== \"present\";\n const open = unfinishedAttempts(ledger);\n const resetAttempt =\n open.length === 1 && open[0]!.kind === \"reset-started\"\n ? open[0]!\n : undefined;\n if (open.length > 0 && !resetAttempt) {\n throw new MigrationError(\n \"Unfinished attempt blocks reset\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n }\n const targetIdentity = `${command.target.dialect}:${command.namespace ?? \"\"}`;\n const storedResetPlan = resetAttempt\n ? matchingResetPlan(resetAttempt, graph, target, path, targetIdentity)\n : undefined;\n if (!resetAttempt) {\n refuseIncompatibleHistory(marker, ledger);\n }\n const targetSnapshot = requireStateSnapshot(graph, target);\n const targetSnapshotHash = graph.states.get(target)!.snapshotHash;\n const edges: MarkerPathEdgeV1[] = routeEdges(graph, null, path).map(\n ({ to, transition }) => ({\n stateId: to,\n transitionHash: transition.transitionHash,\n baselineBoundary: false,\n })\n );\n const resetEvent = {\n estateHash: graph.estateHash,\n snapshotHash: targetSnapshotHash,\n sqlHash: null,\n fromState: marker?.stateId ?? null,\n toState: target,\n transitionHash: null,\n direction: \"reset\",\n } as const;\n if (\n resetAttempt &&\n storedResetPlan &&\n marker &&\n resetMarkerProvesApplied(\n marker,\n graph,\n edges,\n targetSnapshotHash,\n storedResetPlan\n ) &&\n (await fingerprintLive(\n await introspectManaged(\n pinned,\n replayedTo(command, graph, marker, target)\n ),\n command,\n pinned\n )) === (await fingerprintLive(targetSnapshot, command, pinned))\n ) {\n await appendLedger(\n pinned,\n command,\n attemptEvents(\n { ...resetEvent, fromState: resetAttempt.fromState },\n resetAttempt.attemptId\n ).event(\"reset-applied\", \"committed\")\n );\n return { preview: false, path };\n }\n if (\n resetAttempt &&\n storedResetPlan &&\n !resetSourceMarkerMatches(\n marker,\n resetAttempt,\n storedResetPlan,\n graph.emptySnapshotHash\n )\n ) {\n throw new MigrationError(\n \"Unfinished reset source marker mismatch\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n }\n const hasReplayEvidence = resetAttempt\n ? ledger.some(\n (event) =>\n event.attemptId === resetAttempt.attemptId &&\n event.kind === \"reset-step-confirmed\" &&\n (event.fromState !== null ||\n event.toState !== null ||\n event.transitionHash !== null ||\n event.operationId !== null)\n )\n : false;\n const livePlan = hasReplayEvidence\n ? undefined\n : await planClear(pinned, command, graph, marker, path);\n const clearDispatches = resetProgram(livePlan, []).map((sql) =>\n dispatchForClearSql(sql)\n );\n if (\n livePlan &&\n command.target.dialect === \"mysql\" &&\n (livePlan.dropForeignKeys.length > 0 || livePlan.dropEnums.length > 0)\n ) {\n throw new MigrationError(\n \"Stepwise reset refuses unproven clear dispatches\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n }\n const planBody = {\n estateHash: graph.estateHash,\n targetIdentity,\n sourceRevision: marker?.revision ?? 0,\n sourceFingerprint: marker?.snapshotHash ?? graph.emptySnapshotHash,\n replayPath: path,\n clearDispatches,\n referencedStates: path,\n };\n const stored = storedResetPlan;\n if (stored && livePlan) {\n assertStoredResetPlan(stored, planBody);\n }\n const resetPlanHash = stored\n ? stored.resetPlanHash\n : domainHash(HASH_DOMAIN.resetPlan, canonicalizeJson(planBody));\n const plan: ResetPlanV1 = stored ?? { ...planBody, resetPlanHash };\n const prepared = prepareResetReplay(\n pinned.supportsTransactions,\n command,\n graph,\n path\n );\n const remaining = resetAttempt\n ? remainingResetReplay(graph, prepared, resetAttempt, plan, ledger)\n : prepared;\n // The statements this command runs, as apply hands its path over: the\n // dialect refuses what they would lose (S11, T5a, Neki) before effects.\n // The source is the marker's state where this estate holds it; a marker\n // it does not (a history replaced by a fresh one, `markerState:\n // \"unknown\"`) has no snapshot here, and the clear drops what the live\n // inventory names, as the dry run plans it.\n const source = marker?.stateId ?? null;\n await command.preflightSchemaRequirements(\n [\n ...(source === null || graph.states.has(source)\n ? [requireStateSnapshot(graph, source)]\n : []),\n ...path.map((stateId) => requireStateSnapshot(graph, stateId)),\n ],\n (sql, params) => pinned._executeRaw(sql, params),\n resetProgram(livePlan, remaining),\n // Where Neki needs a commit, each statement commits alone.\n true\n );\n await assertAdoptable(pinned, command, graph, null, path);\n const begin = resetAttempt\n ? undefined\n : (producer: Parameters<typeof appendLedger>[0]) =>\n appendLedger(\n producer,\n command,\n attemptEvents(\n { ...resetEvent, resetPlan: plan },\n resetPlanHash\n ).event(\"reset-started\", \"none\")\n );\n const finish = async (producer: Parameters<typeof appendLedger>[0]) => {\n await proveLive(\n producer,\n replayedTo(command, graph, marker, target),\n graph,\n targetSnapshotHash,\n () => \"Reset replay did not reach the target snapshot\"\n );\n await advanceMarker(\n producer,\n command,\n graph.estateHash,\n marker,\n edges,\n targetSnapshotHash\n );\n await appendLedger(\n producer,\n command,\n attemptEvents(resetEvent, resetPlanHash).event(\n \"reset-applied\",\n \"committed\"\n )\n );\n };\n // Committed before the program, whose first group re-reads the marker.\n if (needsBootstrap) {\n await ensureControlTables(pinned, command);\n await commitLockedTransaction(pinned, command);\n }\n await runProgram(pinned, command, undefined, (producer) =>\n executeResetProgram(\n pinned,\n producer,\n command,\n marker,\n graph,\n livePlan,\n plan,\n remaining,\n resetPlanHash,\n begin,\n finish,\n client.$schema\n )\n );\n return { preview: false, path };\n }\n );\n}\n\n/**\n * The tables an estate with a `tables` list holds while the marker stands:\n * the estate's own list and every table its arrival path managed. Never a\n * table only the client lists: nothing adopted it, so it is the user's.\n */\nfunction managedByMarker(\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null\n): readonly string[] | undefined {\n const states = [null, ...(marker?.path ?? []).map((edge) => edge.stateId)];\n return managedTables(\n graph.descriptor.target.tables,\n states\n .filter((state) => state === null || graph.states.has(state))\n .map((state) => requireStateSnapshot(graph, state))\n );\n}\n\n/**\n * The command, its inventory what reset clears (`managedByMarker`), once the\n * replay is proven able to recreate it: an adoption has no DDL, so replaying\n * one whose table the clear drops would lose that table and its rows.\n */\nconst invalidState = (message: string, meta?: Record<string, unknown>) =>\n new MigrationError(\n message,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n meta ? { meta } : undefined\n );\n\nfunction clearedBy(\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null,\n path: readonly Sha256[]\n): BoundMigrationDriver {\n const cleared = managedByMarker(graph, marker);\n for (const { to, transition } of routeEdges(graph, null, path)) {\n const lost = transition.adopts?.find((name) => cleared?.includes(name));\n if (lost !== undefined) {\n throw invalidState(\n `reset cannot replay ${to} which adopts \"${lost}\" (cleared with no DDL to recreate).`\n );\n }\n }\n return withManagedTables(command, cleared);\n}\n\n/**\n * The clear, once every table the replay creates is accounted for. A live\n * table the replay creates and the clear keeps (no state of the marker's\n * path managed it: it is not adopted yet, or the marker names a history this\n * estate does not hold) is refused before effects: dropping it could drop a\n * user's table, and keeping it would let the replay's CREATE find it.\n */\nasync function planClear(\n producer: AnyDriver,\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null,\n path: readonly Sha256[]\n): Promise<Awaited<ReturnType<typeof planLiveNamespaceReset>>> {\n const cleared = clearedBy(command, graph, marker, path);\n const kept = managedByMarker(graph, marker);\n if (kept !== undefined) {\n const route = routeEdges(graph, null, path);\n const adopted = route.flatMap(({ transition }) => transition.adopts ?? []);\n const created = new Set(\n route.flatMap(({ to }) =>\n requireStateSnapshot(graph, to).tables.map(({ name }) => name)\n )\n );\n for (const table of [...created].sort()) {\n if (\n kept.includes(table) ||\n adopted.includes(table) ||\n (await isTableMissing(producer, command, table))\n )\n continue;\n const foreign = marker?.path.some(\n ({ stateId }) => !graph.states.has(stateId)\n );\n throw invalidState(\n `reset cannot account for table \"${table}\": exists and replay creates it${foreign ? \" (unknown marker history)\" : \"\"}; drop or rename it first.`,\n { table }\n );\n }\n }\n return planLiveNamespaceReset(producer, cleared);\n}\n\n/** The command, proving the replay's target and that the clear left nothing. */\nfunction replayedTo(\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null,\n target: Sha256\n): BoundMigrationDriver {\n return withManagedTables(\n command,\n managedTables(managedByMarker(graph, marker), [\n requireStateSnapshot(graph, target),\n ])\n );\n}\n\nfunction matchingResetPlan(\n attempt: LedgerEventV1,\n graph: MigrationGraph,\n target: Sha256,\n path: readonly Sha256[],\n targetIdentity: string\n): ResetPlanV1 {\n const targetState = graph.states.get(target);\n const plan = attempt.resetPlan;\n // A source this estate holds fixes the plan's fingerprint; a foreign one (a\n // history replaced by a fresh one) does not, and the plan's own record of\n // the marker is what `resetSourceMarkerMatches` proves the live marker\n // still is.\n const sourceSnapshotHash =\n attempt.fromState === null\n ? graph.emptySnapshotHash\n : graph.states.has(attempt.fromState)\n ? graph.states.get(attempt.fromState)!.snapshotHash\n : plan?.sourceFingerprint;\n if (\n !(targetState && plan) ||\n attempt.direction !== \"reset\" ||\n attempt.attemptId !== plan.resetPlanHash ||\n attempt.estateHash !== graph.estateHash ||\n attempt.snapshotHash !== targetState.snapshotHash ||\n attempt.toState !== target ||\n plan.estateHash !== graph.estateHash ||\n plan.targetIdentity !== targetIdentity ||\n plan.sourceFingerprint !== sourceSnapshotHash ||\n !sameIds(plan.replayPath, path) ||\n !sameIds(plan.referencedStates, path)\n ) {\n throw invalidState(\"Unfinished reset does not match requested reset\");\n }\n return plan;\n}\n\nfunction resetMarkerProvesApplied(\n marker: MigrationMarkerV1,\n graph: MigrationGraph,\n edges: MigrationMarkerV1[\"path\"],\n snapshotHash: Sha256,\n plan: ResetPlanV1\n): boolean {\n const expected = markerFromPath(\n graph.estateHash,\n snapshotHash,\n edges,\n plan.sourceRevision + 1\n );\n return (\n marker.estateHash === expected.estateHash &&\n marker.stateId === expected.stateId &&\n marker.snapshotHash === expected.snapshotHash &&\n sameMarker(marker, expected)\n );\n}\n\nfunction resetSourceMarkerMatches(\n marker: MigrationMarkerV1 | null,\n attempt: LedgerEventV1,\n plan: ResetPlanV1,\n emptySnapshotHash: Sha256\n): boolean {\n return marker\n ? marker.stateId === attempt.fromState &&\n marker.revision === plan.sourceRevision &&\n marker.snapshotHash === plan.sourceFingerprint\n : attempt.fromState === null &&\n plan.sourceRevision === 0 &&\n plan.sourceFingerprint === emptySnapshotHash;\n}\n\nfunction assertStoredResetPlan(\n stored: ResetPlanV1,\n live: Omit<ResetPlanV1, \"resetPlanHash\">\n): void {\n if (\n stored.estateHash !== live.estateHash ||\n stored.targetIdentity !== live.targetIdentity ||\n stored.sourceRevision !== live.sourceRevision ||\n stored.sourceFingerprint !== live.sourceFingerprint ||\n !sameIds(stored.replayPath, live.replayPath)\n )\n throw invalidState(\"Stored reset plan mismatch\");\n const storedIds = new Set(\n stored.clearDispatches.map((dispatch) => dispatch.dispatchId)\n );\n for (const dispatch of live.clearDispatches) {\n if (!storedIds.has(dispatch.dispatchId))\n throw invalidState(\"Live reset clears missing from stored plan\");\n }\n}\n\nfunction sameIds(left: readonly Sha256[], right: readonly Sha256[]): boolean {\n if (left.length !== right.length) return false;\n return left.every((id, index) => id === right[index]);\n}\n\n/** The clear, in the order it runs, then the replay's statements. */\nfunction resetProgram(\n livePlan: Awaited<ReturnType<typeof planLiveNamespaceReset>> | undefined,\n replay: readonly Pick<PreparedResetReplayEdge, \"blob\" | \"operations\">[]\n): string[] {\n return [\n ...(livePlan?.clear ?? []),\n ...replay.flatMap(({ blob, operations }) =>\n stepStatements(blob, operations)\n ),\n ];\n}\n\nfunction dispatchForClearSql(sql: string): MigrationDispatchV1 {\n const bytes = encodeSqlText(sql);\n const sqlHash = encodeSqlBlob(bytes);\n return {\n dispatchId: encodeDispatchIdentity(sqlHash, 0, bytes.length, []),\n sqlHash,\n offset: 0,\n length: bytes.length,\n parameters: [],\n };\n}\n\nasync function executeResetClear(\n pinned: Parameters<typeof executeExactSql>[0],\n command: Parameters<typeof planLiveNamespaceReset>[1],\n livePlan: Awaited<ReturnType<typeof planLiveNamespaceReset>>,\n attemptId: Sha256,\n graph: MigrationGraph,\n strategy: \"transactional\" | \"stepwise\"\n): Promise<void> {\n // Clear statements are numbered in the order they run, as replay ones are.\n let statementIndex = 0;\n const runClearStatement = async (sql: string) => {\n const site = {\n step: \"reset-clear\",\n strategy,\n statementIndex: statementIndex++,\n dispatchId: dispatchForClearSql(sql).dispatchId,\n };\n try {\n await executeExactSql(pinned, sql);\n } catch (error) {\n if (!providerRefused(error)) throw annotateMigrationFailure(error, site);\n throw new MigrationError(\n `Reset clear statement ${site.statementIndex} failed`,\n VibORMErrorCode.MIGRATION_FAILED,\n { cause: error, meta: { ...site, ...providerFacts(error) } }\n );\n }\n };\n // A table or a view is dropped once, proven gone, and confirmed.\n const dropProven = async (\n drop: {\n readonly name: string;\n readonly sql: string;\n readonly materialized?: boolean;\n },\n kind: \"table\" | \"view\"\n ) => {\n const probe = (exists: boolean) =>\n kind === \"view\"\n ? viewExistsProbe(\n command,\n drop.name,\n exists,\n \"live-command\",\n drop.materialized\n )\n : tableExistsProbe(command, drop.name, exists);\n if (!(await evaluateProbe(pinned, probe(true)))) {\n await confirmResetStep(pinned, command, graph, attemptId, drop.sql);\n return;\n }\n await runClearStatement(drop.sql);\n if (!(await evaluateProbe(pinned, probe(false)))) {\n throw new MigrationError(\n `Reset clear did not drop ${kind} ${drop.name}`,\n VibORMErrorCode.MIGRATION_PARTIAL_EFFECT\n );\n }\n await confirmResetStep(pinned, command, graph, attemptId, drop.sql);\n };\n for (const view of livePlan.dropViews) {\n // A view kept by triggers: what keeps it, then its table.\n for (const sql of view.keepers ?? []) {\n await runClearStatement(sql);\n await confirmResetStep(pinned, command, graph, attemptId, sql);\n }\n if (!view.tableless)\n await dropProven(view, view.keepers ? \"table\" : \"view\");\n }\n for (const sql of livePlan.dropForeignKeys) {\n await runClearStatement(sql);\n await confirmResetStep(pinned, command, graph, attemptId, sql);\n }\n for (const table of livePlan.dropTables) await dropProven(table, \"table\");\n for (const sql of livePlan.dropEnums) {\n await runClearStatement(sql);\n await confirmResetStep(pinned, command, graph, attemptId, sql);\n }\n}\n\nasync function evaluateProbe(\n pinned: Parameters<typeof executeExactSql>[0],\n probe: ReturnType<typeof tableExistsProbe>\n): Promise<boolean> {\n const result = await pinned._executeRaw<Record<string, unknown>>(\n probe.sql,\n probe.parameters.map((parameter) =>\n parameter.kind === \"string\" ? parameter.value : null\n )\n );\n const value = Object.values(result.rows[0] ?? {})[0];\n return (\n (value === true || value === 1 || value === \"1\" || value === \"t\") ===\n probe.equals\n );\n}\n\nasync function confirmResetStep(\n pinned: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n attemptId: Sha256,\n sql: string\n): Promise<void> {\n await confirmResetDispatch(\n pinned,\n command,\n graph,\n attemptId,\n dispatchForClearSql(sql)\n );\n}\n\nasync function confirmResetDispatch(\n pinned: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n attemptId: Sha256,\n dispatch: MigrationDispatchV1\n): Promise<void> {\n await appendLedger(\n pinned,\n command,\n ledgerEvent({\n attemptId,\n kind: \"reset-step-confirmed\",\n estateHash: graph.estateHash,\n snapshotHash: graph.emptySnapshotHash,\n sqlHash: dispatch.sqlHash,\n fromState: null,\n toState: null,\n transitionHash: null,\n direction: \"reset\",\n operationId: null,\n dispatchId: dispatch.dispatchId,\n effectState: \"committed\",\n })\n );\n}\n\ninterface PreparedResetReplayEdge extends RouteEdge {\n readonly boundary: \"transactional\" | \"stepwise\";\n readonly operations: readonly MigrationOperationV1[];\n}\n\nfunction prepareResetReplay(\n supportsTransactions: boolean,\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n path: readonly Sha256[]\n): readonly PreparedResetReplayEdge[] {\n return routeEdges(graph, null, path).map((edge) => {\n const requested = edge.transition.requestedForwardBoundary;\n const boundary = classifyStoredAtomicity(\n command,\n requested,\n edge.transition.operations,\n edge.blob\n );\n assertTransactionalBoundaryHonored(supportsTransactions, requested);\n refuseSqliteStepwise(command, requested, edge.to);\n return { ...edge, boundary, operations: edge.transition.operations };\n });\n}\n\nfunction remainingResetReplay(\n graph: MigrationGraph,\n prepared: readonly PreparedResetReplayEdge[],\n attempt: LedgerEventV1,\n plan: ResetPlanV1,\n ledger: readonly LedgerEventV1[]\n): readonly PreparedResetReplayEdge[] {\n const clearByDispatch = new Map(\n plan.clearDispatches.map((dispatch, index) => [dispatch.dispatchId, index])\n );\n const clearCommitted = new Set<number>();\n const steps = prepared.flatMap((edge, edgeIndex) =>\n edge.operations.flatMap((operation) =>\n operation.steps.map((step) => ({ edge, edgeIndex, operation, step }))\n )\n );\n const byDispatch = new Map(\n steps.map((entry, index) => [entry.step.execute.dispatchId, index])\n );\n const completed = new Set<number>();\n const announced = new Set<number>();\n let hasReplayEvidence = false;\n for (const event of ledger) {\n if (\n event.attemptId !== attempt.attemptId ||\n event.kind !== \"reset-step-confirmed\"\n ) {\n continue;\n }\n if (\n event.direction !== \"reset\" ||\n event.estateHash !== graph.estateHash ||\n !event.dispatchId\n )\n corrupt(\"Reset progress plan mismatch\");\n const isClear =\n event.fromState === null &&\n event.toState === null &&\n event.transitionHash === null &&\n event.operationId === null;\n if (isClear) {\n const clearIndex = clearByDispatch.get(event.dispatchId);\n if (\n clearIndex === undefined ||\n event.sqlHash !== plan.clearDispatches[clearIndex]!.sqlHash ||\n event.snapshotHash !== graph.emptySnapshotHash ||\n event.effectState !== \"committed\"\n )\n corrupt(\"Reset clear unknown dispatch\");\n clearCommitted.add(clearIndex);\n continue;\n }\n hasReplayEvidence = true;\n const index = byDispatch.get(event.dispatchId);\n if (index === undefined) corrupt(\"Reset replay unknown dispatch\");\n const entry = steps[index];\n if (\n !entry ||\n event.fromState !== entry.edge.from ||\n event.toState !== entry.edge.to ||\n event.transitionHash !== entry.edge.transition.transitionHash ||\n event.snapshotHash !== entry.edge.state.snapshotHash ||\n event.sqlHash !== entry.edge.state.sqlHash ||\n event.operationId !== entry.operation.id\n )\n corrupt(\"Reset replay unknown dispatch\");\n if (event.effectState === \"committed\") {\n completed.add(index);\n } else if (event.effectState === \"none\") {\n if (entry.step.retry === \"proven\") completed.add(index);\n else announced.add(index);\n } else {\n throw new MigrationError(\n \"Reset replay ambiguous commit\",\n VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT\n );\n }\n }\n confirmedPrefix(clearCommitted, \"Reset clear non-contiguous\");\n if (hasReplayEvidence && clearCommitted.size !== plan.clearDispatches.length)\n corrupt(\"Reset replay before clear complete\");\n if (!hasReplayEvidence) return prepared;\n const completedCount = confirmedPrefix(\n completed,\n \"Reset replay non-contiguous\"\n );\n if (\n [...announced].some(\n (index) => !completed.has(index) && index !== completedCount\n )\n )\n corrupt(\"Reset replay non-contiguous\");\n const next = steps[completedCount];\n refuseAmbiguousNext(\n next?.step,\n next?.edge.boundary,\n announced.has(completedCount),\n \"Next reset dispatch ambiguous\"\n );\n const verificationEdge =\n completedCount === 0 ? undefined : steps[completedCount - 1]?.edgeIndex;\n let skipped = completedCount;\n return prepared.flatMap((edge, edgeIndex) => {\n const operationCount = edge.operations.reduce(\n (count, operation) => count + operation.steps.length,\n 0\n );\n if (skipped >= operationCount) {\n skipped -= operationCount;\n return edgeIndex === verificationEdge\n ? [{ ...edge, operations: [] }]\n : [];\n }\n const operations = sliceOperations(edge.operations, skipped);\n skipped = 0;\n return [{ ...edge, operations }];\n });\n}\n\nasync function executeResetProgram(\n pinned: Parameters<typeof executeOperations>[0],\n producer: Parameters<typeof executeOperations>[0],\n command: BoundMigrationDriver,\n marker: MigrationMarkerV1 | null,\n graph: MigrationGraph,\n livePlan: Awaited<ReturnType<typeof planLiveNamespaceReset>> | undefined,\n plan: ResetPlanV1,\n replay: readonly PreparedResetReplayEdge[],\n attemptId: Sha256,\n beforeFirstEffect:\n | ((producer: Parameters<typeof appendLedger>[0]) => Promise<void>)\n | undefined,\n finish: (producer: Parameters<typeof appendLedger>[0]) => Promise<void>,\n models: MigrationClient[\"$schema\"]\n): Promise<void> {\n const groups = groupContiguousAtomicity(replay, (edge) =>\n resetProgram(undefined, [edge])\n );\n const liveClear = resetProgram(livePlan, []);\n const liveClearDispatches = new Set(\n liveClear.map((sql) => dispatchForClearSql(sql).dispatchId)\n );\n let clearPending = liveClear.length > 0 ? livePlan : undefined;\n // On Neki no program opens a transaction (`runProgram`): what a failure\n // reports as its boundary is the one it ran under.\n const neki = command.commitsSchemaChangesAlone();\n let clearEvidencePending = livePlan !== undefined;\n let admissionPending = beforeFirstEffect;\n // `statements` are the ones the boundary runs: apply's program, so SQLite's\n // foreign keys are lifted (and proven) around a replayed recreation.\n const runBoundary = async (\n boundary: \"transactional\" | \"stepwise\",\n statements: string[],\n body: (target: Parameters<typeof appendLedger>[0]) => Promise<void>\n ) => {\n const guarded = async (target: Parameters<typeof appendLedger>[0]) => {\n // The reset's own attempt is open once admitted (or resumed): before\n // that, an open one was opened while the lock was let go.\n await assertLockedSinceDecision(\n pinned,\n target,\n command,\n marker,\n admissionPending === undefined\n );\n await body(target);\n };\n // On MySQL the reset already runs as one sequential program (`resetV1`).\n try {\n await (command.target.dialect === \"mysql\"\n ? guarded(producer)\n : runProgram(\n pinned,\n command,\n { transactional: boundary === \"transactional\", statements },\n guarded\n ));\n } catch (failure) {\n // A failure no statement named is this boundary's: its commit, its lock.\n throw annotateMigrationFailure(failure, {\n step: \"reset\",\n strategy: neki ? \"stepwise\" : boundary,\n stateId: plan.replayPath.at(-1),\n });\n }\n };\n const completeClearEvidence = async (\n target: Parameters<typeof appendLedger>[0]\n ) => {\n for (const dispatch of plan.clearDispatches) {\n if (!liveClearDispatches.has(dispatch.dispatchId)) {\n await confirmResetDispatch(target, command, graph, attemptId, dispatch);\n }\n }\n };\n const admit = async (target: Parameters<typeof appendLedger>[0]) => {\n const pending = admissionPending;\n if (!pending) return;\n admissionPending = undefined;\n await pending(target);\n };\n const runPendingClear = async (\n target: Parameters<typeof appendLedger>[0],\n boundary: \"transactional\" | \"stepwise\"\n ) => {\n if (clearPending) {\n const clear = clearPending;\n clearPending = undefined;\n await executeResetClear(\n target,\n command,\n clear,\n attemptId,\n graph,\n boundary\n );\n }\n if (clearEvidencePending) {\n await completeClearEvidence(target);\n clearEvidencePending = false;\n }\n };\n // A driver whose index cannot share a transaction with what a clear wrote commits\n // the clear first, whatever boundary the program that follows asks for.\n if (\n clearPending &&\n (groups[0]?.boundary === \"stepwise\" || command.buildsApart?.([], true))\n ) {\n await runBoundary(\n \"transactional\",\n resetProgram(clearPending, []),\n async (target) => {\n await admit(target);\n await runPendingClear(target, neki ? \"stepwise\" : \"transactional\");\n }\n );\n }\n if (!clearPending && groups[0]?.boundary === \"stepwise\" && admissionPending) {\n await runBoundary(\"transactional\", [], admit);\n }\n if (groups.length === 0) {\n const statements = resetProgram(clearPending, []);\n await runBoundary(\"transactional\", statements, async (target) => {\n await admit(target);\n await runPendingClear(target, neki ? \"stepwise\" : \"transactional\");\n await finish(target);\n });\n return;\n }\n for (const [index, group] of groups.entries()) {\n const statements = resetProgram(clearPending, group.items);\n await runBoundary(group.boundary, statements, async (target) => {\n await admit(target);\n await runPendingClear(target, group.boundary);\n for (const edge of group.items) {\n await executeResetReplayEdge(\n target,\n command,\n graph,\n edge,\n attemptId,\n models\n );\n }\n if (index === groups.length - 1) await finish(target);\n });\n }\n}\n\nasync function executeResetReplayEdge(\n pinned: Parameters<typeof executeOperations>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n edge: PreparedResetReplayEdge,\n attemptId: Sha256,\n models: MigrationClient[\"$schema\"]\n): Promise<void> {\n const { from, to, transition, state, blob, boundary, operations } = edge;\n const events = attemptEvents(\n {\n estateHash: graph.estateHash,\n snapshotHash: state.snapshotHash,\n sqlHash: state.sqlHash,\n fromState: from,\n toState: to,\n transitionHash: transition.transitionHash,\n direction: \"reset\",\n },\n attemptId\n );\n await executeOperations(\n pinned,\n blob,\n operations,\n boundary,\n (progress, effect, failure) =>\n appendLedger(\n pinned,\n command,\n events.event(\n \"reset-step-confirmed\",\n progress.skipped ? \"committed\" : effect,\n progress,\n failure\n )\n ),\n command.namespace,\n { fromState: from, toState: to, step: \"reset-replay\" }\n );\n // Replayed manual SQL is canonicalized exactly as apply canonicalizes it.\n await command.canonicalizeLiveStorage?.(\n pinned,\n operations,\n models,\n requireStateSnapshot(graph, to)\n );\n await assertAllChecks(\n pinned,\n blob,\n state.destinationChecks,\n command.namespace,\n \"Reset replay failed destination checks\"\n );\n}\n","/**\n * V1 operator commands: status, verify, log, baseline, reanchor, prune,\n * down, resolve, reset.\n * Status/verify/log are read-only and never bootstrap missing control tables.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { bytesEqual, canonicalizeJson } from \"./canonical-json\";\nimport { qualifiedName, readInvalidIndexes } from \"./catalog-runtime\";\nimport type { MigrationClient } from \"./client-driver\";\nimport {\n advanceMarker,\n appendLedger,\n attemptEvents,\n ensureControlTables,\n isTableMissing,\n ledgerEvent,\n type MigrationControlRead,\n refuseIncompatibleHistory,\n unfinishedAttempts,\n} from \"./control\";\nimport { diff, isDestructiveOperation } from \"./differ\";\nimport { type NormalizedDownOptions, normalizeDownOptions } from \"./down-input\";\nimport {\n assertAllChecks,\n evaluateAllChecks,\n executeOperations,\n} from \"./execute-dispatch\";\nimport {\n loadMigrationGraph,\n type MigrationGraph,\n parentTransition,\n requireStateSnapshot,\n resolveStateSelector,\n routeEdges,\n selectRoute,\n statesFrom,\n} from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport { introspectManaged } from \"./introspect-managed\";\nimport {\n commitLockedTransaction,\n letLockGo,\n resolveCommandDriver,\n runProgram,\n withLockedMigrationProducer,\n} from \"./pinned-session\";\nimport {\n assertAdoptable,\n assertLockedSinceDecision,\n assertNoDrift,\n managedAt,\n markerStanding,\n proveLive,\n} from \"./proof\";\nimport { renderMigrationReview } from \"./public-view\";\nimport { fingerprintLive } from \"./push-fingerprint\";\nimport { approveDestructiveOperations } from \"./resolver\";\nimport {\n countUnanswered,\n openCommand,\n readCommandControl,\n remainingSteps,\n} from \"./resume\";\nimport {\n assertTransactionalBoundaryHonored,\n classifyStoredAtomicity,\n groupContiguousAtomicity,\n refuseSqliteStepwise,\n stepStatements,\n} from \"./runtime-dispatch\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport type {\n MigrationStorageReader,\n MigrationStorageWriter,\n} from \"./storage/contract\";\nimport {\n managedTables,\n selectManagedSnapshot,\n withManagedTables,\n} from \"./target\";\nimport type {\n AmbiguousChange,\n DiffOperation,\n ResolveCallback,\n SchemaSnapshot,\n} from \"./types\";\nimport { corrupt } from \"./v1-parse-shared\";\nimport { encodeSnapshot } from \"./v1-parse-snapshot\";\nimport type {\n BaselineOptions,\n DownPreviewEdgeV1,\n DownV1Options,\n DownV1Result,\n LedgerEventV1,\n MarkerPathEdgeV1,\n MigrationMarkerV1,\n ReanchorOptions,\n ResolveV1Options,\n StateSelector,\n} from \"./v1-types\";\n\nexport { logV1 } from \"./log-v1\";\nexport { resetV1 } from \"./reset-v1\";\nexport { type StatusV1Result, statusV1 } from \"./status-v1\";\nexport { type VerifyV1Result, verifyV1 } from \"./verify-v1\";\n\nconst invalidState = (message: string) =>\n new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_STATE);\nconst notFound = (message: string) =>\n new MigrationError(message, VibORMErrorCode.MIGRATION_NOT_FOUND);\nconst markerConflict = (message: string) =>\n new MigrationError(message, VibORMErrorCode.MIGRATION_MARKER_CONFLICT);\nconst unfinishedError = (message: string) =>\n new MigrationError(message, VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT);\n\nexport async function baselineV1(\n client: MigrationClient,\n storage: MigrationStorageReader,\n options: BaselineOptions\n): Promise<{ readonly stateId: Sha256 }> {\n const graph = await loadMigrationGraph(storage);\n const driver = openCommand(client, graph, \"effectful\", \"baseline()\");\n const target = resolveStateSelector(graph, options.to);\n const path = selectRoute(graph, null, target, options.via);\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const control = await readCommandControl(pinned, command, true);\n const { marker, ledger } = control;\n if (marker || unfinishedAttempts(ledger).length > 0)\n throw invalidState(\n \"baseline requires unmarked DB with no open attempt\"\n );\n refuseIncompatibleHistory(marker, ledger);\n assertStructuralRoute(graph, path, \"baseline\");\n await command.preflightSchemaRequirements(\n [requireStateSnapshot(graph, target)],\n (sql, params) => pinned._executeRaw(sql, params),\n []\n );\n await assertAdoptable(pinned, command, graph, null, path);\n if (control.presence.kind !== \"present\") {\n await ensureControlTables(pinned, command);\n await commitLockedTransaction(pinned, command);\n await assertLockedSinceDecision(pinned, pinned, command, null);\n }\n await proveLive(\n pinned,\n managedAt(command, graph, target),\n graph,\n graph.states.get(target)!.snapshotHash,\n async (differences) =>\n `baseline requires exact live match: ${await differences()}`\n );\n await adoptRoute(pinned, command, graph, path, null);\n return { stateId: target };\n }\n );\n}\n\n/**\n * Plan T3: after a restore left this history older than the database, moves\n * a marker naming a state the history lacks onto the one known state the live\n * schema matches, with baseline's proof and a baseline boundary. `to` adopts\n * the state it names instead: the consent several matching states need.\n */\nexport async function reanchorV1(\n client: MigrationClient,\n storage: MigrationStorageReader,\n options: ReanchorOptions = {}\n): Promise<{ readonly stateId: Sha256 }> {\n const graph = await loadMigrationGraph(storage);\n const driver = openCommand(client, graph, \"effectful\", \"reanchor()\");\n const named = options.to && resolveStateSelector(graph, options.to);\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const { marker, ledger } = await readCommandControl(pinned, command);\n if (!marker || markerStanding(graph, marker) === \"known\")\n throw invalidState(\"reanchor requires marker absent from history\");\n if (unfinishedAttempts(ledger).length > 0)\n throw invalidState(\"reanchor refused with unfinished attempt\");\n // One read of everything any candidate manages, then each candidate\n // compared with what it manages, selected in memory.\n const candidates = named ? [named] : [...graph.states.keys()];\n const read = await introspectManaged(\n pinned,\n withManagedTables(\n command,\n managedTables(\n graph.descriptor.target.tables,\n candidates.map((stateId) => requireStateSnapshot(graph, stateId))\n )\n )\n );\n const liveAt = (stateId: Sha256) =>\n selectManagedSnapshot(read, managedAt(command, graph, stateId).target);\n // One fingerprint per distinct selection: without a list, exactly one.\n const liveHashes = new Map<string, Promise<string>>();\n const liveHash = (stateId: Sha256) => {\n const key = JSON.stringify(\n managedAt(command, graph, stateId).target.tables ?? null\n );\n let hash = liveHashes.get(key);\n if (hash === undefined) {\n hash = fingerprintLive(liveAt(stateId), command, pinned);\n liveHashes.set(key, hash);\n }\n return hash;\n };\n const matches: Sha256[] = [];\n for (const stateId of candidates) {\n const snapshot = requireStateSnapshot(graph, stateId);\n if (\n (await liveHash(stateId)) ===\n (await fingerprintLive(snapshot, command, pinned))\n ) {\n matches.push(stateId);\n }\n }\n const reference =\n named ?? (graph.leaves.length === 1 ? graph.leaves[0] : undefined);\n if (matches.length === 0) {\n const differences = reference\n ? ` Differences from ${reference}: ${JSON.stringify(await diff(liveAt(reference), requireStateSnapshot(graph, reference)))}`\n : \"\";\n throw new MigrationError(\n `reanchor found no matching state.${differences}`,\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n if (matches.length > 1)\n throw invalidState(\n `Multiple states match live (${matches.join(\", \")}); specify reanchor({ to }).`\n );\n const target = matches[0]!;\n if (marker.path.some((edge) => edge.stateId === target))\n throw invalidState(\n `reanchor refuses ${target}: already on marker path.`\n );\n const path = selectRoute(graph, null, target, options.via);\n assertStructuralRoute(graph, path, \"reanchor\");\n await command.preflightSchemaRequirements(\n [requireStateSnapshot(graph, target)],\n (sql, params) => pinned._executeRaw(sql, params),\n []\n );\n await assertAdoptable(pinned, command, graph, null, path);\n await adoptRoute(pinned, command, graph, path, marker);\n return { stateId: target };\n }\n );\n}\n\n/** Baseline's proof of a root route: no manual, opaque or data-only edge. */\nfunction assertStructuralRoute(\n graph: MigrationGraph,\n path: readonly Sha256[],\n command: \"baseline\" | \"reanchor\"\n): void {\n for (const { from, transition, state } of routeEdges(graph, null, path)) {\n const parentSnapshot =\n from === null\n ? graph.emptySnapshotHash\n : graph.states.get(from)?.snapshotHash;\n if (\n transition.operations.some(\n (operation) =>\n operation.origin === \"manual\" || operation.risk === \"opaque\"\n ) ||\n parentSnapshot === state.snapshotHash\n ) {\n throw invalidState(\n `${command} refuses manual, opaque, or data-only transitions`\n );\n }\n }\n}\n\n/**\n * Publishes the marker re-rooted on `path`, its first edge a baseline\n * boundary, in place of `current` (compare-and-swap), with the event that\n * says so: `baselined` without a marker before, `reanchored` with one. In one\n * transaction when the producer can.\n */\nasync function adoptRoute(\n pinned: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n path: readonly Sha256[],\n current: MigrationMarkerV1 | null\n): Promise<void> {\n const edges = routeEdges(graph, null, path).map(\n ({ to, transition }, index) => ({\n stateId: to,\n transitionHash: transition.transitionHash,\n baselineBoundary: index === 0,\n })\n );\n const target = path.at(-1)!;\n const publish = async (producer: AnyDriver) => {\n const next = await advanceMarker(\n producer,\n command,\n graph.estateHash,\n current,\n edges,\n graph.states.get(target)!.snapshotHash\n );\n await appendLedger(\n producer,\n command,\n ledgerEvent({\n attemptId: next.pathHash,\n kind: current ? \"reanchored\" : \"baselined\",\n estateHash: graph.estateHash,\n snapshotHash: next.snapshotHash,\n sqlHash: null,\n fromState: current?.stateId ?? null,\n toState: target,\n transitionHash: null,\n direction: \"baseline\",\n operationId: null,\n dispatchId: null,\n effectState: \"none\",\n })\n );\n };\n if (pinned.supportsTransactions) {\n await pinned.withTransaction((transaction) => publish(transaction));\n } else {\n await publish(pinned);\n }\n}\n\nexport interface PruneOptions {\n /** The authored checkpoint (`generate({ from: null })`) to keep history from. */\n readonly checkpoint: StateSelector;\n /** A fresh history: the source is never changed. */\n readonly into: MigrationStorageWriter;\n}\n\nexport interface PruneResult {\n /** The states `into` now holds from this history. */\n readonly states: readonly Sha256[];\n}\n\n/**\n * Plan T4: copies the checkpoint and the states `statesFrom` keeps after it\n * into a fresh history. Storage stays append-only, so pruning is a copy: what\n * it leaves out is what `check()` would report as orphaned, once the earlier\n * manifests were gone. A marker on a dropped state is moved by `reanchor()`.\n */\nexport async function pruneV1(\n storage: MigrationStorageReader,\n options: PruneOptions\n): Promise<PruneResult> {\n const graph = await loadMigrationGraph(storage);\n const kept = statesFrom(\n graph,\n resolveStateSelector(graph, options.checkpoint)\n );\n const { into } = options;\n await into.publishEstate(\n await present(\n storage.readEstate(),\n \"estate.json\",\n canonicalizeJson(graph.descriptor)\n )\n );\n const copiedSnapshots = new Set<Sha256>();\n for (const id of kept) {\n const { snapshotHash, snapshotArtifactHash, sqlHash } =\n graph.states.get(id)!;\n const dependencies: Sha256[] = [];\n let hash: Sha256 | undefined = snapshotArtifactHash ?? snapshotHash;\n while (hash !== undefined && !copiedSnapshots.has(hash)) {\n dependencies.push(hash);\n hash = graph.snapshotArtifacts.get(hash)?.baseArtifactHash;\n }\n for (const dependency of dependencies.reverse()) {\n const artifact = graph.snapshotArtifacts.get(dependency);\n const expected =\n artifact?.bytes ??\n encodeSnapshot(requireStateSnapshot(graph, null)).bytes;\n // Only the implicit empty schema needs no stored object. An explicit\n // reference, including an empty delta base, must still remain present.\n const bytes =\n !artifact && dependency === graph.emptySnapshotHash\n ? ((await storage.readSnapshot(dependency)) ?? expected)\n : await present(storage.readSnapshot(dependency), dependency);\n if (!bytesEqual(bytes, expected))\n corrupt(`Snapshot ${dependency} changed during prune`);\n await into.publishSnapshot(dependency, expected.slice());\n copiedSnapshots.add(dependency);\n }\n await into.publishSql(sqlHash, graph.sql.get(sqlHash)!);\n await into.publishState(\n id,\n await present(\n storage.readState(id),\n id,\n canonicalizeJson(graph.states.get(id)!)\n )\n );\n }\n return { states: [...kept] };\n}\n\n/** Refuse missing objects and revalidate fresh manifest/descriptor reads. */\nasync function present(\n read: Promise<Uint8Array | null>,\n artifact: string,\n expected?: Uint8Array\n): Promise<Uint8Array> {\n const bytes = await read;\n if (!bytes) corrupt(`${artifact} missing during prune`);\n if (expected && !bytesEqual(bytes, expected))\n corrupt(`${artifact} changed during prune`);\n return expected ?? bytes;\n}\n\nexport async function downV1(\n client: MigrationClient,\n storage: MigrationStorageReader,\n options: DownV1Options = {}\n): Promise<DownV1Result> {\n const request = normalizeDownOptions(options);\n const graph = await loadMigrationGraph(storage);\n const driver = openCommand(\n client,\n graph,\n request.dryRun ? \"read-only\" : \"effectful\",\n \"down()\"\n );\n if (request.dryRun) {\n const producer = client.$driver;\n const command = await resolveCommandDriver(producer, driver);\n const { close, removed, refusal } = await planRollback(\n producer,\n command,\n graph,\n await readCommandControl(producer, command),\n request,\n true\n );\n return {\n path: close\n ? [close.item.edge.stateId]\n : removed.map((edge) => edge.stateId),\n preview: true,\n edges: [...removed]\n .reverse()\n .map((edge) => previewRollbackEdge(graph, edge)),\n refusal,\n };\n }\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const control = await readCommandControl(pinned, command);\n const { close, removed, run } = await planRollback(\n pinned,\n command,\n graph,\n control,\n request,\n false\n );\n if (close) {\n await command.preflightSchemaRequirements(\n [requireStateSnapshot(graph, close.item.nextState)],\n (sql, params) => pinned._executeRaw(sql, params),\n []\n );\n await runProgram(pinned, command, undefined, (producer) =>\n closeCompletedRollback(\n producer,\n command,\n graph,\n close.item,\n close.attempt,\n control.ledger,\n control.marker\n )\n );\n return { path: [close.item.edge.stateId], preview: false };\n }\n if (!run) return { path: [], preview: false };\n const { prepared, attempt } = run;\n const statementsOf = (item: PreparedRollback) =>\n stepStatements(item.blob, item.rollback.operations);\n let current = run.marker;\n for (const group of groupContiguousAtomicity(prepared, statementsOf)) {\n await runProgram(\n pinned,\n command,\n {\n transactional: group.boundary === \"transactional\",\n statements: group.items.flatMap(statementsOf),\n },\n async (producer) => {\n // Only the attempt `down` resumes is its own: any other one open\n // now was opened while the lock was let go.\n await assertLockedSinceDecision(\n pinned,\n producer,\n command,\n current,\n group.items[0] === prepared[0] && attempt !== undefined\n );\n for (const item of group.items) {\n current = await executeRollbackEdge(\n producer,\n command,\n graph,\n item,\n current,\n item === prepared[0] ? attempt : undefined,\n control.ledger,\n client.$schema\n );\n }\n }\n );\n }\n return { path: removed.map((edge) => edge.stateId), preview: false };\n }\n );\n}\n\ntype PreparedRollback = ReturnType<typeof prepareRollbackEdge>;\n\ninterface RollbackPlan {\n /** The first refusal of a preview; `down` throws it instead. */\n readonly refusal: { code: string; message: string } | null;\n /** A rollback that finished before it was recorded: `down` closes it. */\n readonly close?: {\n readonly item: PreparedRollback;\n readonly attempt: LedgerEventV1;\n };\n /** The marker edges `down` removes. */\n readonly removed: MigrationMarkerV1[\"path\"];\n /** Present when `down` reverses `removed`, newest edge first. */\n readonly run?: {\n readonly marker: MigrationMarkerV1;\n readonly prepared: readonly PreparedRollback[];\n readonly attempt: LedgerEventV1 | undefined;\n };\n}\n\n/**\n * What `down` decides before its first effect, read-only and in its order, so\n * the preview refuses where `down` refuses. `previewing` returns a refusal of\n * the attempt or of the checks as data (`down` throws it); without one, a\n * preview still names the edges.\n */\nasync function planRollback(\n producer: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n { marker, ledger }: MigrationControlRead,\n request: NormalizedDownOptions,\n previewing: boolean\n): Promise<RollbackPlan> {\n assertExpectedRevision(marker, request);\n let refusal: RollbackPlan[\"refusal\"] = null;\n let attempt: LedgerEventV1 | undefined;\n try {\n attempt = admitRollbackAttempt(ledger);\n } catch (error) {\n if (!previewing) throw error;\n refusal = refusalOf(error);\n }\n const { supportsTransactions } = producer;\n if (attempt && attempt.toState === (marker?.stateId ?? null)) {\n const item = prepareRollbackAttempt(\n graph,\n command,\n supportsTransactions,\n attempt\n );\n return { refusal, close: { item, attempt }, removed: [] };\n }\n if (!marker) {\n // `down` refuses the attempt before it finds nothing to roll back.\n if (refusal) return { refusal, removed: [] };\n throw notFound(\"Nothing to roll back\");\n }\n const removed = rollbackSlice(graph, marker, request);\n // `down` checks nothing more when it has nothing to roll back.\n if (refusal || removed.length === 0) return { refusal, removed };\n try {\n const reverse = [...removed].reverse();\n for (const edge of reverse) assertReversibleEdge(graph, edge);\n const prepared = reverse.map((edge) =>\n prepareRollbackEdge(graph, command, supportsTransactions, edge)\n );\n await command.preflightSchemaRequirements(\n [\n requireStateSnapshot(graph, marker.stateId),\n ...prepared.map((item) => requireStateSnapshot(graph, item.nextState)),\n ],\n (sql, params) => producer._executeRaw(sql, params),\n prepared.flatMap((item) =>\n stepStatements(item.blob, item.rollback.operations)\n ),\n // On Neki each statement commits alone: only one dispatch's own\n // statements cannot be divided.\n true\n );\n if (attempt) {\n assertResumesSelectedPath(\n graph,\n command,\n supportsTransactions,\n attempt,\n prepared[0]!\n );\n } else {\n await assertNoDrift(\n producer,\n managedAt(command, graph, marker.stateId, prepared[0]!.nextState),\n graph,\n marker\n );\n }\n await approveRollbackLosses(\n producer,\n command,\n graph,\n prepared,\n request.resolve\n );\n return { refusal, removed, run: { marker, prepared, attempt } };\n } catch (error) {\n if (!previewing) throw error;\n return { refusal: refusalOf(error), removed };\n }\n}\n\nexport async function resolveV1(\n client: MigrationClient,\n storage: MigrationStorageReader,\n options: ResolveV1Options\n): Promise<{ readonly outcome: ResolveV1Options[\"outcome\"] }> {\n const graph = await loadMigrationGraph(storage);\n const driver = openCommand(client, graph, \"effectful\", \"resolve()\");\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const { ledger } = await readCommandControl(pinned, command);\n const open = unfinishedAttempts(ledger);\n if (open.length !== 1) {\n throw invalidState(\n open.length === 0\n ? \"resolve requires an unfinished attempt\"\n : \"resolve requires exactly one unfinished attempt\"\n );\n }\n const attempt = open[0]!;\n if (attempt.kind === \"reset-started\") {\n throw invalidState(\"Unfinished reset must be resumed by reset()\");\n }\n if (attempt.direction === \"rollback\") {\n throw invalidState(\"Unfinished rollback must be resumed by down()\");\n }\n const to = attempt.toState;\n const from = attempt.fromState;\n if (!to) corrupt(\"Unfinished attempt missing target\");\n const state = graph.states.get(to);\n if (!state) corrupt(\"Unfinished attempt target missing\");\n const blob = graph.sql.get(state.sqlHash)!;\n const transition = parentTransition(graph, from, to);\n const destSnapshot = requireStateSnapshot(graph, to);\n const originSnapshot = requireStateSnapshot(graph, from);\n const statements = stepStatements(blob, transition.operations);\n // Only a retry runs the transition: its program is refused as apply's.\n await command.preflightSchemaRequirements(\n [originSnapshot, destSnapshot],\n (sql, params) => pinned._executeRaw(sql, params),\n options.outcome === \"retry\" ? statements : [],\n // On Neki each statement commits alone.\n true\n );\n // Completing or retrying lands on the destination, which manages a\n // table the edge adopts; rolling back leaves it outside.\n if (options.outcome !== \"rolled-back\") {\n await assertAdoptable(pinned, command, graph, from, [to]);\n }\n // Both ends of the edge, read once: the destination manages a table\n // the edge adopts, the origin does not.\n const across = managedAt(command, graph, to, from);\n if (options.outcome !== \"retry\") {\n await repairInvalidIndexes(\n pinned,\n across,\n statements,\n options.outcome === \"complete\" ? destSnapshot : originSnapshot\n );\n }\n const read = await introspectManaged(pinned, across);\n const fp = (snapshot: SchemaSnapshot) =>\n fingerprintLive(snapshot, command, pinned);\n const destHolds =\n (await fp(read)) === (await fp(destSnapshot)) &&\n (await evaluateAllChecks(\n pinned,\n blob,\n state.destinationChecks,\n command.namespace\n ));\n const originHolds =\n (await fp(\n selectManagedSnapshot(\n read,\n managedAt(command, graph, from, to).target\n )\n )) === (await fp(originSnapshot)) &&\n (await evaluateAllChecks(\n pinned,\n blob,\n transition.originChecks,\n command.namespace\n ));\n const manualOpaque = transition.operations.some(\n (operation) =>\n operation.origin === \"manual\" &&\n operation.steps.some((step) => step.retry === \"opaque\")\n );\n // Marking an outcome is one transaction where the producer has one.\n const record = { transactional: true, statements: [] };\n if (options.outcome === \"complete\") {\n if (\n !destHolds ||\n (manualOpaque && state.destinationChecks.length === 0)\n )\n throw invalidState(\"resolve complete requires destination proof\");\n await runProgram(pinned, command, record, async (producer) => {\n await command.canonicalizeLiveStorage?.(\n producer,\n transition.operations,\n client.$schema,\n destSnapshot\n );\n await finishResolve(producer, command, graph, attempt, \"applied\", to);\n });\n return { outcome: \"complete\" };\n }\n if (options.outcome === \"rolled-back\") {\n refuseOpaqueEffect(transition, blob, attempt, ledger);\n if (\n !originHolds ||\n (manualOpaque && transition.originChecks.length === 0)\n )\n throw invalidState(\"resolve rolled-back requires origin proof\");\n await runProgram(pinned, command, record, (producer) =>\n finishResolve(producer, command, graph, attempt, \"rolled-back\", from)\n );\n return { outcome: \"rolled-back\" };\n }\n if (manualOpaque)\n throw invalidState(\"resolve cannot retry opaque dispatch\");\n if (\n transition.operations.some((operation) =>\n operation.steps.some((step) => step.retry === \"opaque\")\n ) &&\n !originHolds\n )\n throw invalidState(\"resolve retry requires origin state\");\n assertTransactionalBoundaryHonored(\n pinned.supportsTransactions,\n transition.requestedForwardBoundary\n );\n const boundary = classifyStoredAtomicity(\n command,\n transition.requestedForwardBoundary,\n transition.operations,\n blob\n );\n // A recreation is refused without a transaction: its lift is unproven.\n await runProgram(\n pinned,\n command,\n { transactional: boundary === \"transactional\", statements },\n async (producer) => {\n await executeOperations(\n producer,\n blob,\n transition.operations,\n boundary,\n undefined,\n command.namespace,\n { fromState: from, toState: to, step: \"resolve\" }\n );\n await assertAllChecks(\n producer,\n blob,\n state.destinationChecks,\n command.namespace,\n \"Retry did not reach the destination\"\n );\n await proveLive(\n producer,\n across,\n graph,\n state.snapshotHash,\n () => \"Retry did not reach the destination\"\n );\n await finishResolve(producer, command, graph, attempt, \"applied\", to);\n }\n );\n return { outcome: \"retry\" };\n }\n );\n}\n\n/**\n * The index a `CREATE`/`DROP`/`REINDEX INDEX CONCURRENTLY` statement names,\n * schema prefix dropped. An unnamed `CREATE INDEX CONCURRENTLY ON t` is never\n * matched; its PG-chosen name is left to the V11023 refusal. (DROP INDEX\n * CONCURRENTLY takes one name only.)\n */\nconst CONCURRENT_INDEX_NAME =\n /\\bINDEX\\s+CONCURRENTLY\\s+(?:IF\\s+(?:NOT\\s+)?EXISTS\\s+)?(?!ON\\b)(?:(?:\"(?:[^\"]|\"\")+\"|[A-Za-z_][\\w$]*)\\s*\\.\\s*)?(\"(?:[^\"]|\"\")+\"|[A-Za-z_][\\w$]*)/gi;\n/** The suffix of the `_ccnew`/`_ccold` copy an interrupted `REINDEX CONCURRENTLY` leaves INVALID. */\nconst REINDEX_REMNANT = /^_cc(?:new|old)\\d*$/;\n\n/**\n * Repairs the INVALID indexes the unfinished attempt's own CONCURRENTLY\n * statements left behind — the index each names, and the `<name>_ccnew` /\n * `<name>_ccold` remnant of an interrupted `REINDEX CONCURRENTLY` — towards the snapshot the\n * requested outcome asserts: an index that snapshot declares is rebuilt, any\n * other is dropped, both CONCURRENTLY so writes keep flowing. An invalid index\n * the attempt never named (another session's build, still running perhaps) is\n * left alone, and the proof that follows refuses on it with V11023. An invalid\n * index belongs to neither state, so the repair cannot turn a false proof true.\n */\nasync function repairInvalidIndexes(\n pinned: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n statements: readonly string[],\n expected: SchemaSnapshot\n): Promise<void> {\n const named = statements.flatMap(concurrentIndexNames);\n if (named.length === 0) return;\n for (const { table, index } of await readInvalidIndexes(pinned, command)) {\n if (\n !named.some(\n (name) =>\n index === name ||\n (index.startsWith(name) &&\n REINDEX_REMNANT.test(index.slice(name.length)))\n )\n )\n continue;\n const rebuild = expected.tables.some(\n (declared) =>\n declared.name === table &&\n declared.indexes.some((item) => item.name === index)\n );\n await pinned._executeRaw(\n `${rebuild ? \"REINDEX INDEX\" : \"DROP INDEX\"} CONCURRENTLY ${qualifiedName(command, index)}`\n );\n }\n}\n\n/** The indexes a statement's `INDEX CONCURRENTLY` clauses name. */\nfunction concurrentIndexNames(text: string): string[] {\n return [...text.matchAll(CONCURRENT_INDEX_NAME)].map(([, name = \"\"]) =>\n name.startsWith('\"')\n ? name.slice(1, -1).replaceAll('\"\"', '\"')\n : name.toLowerCase()\n );\n}\n\nasync function finishResolve(\n pinned: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n attempt: LedgerEventV1,\n kind: \"applied\" | \"rolled-back\",\n to: Sha256 | null\n): Promise<void> {\n const { marker } = await readCommandControl(pinned, command);\n if (kind === \"applied\" && to && marker?.stateId !== to) {\n const transition = parentTransition(graph, attempt.fromState, to);\n await advanceMarker(\n pinned,\n command,\n graph.estateHash,\n marker,\n [\n ...(marker?.path ?? []),\n {\n stateId: to,\n transitionHash: attempt.transitionHash ?? transition.transitionHash,\n baselineBoundary: false,\n },\n ],\n graph.states.get(to)!.snapshotHash\n );\n }\n if (kind === \"rolled-back\" && marker && marker.stateId === attempt.toState) {\n const nextPath = marker.path.slice(0, -1);\n await advanceMarker(\n pinned,\n command,\n graph.estateHash,\n marker,\n nextPath,\n snapshotHashOf(graph, nextPath.at(-1)?.stateId ?? null)\n );\n }\n await appendLedger(\n pinned,\n command,\n ledgerEvent({\n attemptId: attempt.attemptId,\n kind: \"resolved\",\n estateHash: graph.estateHash,\n snapshotHash: snapshotHashOf(graph, to),\n sqlHash: attempt.sqlHash,\n fromState: attempt.fromState,\n toState: to,\n transitionHash: attempt.transitionHash,\n direction: \"resolve\",\n operationId: null,\n dispatchId: null,\n effectState: \"none\",\n })\n );\n}\n\n/** The snapshot a state, or the empty origin, authenticates. */\nfunction snapshotHashOf(graph: MigrationGraph, stateId: Sha256 | null): Sha256 {\n return stateId\n ? graph.states.get(stateId)!.snapshotHash\n : graph.emptySnapshotHash;\n}\n\nfunction prepareRollbackEdge(\n graph: MigrationGraph,\n command: Parameters<typeof appendLedger>[1],\n supportsTransactions: boolean,\n edge: MarkerPathEdgeV1\n) {\n const state = graph.states.get(edge.stateId)!;\n const parent = state.parents.find(\n (item) => item.transitionHash === edge.transitionHash\n )!;\n const blob = graph.sql.get(state.sqlHash)!;\n const rollback = parent.rollback;\n if (rollback.kind === \"irreversible\") {\n throw new MigrationError(\n rollback.reason,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n const requested =\n rollback.kind === \"manual\" ? rollback.requestedBoundary : null;\n assertTransactionalBoundaryHonored(supportsTransactions, requested);\n refuseSqliteStepwise(command, requested, edge.stateId);\n return {\n edge,\n state,\n parent,\n blob,\n rollback,\n boundary: classifyStoredAtomicity(\n command,\n requested,\n rollback.operations,\n blob\n ),\n nextState: parent.fromState,\n };\n}\n\n/**\n * One edge of a down preview: its rollback rendered as `show --sql` renders\n * it, without the forward half or its forward approvals.\n */\nfunction previewRollbackEdge(\n graph: MigrationGraph,\n edge: MarkerPathEdgeV1\n): DownPreviewEdgeV1 {\n const state = graph.states.get(edge.stateId);\n const parent = state?.parents.find(\n (item) => item.transitionHash === edge.transitionHash\n );\n const blob = state && graph.sql.get(state.sqlHash);\n if (!(parent && blob)) corrupt(\"Rollback missing transition or SQL\");\n const { approvals: _forward, ...transition } = parent;\n return {\n stateId: edge.stateId,\n toState: parent.fromState,\n sql: renderMigrationReview(\n [{ ...transition, originChecks: [], operations: [] }],\n [],\n blob\n ),\n };\n}\n\n/** A migration refusal as plain data; any other error is rethrown. */\nfunction refusalOf(error: unknown): { code: string; message: string } {\n if (!(error instanceof MigrationError)) throw error;\n return { code: error.code, message: error.message };\n}\n\n/**\n * The one unfinished attempt `down` may resume: none, or a started rollback.\n * Anything else needs repair first.\n */\nfunction admitRollbackAttempt(\n ledger: readonly LedgerEventV1[]\n): LedgerEventV1 | undefined {\n const open = unfinishedAttempts(ledger);\n if (open.length > 1) {\n throw unfinishedError(\"Multiple unfinished attempts require manual repair\");\n }\n const attempt = open[0];\n if (\n attempt &&\n (attempt.kind !== \"started\" || attempt.direction !== \"rollback\")\n ) {\n throw unfinishedError(\"Unfinished attempt blocks ordinary work\");\n }\n return attempt;\n}\n\n/** An unfinished rollback resumes only as the first edge `down` selected. */\nfunction assertResumesSelectedPath(\n graph: MigrationGraph,\n command: Parameters<typeof appendLedger>[1],\n supportsTransactions: boolean,\n attempt: LedgerEventV1,\n first: PreparedRollback\n): void {\n const resumed = prepareRollbackAttempt(\n graph,\n command,\n supportsTransactions,\n attempt\n );\n if (\n resumed.edge.stateId !== first.edge.stateId ||\n resumed.nextState !== first.nextState ||\n resumed.edge.transitionHash !== first.edge.transitionHash\n ) {\n throw unfinishedError(\n \"Unfinished rollback does not match selected reverse path\"\n );\n }\n}\n\nfunction prepareRollbackAttempt(\n graph: MigrationGraph,\n command: Parameters<typeof appendLedger>[1],\n supportsTransactions: boolean,\n attempt: LedgerEventV1\n): PreparedRollback {\n if (!(attempt.fromState && attempt.transitionHash))\n corrupt(\"Unfinished rollback missing edge\");\n const item = prepareRollbackEdge(graph, command, supportsTransactions, {\n stateId: attempt.fromState,\n transitionHash: attempt.transitionHash,\n baselineBoundary: false,\n });\n if (\n attempt.toState !== item.nextState ||\n attempt.estateHash !== graph.estateHash ||\n attempt.snapshotHash !== item.state.snapshotHash ||\n attempt.sqlHash !== item.state.sqlHash\n )\n corrupt(\"Unfinished rollback edge mismatch\");\n return item;\n}\n\nasync function executeRollbackEdge(\n producer: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n item: PreparedRollback,\n current: MigrationMarkerV1,\n resume: LedgerEventV1 | undefined,\n ledger: readonly LedgerEventV1[],\n models: MigrationClient[\"$schema\"]\n): Promise<MigrationMarkerV1> {\n const { edge, state, blob, rollback, boundary, nextState } = item;\n if (\n current.stateId !== edge.stateId ||\n current.path.at(-1)?.stateId !== edge.stateId ||\n current.path.at(-1)?.transitionHash !== edge.transitionHash\n ) {\n throw markerConflict(\"Rollback marker does not match reversed edge\");\n }\n if (!resume) {\n await assertAllChecks(\n producer,\n blob,\n state.destinationChecks,\n command.namespace,\n \"Destination checks failed before rollback\"\n );\n }\n const events = attemptEvents(\n rollbackEventSeed(graph, item),\n resume?.attemptId\n );\n if (!resume) {\n await appendLedger(producer, command, events.event(\"started\", \"none\"));\n }\n await executeOperations(\n producer,\n blob,\n resume\n ? remainingRollbackOperations(graph, item, resume, ledger)\n : rollback.operations,\n boundary,\n (progress, effect, failure) =>\n appendLedger(\n producer,\n command,\n events.event(\n \"step-confirmed\",\n progress.skipped ? \"committed\" : effect,\n progress,\n failure\n )\n ),\n command.namespace,\n { fromState: edge.stateId, toState: nextState, step: \"down\" }\n );\n // Manual rollback SQL may store text typed queries cannot compare.\n await command.canonicalizeLiveStorage?.(\n producer,\n rollback.operations,\n models,\n requireStateSnapshot(graph, nextState)\n );\n const snapshotHash = await proveRolledBack(producer, command, graph, item);\n const next = await advanceMarker(\n producer,\n command,\n graph.estateHash,\n current,\n current.path.slice(0, -1),\n snapshotHash\n );\n await appendRolledBackEvent(producer, command, graph, item, events.attemptId);\n return next;\n}\n\nasync function closeCompletedRollback(\n producer: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n item: PreparedRollback,\n attempt: LedgerEventV1,\n ledger: readonly LedgerEventV1[],\n marker: MigrationMarkerV1 | null\n): Promise<void> {\n remainingRollbackOperations(graph, item, attempt, ledger);\n if (marker ? marker.stateId !== item.nextState : item.nextState !== null) {\n throw markerConflict(\"Rollback marker does not match unfinished edge\");\n }\n await proveRolledBack(producer, command, graph, item);\n await appendRolledBackEvent(\n producer,\n command,\n graph,\n item,\n attempt.attemptId\n );\n}\n\n/**\n * Proves a reversed edge reached its parent: the origin checks hold and the\n * live schema is the parent's snapshot, whose hash it returns.\n */\nasync function proveRolledBack(\n producer: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n { parent, blob, nextState, edge }: PreparedRollback\n): Promise<Sha256> {\n await assertAllChecks(\n producer,\n blob,\n parent.originChecks,\n command.namespace,\n \"Origin checks failed after rollback\"\n );\n const snapshotHash = snapshotHashOf(graph, nextState);\n // On the parent's side: a table the edge adopted is released, rows kept.\n await proveLive(\n producer,\n managedAt(command, graph, nextState, edge.stateId),\n graph,\n snapshotHash,\n () => \"Rollback did not reach the parent snapshot\"\n );\n return snapshotHash;\n}\n\n/** The fields every event of one reversed edge carries. */\nfunction rollbackEventSeed(\n graph: MigrationGraph,\n { edge, state, nextState }: PreparedRollback\n) {\n return {\n estateHash: graph.estateHash,\n snapshotHash: state.snapshotHash,\n sqlHash: state.sqlHash,\n fromState: edge.stateId,\n toState: nextState,\n transitionHash: edge.transitionHash,\n direction: \"rollback\",\n } as const;\n}\n\nasync function appendRolledBackEvent(\n producer: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n item: PreparedRollback,\n attemptId: Sha256\n): Promise<void> {\n const arrived = {\n ...rollbackEventSeed(graph, item),\n snapshotHash: snapshotHashOf(graph, item.nextState),\n };\n await appendLedger(\n producer,\n command,\n attemptEvents(arrived, attemptId).event(\"rolled-back\", \"committed\")\n );\n}\n\nfunction remainingRollbackOperations(\n graph: MigrationGraph,\n item: PreparedRollback,\n attempt: LedgerEventV1,\n ledger: readonly LedgerEventV1[]\n): PreparedRollback[\"rollback\"][\"operations\"] {\n return remainingSteps(\n ledger,\n attempt,\n {\n direction: \"rollback\",\n estateHash: graph.estateHash,\n fromState: item.edge.stateId,\n toState: item.nextState,\n transitionHash: item.edge.transitionHash,\n sqlHash: item.state.sqlHash,\n operations: item.rollback.operations,\n boundary: item.boundary,\n },\n \"Rollback\"\n ).operations;\n}\n\nfunction assertReversibleEdge(\n graph: MigrationGraph,\n edge: MarkerPathEdgeV1\n): void {\n const state = graph.states.get(edge.stateId);\n if (!state) corrupt(\"Rollback target missing\");\n const parent = state.parents.find(\n (item) => item.transitionHash === edge.transitionHash\n );\n if (!parent) corrupt(\"Rollback transition missing\");\n if (parent.rollback.kind === \"irreversible\") {\n throw new MigrationError(\n parent.rollback.reason,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n}\n\n/** `down({ expectRevision })`: the marker must still be the one the caller read. */\nfunction assertExpectedRevision(\n marker: MigrationMarkerV1 | null,\n request: NormalizedDownOptions\n): void {\n if (\n request.expectRevision === undefined ||\n marker?.revision === request.expectRevision\n ) {\n return;\n }\n throw markerConflict(\n `down expected revision ${request.expectRevision}, got ${marker?.revision ?? \"none\"}`\n );\n}\n\n/**\n * Puts each destructive change the rollback makes to a table holding rows to\n * `resolve`, as generate and push ask (plan S4): a retried or mistaken `down`\n * cannot drop data unasked. Only edges whose stored rollback is destructive\n * are diffed: a manual rollback is SQL its author wrote and published, often\n * to move the rows back before a drop, so it is not asked again. An ambiguous\n * change counts as the drop it may be. A table an earlier edge of the path\n * recreates is absent live, and holds no rows. A table the edge adopts is\n * not dropped at all.\n */\nasync function approveRollbackLosses(\n producer: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n prepared: readonly PreparedRollback[],\n resolve: ResolveCallback | undefined\n): Promise<void> {\n const losses: DiffOperation[] = [];\n for (const item of prepared) {\n if (!item.rollback.operations.some((op) => op.risk === \"destructive\")) {\n continue;\n }\n const { operations, ambiguousChanges } = await diff(\n requireStateSnapshot(graph, item.edge.stateId),\n requireStateSnapshot(graph, item.nextState)\n );\n for (const change of [...operations, ...ambiguousChanges.map(asDrop)]) {\n if (\n \"tableName\" in change &&\n // An adopted table is released with no DDL: its rows stay.\n !item.parent.adopts?.includes(change.tableName) &&\n isDestructiveOperation(change) &&\n (await holdsRows(producer, command, change.tableName))\n ) {\n losses.push(change);\n }\n }\n }\n // The callback is the caller's work: no locked transaction waits on it.\n // Each group of `down` re-reads the marker under the lock it takes again.\n if (losses.length > 0 && resolve) await letLockGo(producer);\n await approveDestructiveOperations(losses, resolve, false);\n}\n\nfunction asDrop(change: AmbiguousChange): DiffOperation {\n return change.type === \"ambiguousTable\"\n ? { type: \"dropTable\", tableName: change.droppedTable }\n : {\n type: \"dropColumn\",\n tableName: change.tableName,\n columnName: change.droppedColumn.name,\n };\n}\n\n/**\n * The absent-and-empty-table probe: an absent table (a later state dropped it,\n * or a resumed rollback already did) holds no rows.\n */\nasync function holdsRows(\n producer: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n table: string\n): Promise<boolean> {\n if (await isTableMissing(producer, command, table)) return false;\n const result = await producer._executeRaw(\n `SELECT 1 AS populated FROM ${qualifiedName(command, table)} LIMIT 1`\n );\n return result.rows.length > 0;\n}\n\n/**\n * A rolled-back attempt must have left nothing behind. A manual opaque step of\n * it that committed, or was announced and never answered (it may have\n * committed), is an effect no fingerprint shows and that no rollback undid: a\n * forward attempt runs none. Marking it rolled back would let `apply` run the\n * step again — the double credit (plan S4). A step the server refused whole is\n * answered with its `failure`: nothing of it committed. Each announcement is\n * answered on its own (`countUnanswered`, as resume counts them): a resumed\n * retry of a refused step whose reply was lost may have committed. Generated\n * steps are structural, and so is a CONCURRENTLY index statement, whose index\n * resolve repairs before the origin proof (plan S7): the fingerprint proves\n * those undone.\n */\nfunction refuseOpaqueEffect(\n transition: ReturnType<typeof parentTransition>,\n blob: Uint8Array,\n attempt: LedgerEventV1,\n ledger: readonly LedgerEventV1[]\n): void {\n const opaque = new Set(\n transition.operations.flatMap((operation) =>\n operation.steps.flatMap((step) =>\n operation.origin === \"manual\" &&\n step.retry === \"opaque\" &&\n concurrentIndexNames(sliceDispatch(blob, step.execute)).length === 0\n ? [step.execute.dispatchId]\n : []\n )\n )\n );\n const effects = ledger.filter(\n (event) =>\n event.attemptId === attempt.attemptId &&\n event.kind === \"step-confirmed\" &&\n opaque.has(event.dispatchId ?? \"\")\n );\n const unanswered = new Map<LedgerEventV1[\"dispatchId\"], number>();\n for (const event of effects) {\n countUnanswered(unanswered, event.dispatchId, event);\n }\n const effect =\n effects.find((event) => event.effectState === \"committed\") ??\n effects.find((event) => (unanswered.get(event.dispatchId) ?? 0) > 0);\n if (effect === undefined) return;\n const committed = effect.effectState === \"committed\";\n throw new MigrationError(\n `resolve rolled-back refused: opaque ${effect.dispatchId} ${committed ? \"committed\" : \"may have committed\"}.`,\n committed\n ? VibORMErrorCode.MIGRATION_PARTIAL_EFFECT\n : VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT,\n {\n meta: {\n ...(attempt.fromState ? { fromState: attempt.fromState } : {}),\n ...(attempt.toState ? { toState: attempt.toState } : {}),\n operationId: effect.operationId ?? undefined,\n dispatchId: effect.dispatchId ?? undefined,\n lastConfirmedStep: effect.dispatchId ?? undefined,\n effectState: committed ? \"committed\" : \"may-have-committed\",\n partial: true,\n },\n }\n );\n}\n\nfunction rollbackSlice(\n graph: MigrationGraph,\n marker: MigrationMarkerV1,\n options: NormalizedDownOptions\n): MigrationMarkerV1[\"path\"] {\n if (marker.path.length === 0) {\n throw notFound(\"Nothing to roll back\");\n }\n const steps = options.to\n ? distanceTo(\n marker.path.map((edge) => edge.stateId),\n resolveStateSelector(graph, options.to)\n )\n : options.steps;\n const removed = steps === 0 ? [] : marker.path.slice(-steps);\n if (removed.some((edge) => edge.baselineBoundary)) {\n throw invalidState(\"down cannot cross a baseline boundary\");\n }\n return removed;\n}\n\nfunction distanceTo(path: readonly Sha256[], target: Sha256): number {\n const index = path.lastIndexOf(target);\n if (index < 0) {\n throw notFound(\"down target is not on the arrival path\");\n }\n return path.length - 1 - index;\n}\n","/** One capability-sensitive migration client composition root. */\n\nimport { CLIENT_DIAGNOSTICS } from \"../drivers/execution-context\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport { type ApplyV1Result, applyV1 } from \"./apply-v1\";\nimport { type CheckResult, checkEstate } from \"./check\";\nimport { annotateMigrationFailure } from \"./execute-dispatch\";\nimport { type GenerateV1Result, generateV1 } from \"./generate-v1\";\nimport { loadMigrationGraph, resolveStateSelector } from \"./graph\";\nimport { snapshotExactRecord } from \"./input-boundary\";\nimport { type MigrationLimits, resolveMigrationLimits } from \"./limits\";\nimport {\n baselineV1,\n downV1,\n logV1,\n type PruneOptions,\n type PruneResult,\n pruneV1,\n reanchorV1,\n resetV1,\n resolveV1,\n type StatusV1Result,\n statusV1,\n type VerifyV1Result,\n verifyV1,\n} from \"./operators\";\nimport {\n type GraphResult,\n type ListResult,\n listMigrationStates,\n migrationGraphResult,\n type ShowResult,\n showMigrationState,\n} from \"./public-view\";\nimport type { MigrationClient } from \"./push/planner\";\nimport { type PushResultFor, pushV1 } from \"./push-v1\";\nimport type {\n MigrationStorageReader,\n MigrationStorageWriter,\n} from \"./storage/contract\";\nimport {\n isMigrationStorageReader,\n isMigrationStorageWriter,\n} from \"./storage/contract\";\nimport {\n MANAGED_TABLES,\n MIGRATION_LIMITS,\n normalizeManagedTables,\n} from \"./target\";\nimport type {\n ApplyV1Options,\n BaselineOptions,\n DownV1Options,\n DownV1Result,\n ExactPushOptions,\n GenerateV1Options,\n LedgerEventV1,\n PushOptionsV1,\n ReanchorOptions,\n ResetV1Options,\n ResolveV1Options,\n StateSelector,\n} from \"./v1-types\";\n\nexport interface MigrationClientOptions<\n S extends MigrationStorageReader = MigrationStorageReader,\n> {\n readonly storage: S;\n readonly tables?: readonly string[];\n /**\n * PostgreSQL session limits and VibORM's own waits, in milliseconds, and\n * `largeTableRows`, the estimated table size above which a rewrite or scan\n * is refused in-request.\n */\n readonly limits?: MigrationLimits;\n}\n\n/** A storage-less client's options: managed tables, limits, or both. */\ntype LiveMigrationClientOptions =\n | {\n readonly tables: readonly string[];\n readonly limits?: MigrationLimits;\n }\n | {\n readonly tables?: readonly string[];\n readonly limits: MigrationLimits;\n };\n\ntype NoExtraMigrationClientOptionKeys<Given> = Record<\n Exclude<keyof Given, \"storage\" | \"tables\" | \"limits\">,\n never\n>;\n\nexport type GenerateResult = GenerateV1Result;\nexport type StatusResult = StatusV1Result;\nexport type VerifyResult = VerifyV1Result;\nexport type LogResult = readonly LedgerEventV1[];\nexport type ApplyResult = ApplyV1Result;\nexport type DownResult = DownV1Result;\nexport interface BaselineResult {\n readonly stateId: string;\n}\nexport interface ReanchorResult {\n readonly stateId: string;\n}\nexport interface ResolveResult {\n readonly outcome: ResolveV1Options[\"outcome\"];\n}\nexport interface ResetResult {\n /** Physical tables selected for a read-only reset preview. */\n readonly tables?: readonly string[];\n readonly preview: boolean;\n readonly path: readonly string[];\n}\nexport interface LiveMigrations {\n log(): Promise<LogResult>;\n push<O extends PushOptionsV1>(\n options?: ExactPushOptions<O>\n ): Promise<PushResultFor<O>>;\n}\n\nexport interface ReadableMigrations extends LiveMigrations {\n check(): Promise<CheckResult>;\n list(): Promise<ListResult>;\n show(selector: StateSelector): Promise<ShowResult>;\n graph(): Promise<GraphResult>;\n status(): Promise<StatusResult>;\n verify(): Promise<VerifyResult>;\n apply(options?: ApplyV1Options): Promise<ApplyResult>;\n down(options?: DownV1Options): Promise<DownResult>;\n baseline(options: BaselineOptions): Promise<BaselineResult>;\n reanchor(options?: ReanchorOptions): Promise<ReanchorResult>;\n prune(options: PruneOptions): Promise<PruneResult>;\n resolve(options: ResolveV1Options): Promise<ResolveResult>;\n}\n\nexport interface WritableMigrations extends ReadableMigrations {\n generate(options?: GenerateV1Options): Promise<GenerateResult>;\n reset(options?: ResetV1Options): Promise<ResetResult>;\n}\n\nexport function createMigrationClient<\n Options extends MigrationClientOptions<MigrationStorageWriter>,\n>(\n client: MigrationClient,\n options: Options & NoExtraMigrationClientOptionKeys<Options>\n): WritableMigrations;\nexport function createMigrationClient<\n Options extends MigrationClientOptions<MigrationStorageReader>,\n>(\n client: MigrationClient,\n options: Options & NoExtraMigrationClientOptionKeys<Options>\n): ReadableMigrations;\nexport function createMigrationClient<\n Options extends LiveMigrationClientOptions,\n>(\n client: MigrationClient,\n options: Options & NoExtraMigrationClientOptionKeys<Options>\n): LiveMigrations;\nexport function createMigrationClient(\n client: MigrationClient,\n options?: undefined\n): LiveMigrations;\nexport function createMigrationClient(\n client: MigrationClient,\n options?: MigrationClientOptions | LiveMigrationClientOptions\n): LiveMigrations | ReadableMigrations | WritableMigrations {\n // VibORM only reads Snowflake: no estate, no control table, no DDL. Every\n // command is refused here, before it reads storage or sends a statement.\n if (client.$driver.dialect === \"snowflake\")\n throw new MigrationError(\n // Short: this text ships in every migrations bundle. The Snowflake page\n // says why.\n \"Snowflake has no migrations: VibORM only reads it (introspectSchema() reads its schema).\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { dialect: \"snowflake\" } }\n );\n const record =\n options === undefined\n ? undefined\n : snapshotExactRecord(\n options,\n [\"storage\", \"tables\", \"limits\"],\n \"migration client options\",\n refuseClientOptions\n );\n const tables = normalizeManagedTables(record?.tables);\n const limits =\n record?.limits === undefined\n ? undefined\n : resolveMigrationLimits(record.limits);\n const executionClient: MigrationClient =\n tables === undefined && limits === undefined\n ? client\n : {\n $driver: client.$driver,\n $schema: client.$schema,\n [MANAGED_TABLES]: tables,\n [MIGRATION_LIMITS]: limits,\n [CLIENT_DIAGNOSTICS]: client[CLIENT_DIAGNOSTICS],\n };\n const live: LiveMigrations = Object.freeze({\n log: () => logV1(executionClient),\n push<O extends PushOptionsV1>(\n pushOptions?: ExactPushOptions<O>\n ): Promise<PushResultFor<O>> {\n return pushV1(executionClient, pushOptions);\n },\n });\n if (record === undefined) return live;\n const storage = record.storage;\n if (storage === undefined) {\n if (tables !== undefined || limits !== undefined) return live;\n return refuseClientOptions(\n \"migration client options must include storage, tables or limits when supplied\"\n );\n }\n let readableStorage: MigrationStorageReader;\n try {\n if (!isMigrationStorageReader(storage)) {\n return refuseClientOptions(\n \"migration client storage must implement MigrationStorageReader\"\n );\n }\n readableStorage = storage;\n } catch (failure) {\n return refuseClientOptions(\n \"migration client storage could not be inspected\",\n errorCause(failure)\n );\n }\n\n const readable: ReadableMigrations = Object.freeze({\n ...live,\n check: () => checkEstate(readableStorage),\n list: async () =>\n listMigrationStates(await loadMigrationGraph(readableStorage)),\n show: async (selector) => {\n const graph = await loadMigrationGraph(readableStorage);\n return showMigrationState(graph, resolveStateSelector(graph, selector));\n },\n graph: async () =>\n migrationGraphResult(await loadMigrationGraph(readableStorage)),\n status: () => statusV1(executionClient, readableStorage),\n verify: () => verifyV1(executionClient, readableStorage),\n apply: (applyOptions) =>\n named(\"apply\", applyV1(executionClient, readableStorage, applyOptions)),\n down: (downOptions) =>\n named(\"down\", downV1(executionClient, readableStorage, downOptions)),\n baseline: (baselineOptions) =>\n named(\n \"baseline\",\n baselineV1(executionClient, readableStorage, baselineOptions)\n ),\n reanchor: (reanchorOptions) =>\n named(\n \"reanchor\",\n reanchorV1(executionClient, readableStorage, reanchorOptions)\n ),\n prune: (pruneOptions) => pruneV1(readableStorage, pruneOptions),\n resolve: (resolveOptions) =>\n named(\n \"resolve\",\n resolveV1(executionClient, readableStorage, resolveOptions)\n ),\n });\n let writableStorage: MigrationStorageWriter;\n try {\n if (!isMigrationStorageWriter(readableStorage)) return readable;\n writableStorage = readableStorage;\n } catch (failure) {\n return refuseClientOptions(\n \"migration client storage could not be inspected\",\n errorCause(failure)\n );\n }\n\n return Object.freeze({\n ...readable,\n generate: (generateOptions) =>\n generateV1(executionClient, writableStorage, generateOptions),\n reset: (resetOptions) =>\n named(\"reset\", resetV1(executionClient, writableStorage, resetOptions)),\n });\n}\n\n/**\n * The command's result, its failure naming the step it failed in when no\n * statement or boundary inside it did: a lock wait, a marker write.\n */\nfunction named<T>(step: string, running: Promise<T>): Promise<T> {\n return running.catch((failure: unknown) => {\n throw annotateMigrationFailure(failure, { step });\n });\n}\n\nfunction refuseClientOptions(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n"],"mappings":"gtDAoBA,eAAsB,GACpB,EACsB,CACtB,IAAM,EAA2B,EAAE,CACnC,GAAI,CACF,IAAM,EAAQ,MAAM,EAAmB,EAAQ,CAC3C,EAAM,OAAO,OAAS,GACxB,EAAS,KAAK,CACZ,KAAM,oBACN,QAAS,cAAc,EAAM,OAAO,OAAO,mDAC5C,CAAC,CAEJ,IAAM,EAAsB,IAAI,IAAY,CAC1C,EAAM,kBACN,GAAG,EAAM,kBAAkB,MAAM,CAClC,CAAC,CACI,EAAgB,IAAI,IAC1B,IAAK,IAAM,KAAS,EAAM,OAAO,QAAQ,CACvC,EAAc,IAAI,EAAM,QAAQ,CAElC,IAAM,EAAY,MAAM,EAAQ,eAAe,CAC/C,MAAM,GACJ,EACA,EACA,IAAI,IAAI,EAAM,kBAAkB,CACjC,CACD,IAAK,IAAM,KAAQ,EACZ,EAAoB,IAAI,EAAK,EAChC,EAAS,KAAK,CACZ,KAAM,kBACN,QAAS,YAAY,EAAK,iCAC3B,CAAC,CAGN,IAAK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