viborm 1.16.1 → 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.
- package/dist/adapter-internals-Dz2nNEF5.mjs +2 -0
- package/dist/adapter-internals-Dz2nNEF5.mjs.map +1 -0
- package/dist/adapter-namespace-C1SUkH2U.mjs +2 -0
- package/dist/{adapter-namespace-DwFnfpED.mjs.map → adapter-namespace-C1SUkH2U.mjs.map} +1 -1
- package/dist/adapters.d.mts +50 -94
- package/dist/adapters.mjs +1 -1
- package/dist/{args-7WgBFd_f.mjs → args-DsGRkPRw.mjs} +2 -2
- package/dist/{args-7WgBFd_f.mjs.map → args-DsGRkPRw.mjs.map} +1 -1
- package/dist/{array-literal-BOzj0E2u.mjs → array-literal-U6SeastY.mjs} +1 -1
- package/dist/{array-literal-BOzj0E2u.mjs.map → array-literal-U6SeastY.mjs.map} +1 -1
- package/dist/auto-names-GpcDfhaw.mjs +2 -0
- package/dist/auto-names-GpcDfhaw.mjs.map +1 -0
- package/dist/batch-refs-BuICt2tu.mjs +2 -0
- package/dist/{batch-refs-Bd8HvwUc.mjs.map → batch-refs-BuICt2tu.mjs.map} +1 -1
- package/dist/better-auth.d.mts +1 -1
- package/dist/better-auth.mjs +2 -2
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache.d.mts +2 -2
- package/dist/cache.mjs +1 -1
- package/dist/call-D2E7dPCd.mjs +2 -0
- package/dist/{call-0bd_B9Vp.mjs.map → call-D2E7dPCd.mjs.map} +1 -1
- package/dist/cli.mjs +6 -6
- package/dist/cli.mjs.map +1 -1
- package/dist/client-Cq_VcF43.d.mts +183 -0
- package/dist/client-DkNRAOuH.mjs +2 -0
- package/dist/client-DkNRAOuH.mjs.map +1 -0
- package/dist/{planner-CYu6_q4w.d.mts → client-driver-DuQy6lsN.d.mts} +3 -3
- package/dist/client-rIiFOn1W.mjs +9 -0
- package/dist/client-rIiFOn1W.mjs.map +1 -0
- package/dist/client.d.mts +2 -2
- package/dist/client.mjs +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/{confine-CyI9IwjC.mjs → confine-FIfjlAHp.mjs} +2 -2
- package/dist/{confine-CyI9IwjC.mjs.map → confine-FIfjlAHp.mjs.map} +1 -1
- package/dist/{object-store-BBDTj8x3.d.mts → conformance-C1JveA8y.d.mts} +5 -60
- package/dist/conformance-C4JYA0JG.mjs +2 -0
- package/dist/conformance-C4JYA0JG.mjs.map +1 -0
- package/dist/contract-BBone8RD.mjs +2 -0
- package/dist/contract-BBone8RD.mjs.map +1 -0
- package/dist/coordination-BxMskOgi.mjs +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/{database-adapter-01J6mYq5.d.mts → database-adapter-cW0nmWM6.d.mts} +2 -2
- package/dist/datetime-physical-codec-Ci0dyOot.mjs +2 -0
- package/dist/datetime-physical-codec-Ci0dyOot.mjs.map +1 -0
- package/dist/datetime-values-D_G6m5_o.mjs +2 -0
- package/dist/datetime-values-D_G6m5_o.mjs.map +1 -0
- package/dist/decimal-D4DRlT2y.mjs +2 -0
- package/dist/decimal-D4DRlT2y.mjs.map +1 -0
- package/dist/{defaults-DAPb-tJ4.mjs → defaults-BrXUK350.mjs} +2 -2
- package/dist/{defaults-DAPb-tJ4.mjs.map → defaults-BrXUK350.mjs.map} +1 -1
- package/dist/{document-DRPqjDv_.d.mts → document-B8ClXlb7.d.mts} +1 -1
- package/dist/{driver-kiIQS_Fd.mjs → driver-BOsmU3kz.mjs} +2 -2
- package/dist/{driver-kiIQS_Fd.mjs.map → driver-BOsmU3kz.mjs.map} +1 -1
- package/dist/{driver-CTjq1yxj.d.mts → driver-KgGMnfz8.d.mts} +1 -1
- package/dist/{driver-lShUkDmf.mjs → driver-PkP_1p80.mjs} +2 -2
- package/dist/{driver-lShUkDmf.mjs.map → driver-PkP_1p80.mjs.map} +1 -1
- package/dist/{driver-diagnostics-aQ54bArn.mjs → driver-diagnostics-sSpge6kv.mjs} +1 -1
- package/dist/{driver-diagnostics-aQ54bArn.mjs.map → driver-diagnostics-sSpge6kv.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/durable-object.d.mts +1 -1
- package/dist/durable-object.mjs +2 -2
- package/dist/error-mapping-B9rSvgG9.mjs +1 -1
- package/dist/every-tAZuZ50K.mjs +2 -0
- package/dist/{every-CgeIFxWR.mjs.map → every-tAZuZ50K.mjs.map} +1 -1
- package/dist/execution-context-couU2tgh.mjs +1 -1
- package/dist/{exports-nC8lsVKO.d.mts → exports-reE3GioL.d.mts} +1 -1
- package/dist/extension-Bf4vO5mp.mjs +2 -0
- package/dist/extension-Bf4vO5mp.mjs.map +1 -0
- package/dist/facts-Bjnzv3j-.mjs +2 -0
- package/dist/facts-Bjnzv3j-.mjs.map +1 -0
- package/dist/{fs-estate-n-QpsFqb.mjs → fs-estate-C3ahNKmi.mjs} +2 -2
- package/dist/{fs-estate-n-QpsFqb.mjs.map → fs-estate-C3ahNKmi.mjs.map} +1 -1
- package/dist/geo-area-codec-CBdiCOzj.mjs +2 -0
- package/dist/{geo-area-codec-Bti2PA2i.mjs.map → geo-area-codec-CBdiCOzj.mjs.map} +1 -1
- package/dist/geo-point-DCV0eO1p.mjs +2 -0
- package/dist/geo-point-DCV0eO1p.mjs.map +1 -0
- package/dist/id-domain-Cj6MnMxg.mjs +2 -0
- package/dist/{id-domain-Cg65TLZ-.mjs.map → id-domain-Cj6MnMxg.mjs.map} +1 -1
- package/dist/identifier-BdLx66pi.mjs +2 -0
- package/dist/identifier-BdLx66pi.mjs.map +1 -0
- package/dist/identifier-conversion-CMKVatU4.mjs +3 -0
- package/dist/identifier-conversion-CMKVatU4.mjs.map +1 -0
- package/dist/{identifiers-BxOf57qy.mjs → identifiers-BAZ_S6Lk.mjs} +1 -1
- package/dist/{identifiers-BxOf57qy.mjs.map → identifiers-BAZ_S6Lk.mjs.map} +1 -1
- package/dist/{identity-CJlRQA-m.mjs → identity-nPArhpsD.mjs} +2 -2
- package/dist/{identity-CJlRQA-m.mjs.map → identity-nPArhpsD.mjs.map} +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/introspect-dyBpdr2L.mjs +2 -0
- package/dist/{introspect-rGqr93B3.mjs.map → introspect-dyBpdr2L.mjs.map} +1 -1
- package/dist/json-DvvrTWUw.mjs +2 -0
- package/dist/{json-CsAdz9pg.mjs.map → json-DvvrTWUw.mjs.map} +1 -1
- package/dist/{json-number-C09rsm1g.mjs → json-number-Guh-5rff.mjs} +1 -1
- package/dist/{json-number-C09rsm1g.mjs.map → json-number-Guh-5rff.mjs.map} +1 -1
- package/dist/{json-parameter-D7hDrVKw.mjs → json-parameter-DtHhEfyE.mjs} +1 -1
- package/dist/{json-parameter-D7hDrVKw.mjs.map → json-parameter-DtHhEfyE.mjs.map} +1 -1
- package/dist/judge-words-CqNdnbou.mjs +2 -0
- package/dist/judge-words-CqNdnbou.mjs.map +1 -0
- package/dist/{key-BDH6oTyC.mjs → key-v4k7Cqb6.mjs} +2 -2
- package/dist/{key-BDH6oTyC.mjs.map → key-v4k7Cqb6.mjs.map} +1 -1
- package/dist/{keys-CIal55WQ.mjs → keys-BLWaO_YM.mjs} +1 -1
- package/dist/{keys-CIal55WQ.mjs.map → keys-BLWaO_YM.mjs.map} +1 -1
- package/dist/keys-o4Pl6Vsg.mjs +2 -0
- package/dist/{keys-DZdKAd4n.mjs.map → keys-o4Pl6Vsg.mjs.map} +1 -1
- package/dist/libsql-C0iMZifz.mjs +3 -0
- package/dist/libsql-C0iMZifz.mjs.map +1 -0
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/light-reLULeHN.mjs +2 -0
- package/dist/{light-D2wNSbzY.mjs.map → light-reLULeHN.mjs.map} +1 -1
- package/dist/memory-DtTuFo-h.mjs +2 -0
- package/dist/memory-DtTuFo-h.mjs.map +1 -0
- package/dist/methods-part-Dsi0DBNU.mjs +2 -0
- package/dist/{methods-part-BaNx3o7b.mjs.map → methods-part-Dsi0DBNU.mjs.map} +1 -1
- package/dist/migrations/mysql/runtime.d.mts +7 -0
- package/dist/migrations/mysql/runtime.mjs +2 -0
- package/dist/migrations/mysql/runtime.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +7 -5
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/mysql.mjs.map +1 -1
- package/dist/migrations/postgres/runtime.d.mts +7 -0
- package/dist/migrations/postgres/runtime.mjs +2 -0
- package/dist/migrations/postgres/runtime.mjs.map +1 -0
- package/dist/migrations/postgres.d.mts +7 -5
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/postgres.mjs.map +1 -1
- package/dist/migrations/snowflake.d.mts +7 -5
- package/dist/migrations/snowflake.mjs +1 -1
- package/dist/migrations/snowflake.mjs.map +1 -1
- package/dist/migrations/sqlite/runtime.d.mts +7 -0
- package/dist/migrations/sqlite/runtime.mjs +2 -0
- package/dist/migrations/sqlite/runtime.mjs.map +1 -0
- package/dist/migrations/sqlite.d.mts +7 -5
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/sqlite.mjs.map +1 -1
- package/dist/migrations/storage/durable-object.d.mts +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/fs.d.mts +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/surrealdb.d.mts +7 -5
- package/dist/migrations/surrealdb.mjs +1 -1
- package/dist/migrations/surrealdb.mjs.map +1 -1
- package/dist/migrations/tenant.d.mts +4 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations/tenant.mjs.map +1 -1
- package/dist/migrations.d.mts +7 -5
- package/dist/migrations.mjs +1 -1
- package/dist/migrations.mjs.map +1 -1
- package/dist/model-ByktcCGW.mjs +2 -0
- package/dist/model-ByktcCGW.mjs.map +1 -0
- package/dist/mysql-DPYi1p_g.mjs +4 -0
- package/dist/mysql-DPYi1p_g.mjs.map +1 -0
- package/dist/mysql-adapter-6gVm5PHp.mjs +2 -0
- package/dist/{mysql-adapter-BFWYPoM0.mjs.map → mysql-adapter-6gVm5PHp.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/{named-statements-CkOOD__I.mjs → named-statements-CswIc5m1.mjs} +2 -2
- package/dist/{named-statements-CkOOD__I.mjs.map → named-statements-CswIc5m1.mjs.map} +1 -1
- package/dist/native-types-BUkcVedc.mjs +2 -0
- package/dist/native-types-BUkcVedc.mjs.map +1 -0
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/normalized-result-D7nVkF36.mjs +1 -1
- package/dist/{object-store-Chq1PMYz.mjs → object-store-DnrLNxz_.mjs} +2 -2
- package/dist/{object-store-Chq1PMYz.mjs.map → object-store-DnrLNxz_.mjs.map} +1 -1
- package/dist/object-store-j4kgh61D.d.mts +59 -0
- package/dist/{on-ZkOVmE4-.mjs → on-nOenqmgP.mjs} +2 -2
- package/dist/{on-ZkOVmE4-.mjs.map → on-nOenqmgP.mjs.map} +1 -1
- package/dist/on.d.mts +1 -1
- package/dist/on.mjs +1 -1
- package/dist/ordering/keys.mjs +1 -1
- package/dist/ordering.d.mts +1 -1
- package/dist/ordering.mjs +2 -2
- package/dist/pending-operation-B5o-zhES.mjs +2 -0
- package/dist/{pending-operation-D4gUKMxD.mjs.map → pending-operation-B5o-zhES.mjs.map} +1 -1
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/pg.d.mts +2 -2
- package/dist/pg.mjs +1 -1
- package/dist/pglite.d.mts +1 -1
- package/dist/pglite.mjs +1 -1
- package/dist/{physical-DO4PEYcc.mjs → physical-BheMRPY0.mjs} +2 -2
- package/dist/{physical-DO4PEYcc.mjs.map → physical-BheMRPY0.mjs.map} +1 -1
- package/dist/{pinned-session-Y7-2pRBJ.mjs → pinned-session-eNyd0dkT.mjs} +2 -2
- package/dist/{pinned-session-Y7-2pRBJ.mjs.map → pinned-session-eNyd0dkT.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/postgres-CEGFOi8D.mjs +27 -0
- package/dist/postgres-CEGFOi8D.mjs.map +1 -0
- package/dist/postgres-adapter-B-im38AE.mjs +2 -0
- package/dist/postgres-adapter-B-im38AE.mjs.map +1 -0
- package/dist/{postgres-adapter-BpLizOaK.mjs → postgres-adapter-OoqoBdhb.mjs} +2 -2
- package/dist/{postgres-adapter-BpLizOaK.mjs.map → postgres-adapter-OoqoBdhb.mjs.map} +1 -1
- package/dist/{postgres-result-133boRW-.mjs → postgres-result-D-bqmofR.mjs} +1 -1
- package/dist/{postgres-result-133boRW-.mjs.map → postgres-result-D-bqmofR.mjs.map} +1 -1
- package/dist/postgres.d.mts +2 -2
- package/dist/postgres.mjs +1 -1
- package/dist/provider-limits-DvcCUw7l.mjs +2 -0
- package/dist/{provider-limits-SdI1SaJS.mjs.map → provider-limits-DvcCUw7l.mjs.map} +1 -1
- package/dist/{provider-parameter-snapshot-cyTUDutH.mjs → provider-parameter-snapshot-DnJ6Av9y.mjs} +2 -2
- package/dist/{provider-parameter-snapshot-cyTUDutH.mjs.map → provider-parameter-snapshot-DnJ6Av9y.mjs.map} +1 -1
- package/dist/push-fingerprint-CegYVFFp.mjs +18 -0
- package/dist/push-fingerprint-CegYVFFp.mjs.map +1 -0
- package/dist/{quantized-BKBs0joq.mjs → quantized-DLD2cd6q.mjs} +1 -1
- package/dist/{quantized-BKBs0joq.mjs.map → quantized-DLD2cd6q.mjs.map} +1 -1
- package/dist/query-DSEMPA7r.mjs +2 -0
- package/dist/query-DSEMPA7r.mjs.map +1 -0
- package/dist/query-backend-CzwVfrQ6.mjs +2 -0
- package/dist/{query-backend-TisPjCPF.mjs.map → query-backend-CzwVfrQ6.mjs.map} +1 -1
- package/dist/{query-inspection-DwYBKSDG.mjs → query-inspection-CvtTL5Fs.mjs} +2 -2
- package/dist/{query-inspection-DwYBKSDG.mjs.map → query-inspection-CvtTL5Fs.mjs.map} +1 -1
- package/dist/raw-B8cNef_V.mjs +2 -0
- package/dist/{raw-DqEb71JZ.mjs.map → raw-B8cNef_V.mjs.map} +1 -1
- package/dist/{relation-bound-CSNKLyDy.mjs → relation-bound-DHP5cpTE.mjs} +1 -1
- package/dist/{relation-bound-CSNKLyDy.mjs.map → relation-bound-DHP5cpTE.mjs.map} +1 -1
- package/dist/{result-parsing-BbffueEX.mjs → result-parsing-DfwBAXY2.mjs} +1 -1
- package/dist/{result-parsing-BbffueEX.mjs.map → result-parsing-DfwBAXY2.mjs.map} +1 -1
- package/dist/{rows-of-Bgl9GVtK.mjs → rows-of-UeSasWGq.mjs} +2 -2
- package/dist/{rows-of-Bgl9GVtK.mjs.map → rows-of-UeSasWGq.mjs.map} +1 -1
- package/dist/rule-words-ojG0-vSf.mjs +2 -0
- package/dist/{rule-words-DMbQuvD2.mjs.map → rule-words-ojG0-vSf.mjs.map} +1 -1
- package/dist/runtime-BAqlANG_.mjs +10 -0
- package/dist/runtime-BAqlANG_.mjs.map +1 -0
- package/dist/runtime-D0oaIS1E.mjs +2 -0
- package/dist/runtime-D0oaIS1E.mjs.map +1 -0
- package/dist/runtime-Dfkv59_p.mjs +15 -0
- package/dist/runtime-Dfkv59_p.mjs.map +1 -0
- package/dist/runtime-client-CvGGOOFd.d.mts +38 -0
- package/dist/runtime-client-xeiXA_1m.mjs +2 -0
- package/dist/runtime-client-xeiXA_1m.mjs.map +1 -0
- package/dist/scalar-BTYxpiP_.mjs +4 -0
- package/dist/scalar-BTYxpiP_.mjs.map +1 -0
- package/dist/schema/introspect.d.mts +2 -2
- package/dist/schema/introspect.mjs +1 -1
- package/dist/schema/json.d.mts +2 -2
- package/dist/schema/json.mjs +1 -1
- package/dist/schema-BzkBJTF-.mjs +2 -0
- package/dist/{schema-DDkAUfOb.mjs.map → schema-BzkBJTF-.mjs.map} +1 -1
- package/dist/schema-D7MyYTjA.mjs +2 -0
- package/dist/{schema-DqR_Kcje.mjs.map → schema-D7MyYTjA.mjs.map} +1 -1
- package/dist/{schema-introspection-Bbo4DN_d.mjs → schema-introspection-b4xPGPfu.mjs} +4 -4
- package/dist/{schema-introspection-Bbo4DN_d.mjs.map → schema-introspection-b4xPGPfu.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-CEpNu-Gw.mjs → select-assembly-B01JtBRm.mjs} +2 -2
- package/dist/{select-assembly-CEpNu-Gw.mjs.map → select-assembly-B01JtBRm.mjs.map} +1 -1
- package/dist/serializer-CIhcZMxs.mjs +7 -0
- package/dist/serializer-CIhcZMxs.mjs.map +1 -0
- package/dist/{settle-Pui-1tfJ.mjs → settle-CIbvnLED.mjs} +1 -1
- package/dist/{settle-Pui-1tfJ.mjs.map → settle-CIbvnLED.mjs.map} +1 -1
- package/dist/{settled-DYYPcaBX.mjs → settled-Clanz_kI.mjs} +2 -2
- package/dist/{settled-DYYPcaBX.mjs.map → settled-Clanz_kI.mjs.map} +1 -1
- package/dist/snowflake-C1dqbche.mjs +2 -0
- package/dist/{snowflake-B8Ei88bg.mjs.map → snowflake-C1dqbche.mjs.map} +1 -1
- package/dist/snowflake.d.mts +2 -2
- package/dist/snowflake.mjs +2 -2
- package/dist/snowflake.mjs.map +1 -1
- package/dist/soft-delete.d.mts +1 -1
- package/dist/soft-delete.mjs +1 -1
- package/dist/{spans-DwDXMvyd.mjs → spans-CVl3RKUR.mjs} +1 -1
- package/dist/{spans-DwDXMvyd.mjs.map → spans-CVl3RKUR.mjs.map} +1 -1
- package/dist/sql-AHN2niBz.mjs +2 -0
- package/dist/{sql-M5WsPhqr.mjs.map → sql-AHN2niBz.mjs.map} +1 -1
- package/dist/sql-control-Cdp0_Mwy.mjs +2 -0
- package/dist/sql-control-Cdp0_Mwy.mjs.map +1 -0
- package/dist/{sql-statement-tokens-Z5Ta4iDB.mjs → sql-statement-tokens-BdVJnUQY.mjs} +2 -2
- package/dist/{sql-statement-tokens-Z5Ta4iDB.mjs.map → sql-statement-tokens-BdVJnUQY.mjs.map} +1 -1
- package/dist/sql-tegqTqGq.mjs +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sqlite-adapter-B7r7w3CS.mjs +2 -0
- package/dist/sqlite-adapter-B7r7w3CS.mjs.map +1 -0
- package/dist/{sqlite-statement-classifier-JBHiQO6Q.mjs → sqlite-statement-classifier-CBmKy8Ta.mjs} +2 -2
- package/dist/{sqlite-statement-classifier-JBHiQO6Q.mjs.map → sqlite-statement-classifier-CBmKy8Ta.mjs.map} +1 -1
- package/dist/sqlite-storage-audit-D8nA9ylL.mjs +2 -0
- package/dist/sqlite-storage-audit-D8nA9ylL.mjs.map +1 -0
- package/dist/{sqlite-utils-Bfmtkt1b.mjs → sqlite-utils-BAUMCrok.mjs} +2 -2
- package/dist/{sqlite-utils-Bfmtkt1b.mjs.map → sqlite-utils-BAUMCrok.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/{standard-sql-Bl2OHGfi.mjs → standard-sql-tpcKlArE.mjs} +2 -2
- package/dist/{standard-sql-Bl2OHGfi.mjs.map → standard-sql-tpcKlArE.mjs.map} +1 -1
- package/dist/surrealdb.d.mts +2 -2
- package/dist/surrealdb.mjs +1 -1
- package/dist/surrealdb.mjs.map +1 -1
- package/dist/surrealql-AyDLKSEQ.mjs +2 -0
- package/dist/surrealql-AyDLKSEQ.mjs.map +1 -0
- package/dist/time-step-BIdl2Iy7.mjs +2 -0
- package/dist/time-step-BIdl2Iy7.mjs.map +1 -0
- package/dist/transaction-operation-CaWzo7gE.mjs +1 -1
- package/dist/type-mapping-BYre7JQ1.mjs +3 -0
- package/dist/type-mapping-BYre7JQ1.mjs.map +1 -0
- package/dist/{types-Dy33vBdd.mjs → types-M-IdB4Mo.mjs} +1 -1
- package/dist/{types-Dy33vBdd.mjs.map → types-M-IdB4Mo.mjs.map} +1 -1
- package/dist/{unit-DUPX5Sdd.mjs → unit-Dnp2HIWg.mjs} +2 -2
- package/dist/{unit-DUPX5Sdd.mjs.map → unit-Dnp2HIWg.mjs.map} +1 -1
- package/dist/{unit-words-BXpLpyr2.mjs → unit-words-DjVhRXAQ.mjs} +2 -2
- package/dist/{unit-words-BXpLpyr2.mjs.map → unit-words-DjVhRXAQ.mjs.map} +1 -1
- package/dist/{utils-BHkJsduV.mjs → utils-BB_4NZQC.mjs} +2 -2
- package/dist/{utils-BHkJsduV.mjs.map → utils-BB_4NZQC.mjs.map} +1 -1
- package/dist/utils-DYrxwV_M.mjs +2 -0
- package/dist/utils-DYrxwV_M.mjs.map +1 -0
- package/dist/{v1-parse-shared-cJ-uD14P.mjs → v1-parse-shared-CNiFHAJF.mjs} +1 -1
- package/dist/{v1-parse-shared-cJ-uD14P.mjs.map → v1-parse-shared-CNiFHAJF.mjs.map} +1 -1
- package/dist/validation-CEnhYqhl.mjs +2 -0
- package/dist/{validation-BHjx13zG.mjs.map → validation-CEnhYqhl.mjs.map} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-CISkL46K.mjs +2 -0
- package/dist/validator-CISkL46K.mjs.map +1 -0
- package/dist/{values-Ch2cTlss.mjs → values-D0k60ei0.mjs} +2 -2
- package/dist/{values-Ch2cTlss.mjs.map → values-D0k60ei0.mjs.map} +1 -1
- package/dist/{client-Bb2oZOzg.d.mts → verify-v1-CJFrJ4lx.d.mts} +10 -183
- package/dist/version-nEOMCWfV.mjs +2 -0
- package/dist/{version-Bu2LCuaj.mjs.map → version-nEOMCWfV.mjs.map} +1 -1
- package/dist/view-CmLQ0I6x.mjs +2 -0
- package/dist/{view-CHgjF2BO.mjs.map → view-CmLQ0I6x.mjs.map} +1 -1
- package/dist/write-sinks-BhwgQn_5.mjs +2 -0
- package/dist/{write-sinks-Bei5vFHP.mjs.map → write-sinks-BhwgQn_5.mjs.map} +1 -1
- package/package.json +27 -2
- package/dist/adapter-namespace-DwFnfpED.mjs +0 -2
- package/dist/batch-refs-Bd8HvwUc.mjs +0 -2
- package/dist/call-0bd_B9Vp.mjs +0 -2
- package/dist/client-BvAmGuYW.mjs +0 -9
- package/dist/client-BvAmGuYW.mjs.map +0 -1
- package/dist/client-Q4zkYZbn.mjs +0 -2
- package/dist/client-Q4zkYZbn.mjs.map +0 -1
- package/dist/datetime-physical-codec-DAF7WJpy.mjs +0 -2
- package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +0 -1
- package/dist/every-CgeIFxWR.mjs +0 -2
- package/dist/extension-Dh1ddrlA.mjs +0 -2
- package/dist/extension-Dh1ddrlA.mjs.map +0 -1
- package/dist/geo-area-codec-Bti2PA2i.mjs +0 -2
- package/dist/id-domain-Cg65TLZ-.mjs +0 -2
- package/dist/identifier-conversion-BTDxDwDB.mjs +0 -2
- package/dist/identifier-conversion-BTDxDwDB.mjs.map +0 -1
- package/dist/introspect-rGqr93B3.mjs +0 -2
- package/dist/json-CsAdz9pg.mjs +0 -2
- package/dist/judge-words-k5GCc4cV.mjs +0 -2
- package/dist/judge-words-k5GCc4cV.mjs.map +0 -1
- package/dist/keys-DZdKAd4n.mjs +0 -2
- package/dist/libsql-BZAXy5PY.mjs +0 -3
- package/dist/libsql-BZAXy5PY.mjs.map +0 -1
- package/dist/light-D2wNSbzY.mjs +0 -2
- package/dist/memory-DgBGBQdJ.mjs +0 -2
- package/dist/memory-DgBGBQdJ.mjs.map +0 -1
- package/dist/methods-part-BaNx3o7b.mjs +0 -2
- package/dist/model-Dtd37Sky.mjs +0 -2
- package/dist/model-Dtd37Sky.mjs.map +0 -1
- package/dist/mysql-BjIAoFH6.mjs +0 -9
- package/dist/mysql-BjIAoFH6.mjs.map +0 -1
- package/dist/mysql-adapter-BFWYPoM0.mjs +0 -2
- package/dist/native-types-1ewJXVks.mjs +0 -2
- package/dist/native-types-1ewJXVks.mjs.map +0 -1
- package/dist/pending-operation-D4gUKMxD.mjs +0 -2
- package/dist/postgres-CaMB2Y4p.mjs +0 -35
- package/dist/postgres-CaMB2Y4p.mjs.map +0 -1
- package/dist/postgres-adapter-psTVfuw7.mjs +0 -2
- package/dist/postgres-adapter-psTVfuw7.mjs.map +0 -1
- package/dist/provider-limits-SdI1SaJS.mjs +0 -2
- package/dist/query-BTb6iakn.mjs +0 -2
- package/dist/query-BTb6iakn.mjs.map +0 -1
- package/dist/query-backend-TisPjCPF.mjs +0 -2
- package/dist/raw-DqEb71JZ.mjs +0 -2
- package/dist/rule-words-DMbQuvD2.mjs +0 -2
- package/dist/scalar-Dm9brvAU.mjs +0 -4
- package/dist/scalar-Dm9brvAU.mjs.map +0 -1
- package/dist/schema-DDkAUfOb.mjs +0 -2
- package/dist/schema-DqR_Kcje.mjs +0 -2
- package/dist/serializer-Br9JgpQI.mjs +0 -33
- package/dist/serializer-Br9JgpQI.mjs.map +0 -1
- package/dist/snowflake-B8Ei88bg.mjs +0 -2
- package/dist/sql-M5WsPhqr.mjs +0 -2
- package/dist/sqlite-adapter-Cb-SJw2f.mjs +0 -2
- package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +0 -1
- package/dist/surrealql-f2Rgu47F.mjs +0 -2
- package/dist/surrealql-f2Rgu47F.mjs.map +0 -1
- package/dist/time-step-DJaIhpAz.mjs +0 -2
- package/dist/time-step-DJaIhpAz.mjs.map +0 -1
- package/dist/validation-BHjx13zG.mjs +0 -2
- package/dist/validator-DMzH5Tz0.mjs +0 -2
- package/dist/validator-DMzH5Tz0.mjs.map +0 -1
- package/dist/version-Bu2LCuaj.mjs +0 -2
- package/dist/view-CHgjF2BO.mjs +0 -2
- package/dist/write-sinks-Bei5vFHP.mjs +0 -2
- /package/dist/{contract-CxJn0_cV.d.mts → contract-CAoFgKSO.d.mts} +0 -0
- /package/dist/{named-statements-NF7Iycjk.d.mts → named-statements-CT4Gbd6t.d.mts} +0 -0
- /package/dist/{sql-C4_sFNDm.d.mts → sql-C-SBCGCx.d.mts} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"contract-BBone8RD.mjs","names":["location","artifacts"],"sources":["../src/migrations/empty-snapshot.ts","../src/migrations/snapshot-artifacts.ts","../src/migrations/graph.ts","../src/migrations/proof.ts","../src/migrations/admission.ts","../src/migrations/client-driver.ts","../src/migrations/resume.ts","../src/migrations/apply-v1.ts","../src/migrations/log-v1.ts","../src/migrations/status-v1.ts","../src/migrations/verify-v1.ts","../src/migrations/storage/contract.ts"],"sourcesContent":["/**\n * The one virtual-root snapshot. Not a stored second root.\n */\n\nimport type { SchemaSnapshot } from \"./types\";\n\nexport function emptyManagedSnapshot(): SchemaSnapshot {\n return { tables: [], enums: [] };\n}\n","/**\n * Stored snapshot representation. Logical identity remains the canonical full\n * schema hash; deltas have their own exact-byte address. No DDL meaning lives\n * here. Every consumer receives the existing strictly admitted full schema.\n */\nimport { isRecord } from \"../validation/value-guards\";\nimport {\n assertCanonicalBytes,\n canonicalizeJson,\n canonicalizeJsonText,\n parseJsonBytes,\n} from \"./canonical-json\";\nimport { domainHash, HASH_DOMAIN, parseSha256, type Sha256 } from \"./identity\";\nimport type { MigrationStorageReader } from \"./storage/contract\";\nimport type { SchemaSnapshot } from \"./types\";\nimport { corrupt, exactKeys, ks, refuse } from \"./v1-parse-shared\";\nimport { encodeSnapshot, parseSnapshotDocument } from \"./v1-parse-snapshot\";\nimport type {\n SnapshotChangeV1,\n SnapshotDeltaFormat,\n SnapshotDeltaV1,\n} from \"./v1-types\";\n\nexport const MAX_SNAPSHOT_DELTA_DEPTH = 32;\n\nconst DELTA_KEYS = ks(\"format baseArtifactHash snapshotHash changes\");\nconst REMOVE_KEYS = ks(\"op path\");\nconst SET_KEYS = ks(\"op path value\");\n\nexport interface ResolvedSnapshotArtifact {\n readonly snapshot: SchemaSnapshot;\n readonly snapshotHash: Sha256;\n readonly depth: number;\n readonly baseArtifactHash?: Sha256;\n /** Detached exact bytes admitted for this command, used by history copying. */\n readonly bytes: Uint8Array;\n}\n\nexport interface EncodedSnapshotArtifact {\n readonly artifactHash: Sha256;\n readonly snapshotHash: Sha256;\n /** Null means an authenticated or candidate-owned object can be reused. */\n readonly bytes: Uint8Array | null;\n readonly depth: number;\n readonly baseArtifactHash?: Sha256;\n}\n\nexport type ParsedSnapshotArtifact =\n | { readonly kind: \"full\"; readonly snapshot: SchemaSnapshot }\n | {\n readonly kind: \"delta\";\n readonly delta: SnapshotDeltaV1;\n readonly snapshot?: SchemaSnapshot;\n };\n\nexport interface SnapshotArtifactCache {\n storedSnapshot(bytes: Uint8Array, hash: Sha256): ParsedSnapshotArtifact;\n rememberSnapshot(\n hash: Sha256,\n bytes: Uint8Array,\n snapshot: SchemaSnapshot\n ): void;\n}\n\nexport function parseSnapshotArtifact(\n bytes: Uint8Array,\n hash: Sha256\n): ParsedSnapshotArtifact {\n const value = parseJsonBytes(bytes, `snapshots/${hash}.json`);\n return isRecord(value) && \"format\" in value\n ? { kind: \"delta\", delta: parseDelta(bytes, value, hash) }\n : { kind: \"full\", snapshot: parseSnapshotDocument(bytes, hash) };\n}\n\nfunction parseChange(\n value: unknown,\n format: SnapshotDeltaFormat\n): SnapshotChangeV1 {\n const inserts = format === \"snapshot-delta-2\";\n if (\n !isRecord(value) ||\n (value.op !== \"set\" &&\n value.op !== \"remove\" &&\n !(inserts && value.op === \"insert\"))\n )\n refuse(\"snapshot delta op invalid\");\n const record = exactKeys(\n value,\n value.op === \"remove\" ? REMOVE_KEYS : SET_KEYS,\n \"snapshot delta change\"\n );\n if (!Array.isArray(record.path) || record.path.length === 0)\n refuse(\"snapshot delta path empty\");\n const path = record.path.map((segment) => {\n if (\n typeof segment === \"string\" ||\n (typeof segment === \"number\" &&\n Number.isSafeInteger(segment) &&\n segment >= 0)\n )\n return segment;\n return refuse(\"snapshot delta path segment invalid\");\n });\n return value.op === \"remove\"\n ? { op: \"remove\", path }\n : { op: value.op, path, value: record.value };\n}\n\nfunction parseDelta(\n bytes: Uint8Array,\n value: unknown,\n hash: Sha256\n): SnapshotDeltaV1 {\n const record = exactKeys(value, DELTA_KEYS, \"snapshot delta\");\n const format = record.format;\n if (\n (format !== \"snapshot-delta-1\" && format !== \"snapshot-delta-2\") ||\n !Array.isArray(record.changes)\n )\n refuse(`Unsupported snapshot delta format ${String(format)}`);\n const delta: SnapshotDeltaV1 = {\n format,\n baseArtifactHash: parseSha256(\n record.baseArtifactHash,\n \"snapshot delta baseArtifactHash\"\n ),\n snapshotHash: parseSha256(\n record.snapshotHash,\n \"snapshot delta snapshotHash\"\n ),\n changes: record.changes.map((change) => parseChange(change, format)),\n };\n assertCanonicalBytes(bytes, delta, \"snapshot delta\");\n if (domainHash(HASH_DOMAIN.snapshotDelta, bytes) !== hash)\n corrupt(`Snapshot delta ${hash} hash mismatch`);\n return delta;\n}\n\ntype PathLocation =\n | {\n readonly kind: \"array\";\n readonly container: unknown[];\n readonly key: number;\n }\n | {\n readonly kind: \"object\";\n readonly container: Record<string, unknown>;\n readonly key: string;\n };\n\n/** A segment's spelling is interpreted only by its actual container. */\nfunction pathLocation(\n container: unknown,\n segment: string | number,\n append: boolean\n): PathLocation {\n if (Array.isArray(container)) {\n if (\n typeof segment !== \"number\" ||\n segment > container.length ||\n (!append && segment === container.length)\n )\n refuse(\"snapshot delta array index out of bounds\");\n return { kind: \"array\", container, key: segment };\n }\n if (!isRecord(container) || typeof segment !== \"string\")\n refuse(\"snapshot delta object key invalid\");\n return { kind: \"object\", container, key: segment };\n}\n\nfunction applyChange(\n document: unknown,\n change: SnapshotChangeV1,\n format: SnapshotDeltaFormat\n): void {\n let container = document;\n for (const segment of change.path.slice(0, -1)) {\n const location = pathLocation(container, segment, false);\n const descriptor = Object.getOwnPropertyDescriptor(\n location.container,\n location.key\n );\n if (!descriptor) refuse(\"snapshot delta missing intermediate\");\n container = descriptor.value;\n }\n const location = pathLocation(\n container,\n change.path.at(-1)!,\n change.op !== \"remove\"\n );\n if (change.op === \"insert\") {\n if (location.kind !== \"array\")\n refuse(\"snapshot delta insert requires array\");\n location.container.splice(location.key, 0, change.value);\n return;\n }\n if (change.op === \"set\") {\n Object.defineProperty(location.container, location.key, {\n value: change.value,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n return;\n }\n if (!Object.hasOwn(location.container, location.key))\n refuse(\"snapshot delta missing property\");\n if (location.kind === \"array\") {\n const { container: array, key: index } = location;\n if (format === \"snapshot-delta-1\" && index !== array.length - 1)\n refuse(\"snapshot delta v1 remove must be tail\");\n array.splice(index, 1);\n } else {\n Reflect.deleteProperty(location.container, location.key);\n }\n}\n\n/** Mutations stay on an independently owned JSON document, including on failure. */\nfunction reconstruct(\n base: SchemaSnapshot,\n delta: SnapshotDeltaV1\n): SchemaSnapshot {\n const document = parseJsonBytes(\n encodeSnapshot(base).bytes,\n \"snapshot delta base\"\n );\n // Cached deltas are frozen and shared; set values belong to this document.\n for (const change of structuredClone(delta.changes))\n applyChange(document, change, delta.format);\n return parseSnapshotDocument(canonicalizeJson(document), delta.snapshotHash);\n}\n\n/**\n * Resolve by physical identity, not logical schema. Absolute depth survives\n * memoization; both a cold chain and a child of a cached chain obey one limit.\n * The same map may be extended to validate orphans, after retaining the separate\n * committed-state dependency closure.\n */\nexport async function resolveSnapshotArtifacts(\n storage: MigrationStorageReader,\n roots: Iterable<Sha256>,\n resolved = new Map<Sha256, ResolvedSnapshotArtifact>(),\n cache?: SnapshotArtifactCache\n): Promise<Map<Sha256, ResolvedSnapshotArtifact>> {\n for (const root of roots) {\n const pending: {\n hash: Sha256;\n delta: SnapshotDeltaV1;\n bytes: Uint8Array;\n snapshot?: SchemaSnapshot;\n }[] = [];\n let hash = root;\n while (!resolved.has(hash)) {\n const bytes = await storage.readSnapshot(hash);\n if (!bytes) corrupt(`Snapshot ${hash} is referenced but missing`);\n const artifact =\n cache?.storedSnapshot(bytes, hash) ??\n parseSnapshotArtifact(bytes, hash);\n if (artifact.kind === \"delta\") {\n const delta = artifact.delta;\n pending.push({\n hash,\n delta,\n bytes: bytes.slice(),\n snapshot: artifact.snapshot,\n });\n if (pending.length > MAX_SNAPSHOT_DELTA_DEPTH)\n refuse(\"snapshot delta chain exceeds 32 links\");\n hash = delta.baseArtifactHash;\n } else {\n resolved.set(hash, {\n snapshot: artifact.snapshot,\n snapshotHash: hash,\n depth: 0,\n bytes: bytes.slice(),\n });\n }\n }\n for (let index = pending.length - 1; index >= 0; index--) {\n const entry = pending[index]!;\n const base = resolved.get(entry.delta.baseArtifactHash)!;\n const depth = base.depth + 1;\n if (depth > MAX_SNAPSHOT_DELTA_DEPTH)\n refuse(\"snapshot delta chain exceeds 32 links\");\n // A cached result is eligible only after every base has been re-read and\n // authenticated, and the absolute dependency depth has been checked.\n const snapshot =\n entry.snapshot ?? reconstruct(base.snapshot, entry.delta);\n cache?.rememberSnapshot(entry.hash, entry.bytes, snapshot);\n resolved.set(entry.hash, {\n snapshot,\n snapshotHash: entry.delta.snapshotHash,\n depth,\n baseArtifactHash: entry.delta.baseArtifactHash,\n bytes: entry.bytes,\n });\n }\n }\n return resolved;\n}\n\n/**\n * An array's element identities when every element has a distinct one: a\n * record's `name` (tables, columns, indexes, constraints, enums) or the string\n * itself (enum values, column lists). Otherwise the array diffs by position.\n */\nfunction elementKeys(array: readonly unknown[]): string[] | undefined {\n const keys = new Set<string>();\n for (const element of array) {\n let key: string | undefined;\n if (typeof element === \"string\") key = `s:${element}`;\n else if (isRecord(element) && typeof element.name === \"string\")\n key = `n:${element.name}`;\n if (key === undefined || keys.has(key)) return undefined;\n keys.add(key);\n }\n return [...keys];\n}\n\n/**\n * The before-indexes of the most shared keys that keep their relative order:\n * with distinct keys, the longest common subsequence is the longest increasing\n * run of after-positions, found in O(n log n) by patience sorting.\n */\nfunction keptInOrder(\n before: readonly string[],\n after: readonly string[]\n): Set<number> {\n const position = new Map(after.map((key, index) => [key, index]));\n // tails[length - 1] is the before-index ending the lowest run of that length.\n const tails: number[] = [];\n const previous = new Map<number, number>();\n for (const [index, key] of before.entries()) {\n const target = position.get(key);\n if (target === undefined) continue;\n let low = 0;\n let high = tails.length;\n while (low < high) {\n const middle = Math.floor((low + high) / 2);\n if (position.get(before[tails[middle]!]!)! < target) low = middle + 1;\n else high = middle;\n }\n if (low > 0) previous.set(index, tails[low - 1]!);\n tails[low] = index;\n }\n const kept = new Set<number>();\n for (\n let index = tails.at(-1);\n index !== undefined;\n index = previous.get(index)\n )\n kept.add(index);\n return kept;\n}\n\n/**\n * Keyed edits leave one element's insertion at one change however many follow\n * it: drop the elements that are not kept, last first, then insert the new and\n * moved ones at their final indexes in order, then edit the kept pairs there.\n */\nfunction keyedChangesBetween(\n before: readonly unknown[],\n after: readonly unknown[],\n beforeKeys: readonly string[],\n afterKeys: readonly string[],\n path: readonly (string | number)[],\n changes: SnapshotChangeV1[]\n): void {\n const kept = keptInOrder(beforeKeys, afterKeys);\n const keptAt = new Map([...kept].map((index) => [beforeKeys[index]!, index]));\n for (let index = before.length - 1; index >= 0; index--) {\n if (!kept.has(index))\n changes.push({ op: \"remove\", path: [...path, index] });\n }\n for (const [index, key] of afterKeys.entries()) {\n if (!keptAt.has(key))\n changes.push({\n op: \"insert\",\n path: [...path, index],\n value: after[index],\n });\n }\n for (const [index, key] of afterKeys.entries()) {\n const from = keptAt.get(key);\n if (from !== undefined)\n changesBetween(\n before[from],\n after[index],\n [...path, index],\n changes,\n true\n );\n }\n}\n\nfunction changesBetween(\n before: unknown,\n after: unknown,\n path: readonly (string | number)[],\n changes: SnapshotChangeV1[],\n keyed: boolean\n): void {\n if (canonicalizeJsonText(before) === canonicalizeJsonText(after)) return;\n if (Array.isArray(before) && Array.isArray(after)) {\n const beforeKeys = keyed ? elementKeys(before) : undefined;\n const afterKeys = beforeKeys && elementKeys(after);\n if (beforeKeys && afterKeys) {\n keyedChangesBetween(before, after, beforeKeys, afterKeys, path, changes);\n return;\n }\n const shared = Math.min(before.length, after.length);\n for (let index = 0; index < shared; index++)\n changesBetween(\n before[index],\n after[index],\n [...path, index],\n changes,\n keyed\n );\n for (let index = before.length - 1; index >= after.length; index--)\n changes.push({ op: \"remove\", path: [...path, index] });\n for (let index = shared; index < after.length; index++)\n changes.push({ op: \"set\", path: [...path, index], value: after[index] });\n } else if (isRecord(before) && isRecord(after)) {\n for (const key of Object.keys(before).sort()) {\n if (!Object.hasOwn(after, key))\n changes.push({ op: \"remove\", path: [...path, key] });\n }\n for (const key of Object.keys(after).sort()) {\n if (Object.hasOwn(before, key))\n changesBetween(before[key], after[key], [...path, key], changes, keyed);\n else changes.push({ op: \"set\", path: [...path, key], value: after[key] });\n }\n } else {\n changes.push({ op: \"set\", path, value: after });\n }\n}\n\n/**\n * A function of the parents' artifacts alone, independent of storage listing\n * order: a state's id hashes its artifact, so the same parents and schema give\n * the same id whatever else the history holds.\n */\nexport function encodeSnapshotArtifact(\n snapshot: SchemaSnapshot,\n artifacts: ReadonlyMap<Sha256, ResolvedSnapshotArtifact>,\n parentArtifacts: Iterable<Sha256>\n): EncodedSnapshotArtifact {\n const full = encodeSnapshot(snapshot);\n const bases = [...new Set(parentArtifacts)].sort();\n for (const hash of bases) {\n const base = artifacts.get(hash)!;\n // A parent already stores this schema; publication can omit this object.\n if (base.snapshotHash === full.snapshotHash) {\n return {\n artifactHash: hash,\n snapshotHash: full.snapshotHash,\n bytes: null,\n depth: base.depth,\n };\n }\n }\n let best: EncodedSnapshotArtifact & { readonly bytes: Uint8Array } = {\n artifactHash: full.snapshotHash,\n ...full,\n depth: 0,\n };\n const desired = parseJsonBytes(full.bytes, \"desired snapshot\");\n for (const baseArtifactHash of bases) {\n const base = artifacts.get(baseArtifactHash)!;\n if (base.depth >= MAX_SNAPSHOT_DELTA_DEPTH) continue;\n const document = parseJsonBytes(\n encodeSnapshot(base.snapshot).bytes,\n \"snapshot base\"\n );\n // Keyed edits win on insertions; positional ones still win on an element\n // renamed in place, which a keyed diff spells as a removal and an insert.\n for (const keyed of [true, false]) {\n const changes: SnapshotChangeV1[] = [];\n // Both encoded snapshots are records, so every emitted edit is below the\n // root; the producer cannot emit the empty path that admission refuses.\n changesBetween(document, desired, [], changes, keyed);\n const delta: SnapshotDeltaV1 = {\n format: \"snapshot-delta-2\",\n baseArtifactHash,\n snapshotHash: full.snapshotHash,\n changes,\n };\n const bytes = canonicalizeJson(delta);\n if (bytes.length < best.bytes.length) {\n best = {\n artifactHash: domainHash(HASH_DOMAIN.snapshotDelta, bytes),\n snapshotHash: full.snapshotHash,\n bytes,\n depth: base.depth + 1,\n baseArtifactHash,\n };\n }\n }\n }\n return best;\n}\n","/**\n * One immutable estate graph. Commands consume this instance; they do not\n * rescan storage or invent apply order from names.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { bytesEqual } from \"./canonical-json\";\nimport { emptyManagedSnapshot } from \"./empty-snapshot\";\nimport type { Sha256 } from \"./identity\";\nimport { freezeDeep } from \"./push-fingerprint\";\nimport {\n type ParsedSnapshotArtifact,\n parseSnapshotArtifact,\n type ResolvedSnapshotArtifact,\n resolveSnapshotArtifacts,\n} from \"./snapshot-artifacts\";\nimport { sliceDispatch, validateSqlRanges } from \"./sql-blob\";\nimport { assertArtifactExecutionSafe } from \"./statement-safety\";\nimport type { MigrationStorageReader } from \"./storage/contract\";\nimport type { MigrationTarget, SchemaSnapshot } from \"./types\";\nimport {\n encodeSnapshot,\n encodeSqlBlob,\n parseEstateDescriptor,\n parseStateManifest,\n} from \"./v1-parse\";\nimport { corrupt } from \"./v1-parse-shared\";\nimport type {\n MigrationBooleanCheckV1,\n MigrationDispatchV1,\n MigrationEstateDescriptorV1,\n MigrationOperationV1,\n MigrationParentTransitionV1,\n MigrationStateManifestV1,\n PathWitness,\n SnapshotDeltaV1,\n StateSelector,\n} from \"./v1-types\";\n\nexport interface MigrationGraph {\n readonly estateHash: Sha256;\n readonly descriptor: MigrationEstateDescriptorV1;\n readonly states: ReadonlyMap<Sha256, MigrationStateManifestV1>;\n readonly snapshots: ReadonlyMap<Sha256, SchemaSnapshot>;\n readonly snapshotArtifacts: ReadonlyMap<Sha256, ResolvedSnapshotArtifact>;\n readonly sql: ReadonlyMap<Sha256, Uint8Array>;\n readonly roots: readonly Sha256[];\n readonly leaves: readonly Sha256[];\n readonly emptySnapshotHash: Sha256;\n}\n\nconst invalidEstate = (message: string) =>\n new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_ESTATE);\nconst notFound = (message: string) =>\n new MigrationError(message, VibORMErrorCode.MIGRATION_NOT_FOUND);\nconst pathError = (message: string) =>\n new MigrationError(message, VibORMErrorCode.MIGRATION_PATH_REQUIRED);\n\nexport function requireStateSnapshot(\n graph: MigrationGraph,\n stateId: Sha256 | null\n): SchemaSnapshot {\n const snapshotHash =\n stateId === null\n ? graph.emptySnapshotHash\n : graph.states.get(stateId)?.snapshotHash;\n const snapshot = snapshotHash ? graph.snapshots.get(snapshotHash) : undefined;\n if (!snapshot) corrupt(\"State missing snapshot\");\n return snapshot;\n}\n\ntype CachedArtifact =\n | { readonly bytes: Uint8Array; readonly snapshot: SchemaSnapshot }\n | {\n readonly bytes: Uint8Array;\n readonly delta: SnapshotDeltaV1;\n readonly snapshot?: SchemaSnapshot;\n readonly decodedBytes?: number;\n }\n | { readonly bytes: Uint8Array; readonly manifest: MigrationStateManifestV1 };\n\n/**\n * Parsed artifacts, keyed by their own content hash: never by the estate\n * hash, which every estate with the same target shares. Only the parse is\n * skipped. Every command still lists and reads the tenant's storage, and an\n * entry answers only bytes identical to the ones it was parsed from, so\n * changed bytes are parsed, and refused, as if nothing were cached. Values\n * are deep-frozen because commands and tenants share them. Least recently\n * used entries are dropped once the held bytes exceed `maxBytes`. A retained\n * delta reconstruction charges its full canonical size as well as delta bytes.\n */\nexport class ArtifactCache {\n private readonly e = new Map<Sha256, CachedArtifact>();\n private readonly m: number;\n private h = 0;\n\n constructor(maxBytes: number) {\n this.m = maxBytes;\n }\n\n get heldBytes(): number {\n return this.h;\n }\n\n storedSnapshot(bytes: Uint8Array, hash: Sha256): ParsedSnapshotArtifact {\n const hit = cacheHit(this.e, hash, bytes);\n if (hit && \"delta\" in hit)\n return { kind: \"delta\", delta: hit.delta, snapshot: hit.snapshot };\n if (hit && \"snapshot\" in hit)\n return { kind: \"full\", snapshot: hit.snapshot };\n const artifact = freezeDeep(parseSnapshotArtifact(bytes, hash));\n this.h = cacheKeep(\n this.e,\n this.m,\n this.h,\n hash,\n artifact.kind === \"full\"\n ? { bytes: bytes.slice(), snapshot: artifact.snapshot }\n : { bytes: bytes.slice(), delta: artifact.delta }\n );\n return artifact;\n }\n\n rememberSnapshot(\n hash: Sha256,\n bytes: Uint8Array,\n snapshot: SchemaSnapshot\n ): void {\n const entry = cacheHit(this.e, hash, bytes);\n if (!(entry && \"delta\" in entry) || entry.snapshot) return;\n this.e.delete(hash);\n this.h -= entry.bytes.length;\n this.h = cacheKeep(this.e, this.m, this.h, hash, {\n ...entry,\n snapshot: freezeDeep(snapshot),\n decodedBytes: encodeSnapshot(snapshot).bytes.length,\n });\n }\n\n manifest(id: Sha256, bytes: Uint8Array): MigrationStateManifestV1 {\n const hit = cacheHit(this.e, id, bytes);\n if (hit && \"manifest\" in hit) return hit.manifest;\n const manifest = freezeDeep(parseStateManifest(bytes, id));\n this.h = cacheKeep(this.e, this.m, this.h, id, {\n bytes: bytes.slice(),\n manifest,\n });\n return manifest;\n }\n}\n\nfunction cacheHit(\n entries: Map<Sha256, CachedArtifact>,\n hash: Sha256,\n bytes: Uint8Array\n): CachedArtifact | undefined {\n const entry = entries.get(hash);\n if (!(entry && bytesEqual(entry.bytes, bytes))) return undefined;\n entries.delete(hash);\n entries.set(hash, entry);\n return entry;\n}\n\nconst entrySize = (entry: CachedArtifact) =>\n entry.bytes.length +\n (\"decodedBytes\" in entry ? (entry.decodedBytes ?? 0) : 0);\n\nfunction cacheKeep(\n entries: Map<Sha256, CachedArtifact>,\n maxBytes: number,\n held: number,\n hash: Sha256,\n entry: CachedArtifact\n): number {\n entries.set(hash, entry);\n let total = held + entrySize(entry);\n for (const [key, oldest] of entries) {\n if (total <= maxBytes) break;\n entries.delete(key);\n total -= entrySize(oldest);\n }\n return total;\n}\n\n/**\n * One per isolate. 8 MiB of artifact bytes hold a 200-state estate of twenty\n * 15-column tables; the parsed values add about as much again.\n */\nconst artifacts = new ArtifactCache(8 * 1024 * 1024);\n\nexport async function loadMigrationGraph(\n storage: MigrationStorageReader,\n cache: ArtifactCache = artifacts\n): Promise<MigrationGraph> {\n const estateBytes = await storage.readEstate();\n if (!estateBytes) throw invalidEstate(\"Estate descriptor missing\");\n const { descriptor, estateHash } = parseEstateDescriptor(estateBytes);\n const emptySnapshotHash = encodeSnapshot(emptyManagedSnapshot()).snapshotHash;\n const stateIds = await storage.listStates();\n const states = new Map<Sha256, MigrationStateManifestV1>();\n const neededSnapshots = new Set<Sha256>();\n const neededSql = new Set<Sha256>();\n\n for (const id of stateIds) {\n const bytes = await storage.readState(id);\n if (!bytes) corrupt(`State ${id} unreadable`);\n if (states.has(id)) corrupt(`State ${id} duplicated`);\n const manifest = cache.manifest(id, bytes);\n if (manifest.estateHash !== estateHash)\n throw invalidEstate(`State ${id} wrong estate`);\n states.set(id, manifest);\n if (\n manifest.snapshotArtifactHash !== undefined ||\n manifest.snapshotHash !== emptySnapshotHash\n )\n neededSnapshots.add(\n manifest.snapshotArtifactHash ?? manifest.snapshotHash\n );\n neededSql.add(manifest.sqlHash);\n }\n\n const snapshots = new Map<Sha256, SchemaSnapshot>();\n snapshots.set(emptySnapshotHash, emptyManagedSnapshot());\n const snapshotArtifacts = await resolveSnapshotArtifacts(\n storage,\n neededSnapshots,\n new Map(),\n cache\n );\n for (const artifact of snapshotArtifacts.values()) {\n if (!Object.isFrozen(artifact.snapshot)) freezeDeep(artifact.snapshot);\n }\n for (const manifest of states.values()) {\n if (\n manifest.snapshotArtifactHash === undefined &&\n manifest.snapshotHash === emptySnapshotHash\n )\n continue;\n const artifact = snapshotArtifacts.get(\n manifest.snapshotArtifactHash ?? manifest.snapshotHash\n )!;\n if (artifact.snapshotHash !== manifest.snapshotHash)\n corrupt(`State ${manifest.stateId} snapshot mismatch`);\n snapshots.set(manifest.snapshotHash, artifact.snapshot);\n }\n\n const sql = new Map<Sha256, Uint8Array>();\n for (const hash of neededSql) {\n const bytes = await storage.readSql(hash);\n if (!bytes) corrupt(`SQL blob ${hash} missing`);\n if (encodeSqlBlob(bytes) !== hash)\n corrupt(`SQL blob ${hash} hash mismatch`);\n sql.set(hash, bytes);\n }\n\n for (const manifest of states.values()) {\n const blob = sql.get(manifest.sqlHash)!;\n const dispatches: MigrationDispatchV1[] = [];\n for (const parent of manifest.parents) {\n collectDispatches(parent, dispatches);\n }\n collectChecks(manifest.destinationChecks, dispatches);\n validateSqlRanges(blob, dispatches);\n assertStoredParameterDialect(\n dispatches,\n descriptor.target.dialect,\n manifest.name\n );\n assertArtifactExecutionSafe(\n dispatches.map((dispatch) => sliceDispatch(blob, dispatch)),\n descriptor.target.dialect,\n manifest.name\n );\n }\n\n const outgoing = new Map<Sha256, Sha256[]>();\n for (const id of states.keys()) {\n outgoing.set(id, []);\n }\n\n for (const [id, manifest] of states) {\n for (const parent of manifest.parents) {\n assertAdoption(id, parent, descriptor.target, (stateId) => {\n const hash =\n stateId === null\n ? emptySnapshotHash\n : states.get(stateId)?.snapshotHash;\n return hash === undefined ? undefined : snapshots.get(hash);\n });\n if (parent.fromState === null) continue;\n if (!states.has(parent.fromState)) {\n throw invalidEstate(`State ${id} has dangling parent`);\n }\n outgoing.get(parent.fromState)!.push(id);\n }\n }\n\n const roots = [...states.keys()].filter((id) =>\n states.get(id)!.parents.some((parent) => parent.fromState === null)\n );\n const leaves = [...states.keys()].filter(\n (id) => (outgoing.get(id) ?? []).length === 0\n );\n assertNoCycle(states, outgoing);\n\n if (states.size > 0 && roots.length === 0) {\n throw invalidEstate(\"Estate has states but no virtual-root transition\");\n }\n assertReachableFromEmpty(states, outgoing, roots);\n\n return {\n estateHash,\n descriptor,\n states,\n snapshots,\n snapshotArtifacts,\n sql,\n roots,\n leaves,\n emptySnapshotHash,\n };\n}\n\n/**\n * An adoption names only tables of its state that its parent lacks, outside\n * the estate's frozen list: the proofs leave an adopted table out on the\n * parent's side (`managedAt`), which is sound only for such a table.\n */\nfunction assertAdoption(\n stateId: Sha256,\n parent: MigrationParentTransitionV1,\n target: MigrationTarget,\n snapshotOf: (stateId: Sha256 | null) => SchemaSnapshot | undefined\n): void {\n if (parent.adopts === undefined) return;\n const has = (snapshot: SchemaSnapshot | undefined, name: string) =>\n snapshot?.tables.some((table) => table.name === name) === true;\n const own = snapshotOf(stateId);\n const before = snapshotOf(parent.fromState);\n for (const name of parent.adopts) {\n if (\n target.tables === undefined ||\n target.tables.includes(name) ||\n !has(own, name) ||\n has(before, name)\n )\n throw invalidEstate(`State ${stateId} invalid adoption \"${name}\"`);\n }\n}\n\nfunction assertStoredParameterDialect(\n dispatches: readonly MigrationDispatchV1[],\n dialect: MigrationEstateDescriptorV1[\"target\"][\"dialect\"],\n artifact: string\n): void {\n if (dialect === \"mysql\") return;\n for (const dispatch of dispatches) {\n if (\n dispatch.parameters.some(\n (parameter) => parameter.kind === \"target-namespace\"\n )\n )\n throw new MigrationError(\n `Migration \"${artifact}\" has target-namespace parameter outside MySQL`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { migrationName: artifact } }\n );\n }\n}\n\nfunction collectDispatches(\n parent: MigrationParentTransitionV1,\n into: MigrationDispatchV1[]\n): void {\n collectChecks(parent.originChecks, into);\n collectOperations(parent.operations, into);\n if (parent.rollback.kind !== \"irreversible\") {\n collectOperations(parent.rollback.operations, into);\n }\n}\n\nfunction collectOperations(\n operations: readonly MigrationOperationV1[],\n into: MigrationDispatchV1[]\n): void {\n for (const operation of operations) {\n for (const step of operation.steps) {\n if (step.retry === \"proven\") {\n into.push(step.precheck.query);\n }\n into.push(step.execute);\n if (step.retry === \"proven\") {\n into.push(step.postcheck.query);\n }\n }\n }\n}\n\nfunction collectChecks(\n checks: readonly MigrationBooleanCheckV1[],\n into: MigrationDispatchV1[]\n): void {\n for (const check of checks) {\n into.push(check.query);\n }\n}\n\nfunction assertNoCycle(\n states: ReadonlyMap<Sha256, MigrationStateManifestV1>,\n outgoing: ReadonlyMap<Sha256, readonly Sha256[]>\n): void {\n const color = new Map<Sha256, 0 | 1 | 2>();\n for (const id of states.keys()) color.set(id, 0);\n for (const start of states.keys()) {\n if (color.get(start) !== 0) continue;\n const stack: Array<{ id: Sha256; next: number }> = [{ id: start, next: 0 }];\n color.set(start, 1);\n while (stack.length > 0) {\n const frame = stack.at(-1)!;\n const edges = outgoing.get(frame.id) ?? [];\n if (frame.next < edges.length) {\n const next = edges[frame.next++]!;\n const seen = color.get(next) ?? 0;\n if (seen === 1) {\n throw invalidEstate(\"Estate graph contains a cycle\");\n }\n if (seen === 0) {\n color.set(next, 1);\n stack.push({ id: next, next: 0 });\n }\n continue;\n }\n color.set(frame.id, 2);\n stack.pop();\n }\n }\n}\n\nfunction assertReachableFromEmpty(\n states: ReadonlyMap<Sha256, MigrationStateManifestV1>,\n outgoing: ReadonlyMap<Sha256, readonly Sha256[]>,\n roots: readonly Sha256[]\n): void {\n const reachable = new Set<Sha256>();\n const pending = [...roots];\n while (pending.length > 0) {\n const id = pending.pop()!;\n if (reachable.has(id)) continue;\n reachable.add(id);\n for (const child of outgoing.get(id) ?? []) {\n pending.push(child);\n }\n }\n for (const id of states.keys()) {\n if (!reachable.has(id)) {\n throw invalidEstate(`State ${id} unreachable from empty`);\n }\n }\n}\n\nexport function resolveStateSelector(\n graph: MigrationGraph,\n selector: StateSelector | undefined\n): Sha256 {\n if (!selector) {\n if (graph.leaves.length === 1) return graph.leaves[0]!;\n if (graph.leaves.length === 0) {\n throw notFound(\"Estate has no states\");\n }\n throw pathRequired(\n graph.leaves.map((leaf) => [leaf]),\n \"Multiple leaves; specify --to / { to }\"\n );\n }\n if (\"id\" in selector) {\n if (!graph.states.has(selector.id)) {\n throw notFound(`Unknown state ${selector.id}`);\n }\n return selector.id;\n }\n if (\"prefix\" in selector) {\n return singleMatch(\n [...graph.states.keys()].filter((id) => id.startsWith(selector.prefix)),\n `No state has prefix ${selector.prefix}`\n );\n }\n return singleMatch(\n [...graph.states.values()]\n .filter((state) => state.name === selector.name)\n .map((state) => state.stateId),\n `No state named ${selector.name}`\n );\n}\n\nfunction singleMatch(matches: readonly Sha256[], missing: string): Sha256 {\n if (matches.length === 1) return matches[0]!;\n if (matches.length === 0) throw notFound(missing);\n throw pathRequired(\n matches.map((id) => [id]),\n AMBIGUOUS_SELECTOR\n );\n}\n\nexport function selectRoute(\n graph: MigrationGraph,\n origin: Sha256 | null,\n target: Sha256,\n via?: readonly Sha256[]\n): readonly Sha256[] {\n if (via && via.length > 0) {\n if (via.at(-1) !== target) {\n throw pathError(\"via must end at resolved target\");\n }\n const seen = new Set<string>();\n let previous = origin;\n for (const step of via) {\n if (seen.has(step)) {\n throw pathError(\"via repeats a state\");\n }\n seen.add(step);\n if (!hasEdge(graph, previous, step)) {\n throw pathError(\"via is not a real estate edge\");\n }\n previous = step;\n }\n return via;\n }\n\n const routes = enumerateRoutes(graph, origin, target, 2);\n if (routes.length === 1) return routes[0]!;\n if (routes.length === 0) {\n throw notFound(\"No path from marker to target\");\n }\n throw pathRequired(routes, \"Multiple paths; specify --via / { via }\");\n}\n\nfunction hasEdge(\n graph: MigrationGraph,\n from: Sha256 | null,\n to: Sha256\n): boolean {\n const state = graph.states.get(to);\n if (!state) return false;\n return state.parents.some((parent) => parent.fromState === from);\n}\n\n/**\n * Plan T4: what a history pruned at `checkpoint` keeps. The checkpoint, every\n * state after it, and every state those name as a parent, so no kept\n * transition dangles: a merge with older history keeps that history.\n */\nexport function statesFrom(\n graph: MigrationGraph,\n checkpoint: Sha256\n): ReadonlySet<Sha256> {\n const children = childrenIndex(graph);\n const closure = (\n start: Iterable<Sha256>,\n next: (id: Sha256) => readonly (Sha256 | null)[]\n ) => {\n const seen = new Set<Sha256>();\n const pending = [...start];\n while (pending.length > 0) {\n const id = pending.pop()!;\n if (seen.has(id)) continue;\n seen.add(id);\n for (const step of next(id)) if (step !== null) pending.push(step);\n }\n return seen;\n };\n return closure(\n closure([checkpoint], (id) => children.get(id) ?? []),\n (id) => graph.states.get(id)!.parents.map((parent) => parent.fromState)\n );\n}\n\nfunction childrenIndex(graph: MigrationGraph): Map<string, Sha256[]> {\n const index = new Map<string, Sha256[]>();\n index.set(\"null\", []);\n for (const id of graph.states.keys()) {\n index.set(id, []);\n }\n for (const [id, state] of graph.states) {\n for (const parent of state.parents) {\n const key = parent.fromState ?? \"null\";\n const list = index.get(key) ?? [];\n list.push(id);\n index.set(key, list);\n }\n }\n return index;\n}\n\nfunction enumerateRoutes(\n graph: MigrationGraph,\n origin: Sha256 | null,\n target: Sha256,\n limit: number\n): Sha256[][] {\n const children = childrenIndex(graph);\n const found: Sha256[][] = [];\n const stack: Array<{ from: Sha256 | null; path: Sha256[] }> = [\n { from: origin, path: [] },\n ];\n while (stack.length > 0 && found.length < limit) {\n const frame = stack.pop()!;\n for (const child of children.get(frame.from ?? \"null\") ?? []) {\n if (frame.path.includes(child)) continue;\n const next = [...frame.path, child];\n if (child === target) {\n found.push(next);\n if (found.length >= limit) break;\n continue;\n }\n stack.push({ from: child, path: next });\n }\n }\n return found;\n}\n\nconst AMBIGUOUS_SELECTOR =\n \"Ambiguous state selector; pass longer prefix or full id\";\n\nfunction pathRequired(\n routes: readonly (readonly Sha256[])[],\n hint: string\n): never {\n const witness: PathWitness = {\n routes: routes.slice(0, 2),\n frontier: firstFrontier(routes),\n more: routes.length > 2,\n };\n throw new MigrationError(\n `${hint}. Candidates: ${witness.routes\n .map((route) => route.join(\" -> \"))\n .join(\" | \")}`,\n VibORMErrorCode.MIGRATION_PATH_REQUIRED,\n { meta: { pathWitness: witness } }\n );\n}\n\nfunction firstFrontier(routes: readonly (readonly Sha256[])[]): Sha256[] {\n if (routes.length < 2) return [];\n const first = routes[0]!;\n const second = routes[1]!;\n const frontier: Sha256[] = [];\n const max = Math.min(first.length, second.length);\n for (let i = 0; i < max; i++) {\n if (first[i] !== second[i]) {\n frontier.push(first[i]!, second[i]!);\n return frontier;\n }\n }\n return frontier;\n}\n\n/** One edge of a route: its endpoints, transition, arrival state and SQL. */\nexport interface RouteEdge {\n readonly from: Sha256 | null;\n readonly to: Sha256;\n readonly transition: MigrationParentTransitionV1;\n readonly state: MigrationStateManifestV1;\n readonly blob: Uint8Array;\n}\n\n/**\n * The edges of `path` walked from `origin`. `parentTransition` refuses a\n * missing edge; the loaded graph holds every state and blob an edge names.\n */\nexport function routeEdges(\n graph: MigrationGraph,\n origin: Sha256 | null,\n path: readonly Sha256[]\n): RouteEdge[] {\n return path.map((to, index) => {\n const from = index === 0 ? origin : path[index - 1]!;\n const transition = parentTransition(graph, from, to);\n const state = graph.states.get(to)!;\n return { from, to, transition, state, blob: graph.sql.get(state.sqlHash)! };\n });\n}\n\nexport function parentTransition(\n graph: MigrationGraph,\n from: Sha256 | null,\n to: Sha256\n): MigrationParentTransitionV1 {\n const state = graph.states.get(to);\n if (!state) throw notFound(`Unknown state ${to}`);\n const found = state.parents.find((parent) => parent.fromState === from);\n if (!found) throw invalidEstate(\"Selected edge has no parent transition\");\n return found;\n}\n","/**\n * Whether the live database is what the durable record says (plan D5, S5):\n * the marker's standing in a history, drift against an authenticated\n * snapshot, and the lock not let go since a decision. One function per proof;\n * nothing here knows a command or a transport.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport {\n type appendLedger,\n CONTROL_TABLES,\n readControlState,\n sameMarker,\n unfinishedAttempts,\n} from \"./control\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { type MigrationGraph, requireStateSnapshot, routeEdges } from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport { introspectManaged } from \"./introspect-managed\";\nimport { lockedSinceDecision } from \"./pinned-session\";\nimport { fingerprintLive } from \"./push-fingerprint\";\nimport { managedTables, withManagedTables } from \"./target\";\nimport type { SchemaSnapshot } from \"./types\";\nimport { corrupt } from \"./v1-parse-shared\";\nimport type { MarkerIndexPredicateV1, MigrationMarkerV1 } from \"./v1-types\";\n\n/**\n * The command, its inventories selecting what an estate with a `tables` list\n * manages at state `at` (`managedTables`): the estate's frozen list and the\n * state's tables. Across the edge to or from `beside`, the other end's tables\n * too, so a proof on either side of a transition also sees what it creates or\n * drops — except a table the edge adopts, on the parent's side, where it is\n * still the user's raw table. Never the client's list. Without a list, the\n * command as it is.\n */\nexport function managedAt(\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n at: Sha256 | null,\n beside?: Sha256 | null\n): BoundMigrationDriver {\n const listed = graph.descriptor.target.tables;\n if (listed === undefined) return command;\n const own = requireStateSnapshot(graph, at);\n if (beside === undefined) {\n return withManagedTables(command, managedTables(listed, [own]));\n }\n // The graph admits an adoption only of a table the parent lacks.\n const edge =\n beside === null\n ? undefined\n : graph.states\n .get(beside)\n ?.parents.find((parent) => parent.fromState === at);\n return withManagedTables(\n command,\n managedTables(\n listed,\n [own, requireStateSnapshot(graph, beside)],\n edge?.adopts\n )\n );\n}\n\n/**\n * Where the live marker stands relative to this history. A marker naming a\n * state the graph holds — or no state — is `known`, and `assertNoDrift` proves\n * the rest. Otherwise its arrival path tells version skew from a stranger: the\n * marker is `ahead` when that path passes through a state of this estate\n * before leaving it (newer code applied the rest), and `unknown` when nothing\n * on it belongs here.\n */\nexport function markerStanding(\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null\n): \"known\" | \"ahead\" | \"unknown\" {\n if (!marker?.stateId || graph.states.has(marker.stateId)) return \"known\";\n return marker.estateHash === graph.estateHash &&\n marker.path.some((edge) => graph.states.has(edge.stateId))\n ? \"ahead\"\n : \"unknown\";\n}\n\n/**\n * Refuses a group whose decision was taken under a lock the command has since\n * let go (plans D1, S5): an earlier group committed, or SQLite committed the\n * decision's transaction to switch foreign keys. Read as the group's first\n * statements, under its own lock: if another command moved the marker in\n * between, nothing of this group runs. Apply leaves an attempt of its own open\n * between two groups only inside an edge split at Neki's commit boundaries,\n * and passes it with the steps it has confirmed: the attempt must be the only\n * one open, as far as this command left it, or another command resumed it.\n * Any other unfinished one is another command's. `down` passes `ownAttempt`\n * only for the attempt it resumes, and `reset` once its own attempt is open:\n * while it is, no other command opens one.\n */\nexport async function assertLockedSinceDecision(\n pinned: Parameters<typeof appendLedger>[0],\n producer: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n expected: MigrationMarkerV1 | null,\n ownAttempt:\n | boolean\n | { readonly attemptId: Sha256; readonly steps: number } = false\n): Promise<void> {\n if (lockedSinceDecision(pinned)) return;\n const { marker, ledger } = await readControlState(producer, command, {\n ledger: \"open\",\n });\n const open = unfinishedAttempts(ledger);\n const own =\n typeof ownAttempt === \"boolean\"\n ? ownAttempt || open.length === 0\n : open.length === 1 &&\n open[0]!.attemptId === ownAttempt.attemptId &&\n ledger.filter(\n (event) =>\n event.attemptId === ownAttempt.attemptId &&\n event.kind === \"step-confirmed\" &&\n event.effectState === \"committed\"\n ).length === ownAttempt.steps;\n if (sameMarker(marker, expected) && own) {\n return;\n }\n throw new MigrationError(\n \"Marker moved concurrently; retry.\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n}\n\nconst drift = (message: string, meta?: Record<string, unknown>) =>\n new MigrationError(\n message,\n VibORMErrorCode.MIGRATION_DRIFT,\n meta ? { meta } : undefined\n );\n\nexport async function assertNoDrift(\n producer: Parameters<typeof introspectManaged>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n marker: MigrationMarkerV1\n): Promise<void> {\n await proveLive(producer, command, graph, markedSnapshotHash(graph, marker));\n}\n\nexport function markedSnapshotHash(\n graph: MigrationGraph,\n marker: MigrationMarkerV1\n): Sha256 {\n if (marker.estateHash !== graph.estateHash) {\n throw drift(\"Marker estate mismatch\", {\n estateHash: marker.estateHash,\n });\n }\n if (marker.stateId) {\n const state = graph.states.get(marker.stateId);\n if (!state) corrupt(\"Marker state missing from estate\");\n if (state.snapshotHash !== marker.snapshotHash)\n throw drift(\"Marker snapshot mismatch\");\n } else if (marker.snapshotHash !== graph.emptySnapshotHash) {\n throw drift(\"Empty-path marker snapshot mismatch\");\n }\n if ((marker.path.at(-1)?.stateId ?? null) !== marker.stateId)\n corrupt(\"Marker path end mismatch\");\n let from: Sha256 | null = null;\n for (const edge of marker.path) {\n const state = graph.states.get(edge.stateId);\n const parent = state?.parents.find(\n (item) =>\n item.transitionHash === edge.transitionHash && item.fromState === from\n );\n if (!(state && parent)) corrupt(\"Marker path invalid\");\n from = edge.stateId;\n }\n return marker.snapshotHash;\n}\n\nexport async function proveLive(\n producer: Parameters<typeof introspectManaged>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n snapshotHash: Sha256,\n refusal: (\n differences: () => Promise<string>\n ) => Promise<string> | string = async (differences) =>\n `Live schema drifted from snapshot: ${await differences()}`\n): Promise<readonly MarkerIndexPredicateV1[]> {\n const expected = graph.snapshots.get(snapshotHash)!;\n const fingerprint = await fingerprintLive(expected, command, producer);\n const digest = await command.catalogDigest?.(producer, CONTROL_TABLES);\n if (digest !== undefined && digest === fingerprint) return [];\n const live = await introspectManaged(producer, command);\n if ((await fingerprintLive(live, command, producer)) !== fingerprint) {\n throw drift(\n await refusal(async () => JSON.stringify(summarizeDrift(live, expected)))\n );\n }\n if (digest !== undefined) {\n throw new MigrationError(\n \"PostgreSQL catalog digest disagrees with introspected schema.\",\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n if (command.target.dialect !== \"postgresql\") return [];\n return [...live.tables, ...(live.views ?? [])].flatMap((relation) =>\n (relation.indexes ?? []).flatMap((index) =>\n index.where\n ? [{ table: relation.name, index: index.name, deparsed: index.where }]\n : []\n )\n );\n}\n\nexport async function assertAdoptable(\n producer: Parameters<typeof introspectManaged>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n origin: Sha256 | null,\n path: readonly Sha256[]\n): Promise<void> {\n const adopted = routeEdges(graph, origin, path).flatMap(\n ({ transition }) => transition.adopts ?? []\n );\n if (adopted.length === 0) return;\n const hazards = await command.adoptionHazards(adopted, (sql, params) =>\n producer._executeRaw(sql, params)\n );\n const [first] = hazards;\n if (first === undefined) return;\n const features = hazards\n .filter(({ table }) => table === first.table)\n .map(({ feature }) => feature);\n throw drift(\n `Cannot adopt \"${first.table}\": unrepresented features (${features.join(\", \")}).`,\n { table: first.table }\n );\n}\n\nexport async function assertEmptyManaged(\n producer: Parameters<typeof introspectManaged>[0],\n command: BoundMigrationDriver\n): Promise<void> {\n const live = await introspectManaged(producer, command);\n if (\n live.tables.length > 0 ||\n (live.enums?.length ?? 0) > 0 ||\n (live.views?.length ?? 0) > 0\n ) {\n throw new MigrationError(\n \"apply requires empty target; use baseline to adopt.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n}\n\nfunction summarizeDrift(live: SchemaSnapshot, expected: SchemaSnapshot) {\n const byName = <T extends { readonly name: string }>(\n items: readonly T[] | undefined\n ) => new Map((items ?? []).map((item) => [item.name, item]));\n const diffSet = <T extends { readonly name: string }>(\n a: readonly T[] | undefined,\n b: readonly T[] | undefined\n ) => {\n const left = byName(a);\n const right = byName(b);\n const extra = [...left.keys()].filter((name) => !right.has(name)).sort();\n const missing = [...right.keys()].filter((name) => !left.has(name)).sort();\n const changed = [...left.keys()]\n .filter(\n (name) =>\n right.has(name) &&\n JSON.stringify(left.get(name)) !== JSON.stringify(right.get(name))\n )\n .sort();\n return {\n ...(extra.length > 0 ? { extra } : {}),\n ...(missing.length > 0 ? { missing } : {}),\n ...(changed.length > 0 ? { changed } : {}),\n };\n };\n return {\n tables: diffSet(live.tables, expected.tables),\n enums: diffSet(live.enums, expected.enums),\n views: diffSet(live.views, expected.views),\n };\n}\n","/**\n * Live-capability admission\n *\n * ONE decision admits a migration command to live database state. Direct\n * `push()` and every high-level migration command reach it here; no command\n * reinterprets either fact for itself.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { canPinSession, runsMigrationBatches } from \"./pinned-session\";\nimport { formatMigrationTarget, readNamespaceAttestation } from \"./target\";\n\n/**\n * What a command asks of live state.\n *\n * - `effectful` — the command can write, or promises a concurrency-stable\n * decision read from live state (apply/down/reset/verify/push, and the live\n * dry down/reset decisions the CLI confirms against).\n * - `batch` — effectful work whose every effect can go out as one atomic\n * request per transactional group (apply): admitted as `effectful` is, and\n * also on a PostgreSQL transport with no session that runs such a request\n * (plan D7), where that work refuses any step needing a session itself.\n * - `read-only` — a point-in-time read that changes nothing (status, log,\n * apply dry-run, push dry-run introspection).\n *\n * Offline and storage-only work — generate, check — never reaches this owner\n * at all.\n */\nexport type MigrationLiveRequirement = \"effectful\" | \"batch\" | \"read-only\";\n\n/**\n * Admits (or refuses) live migration work for one command.\n *\n * The failure precedence for MySQL is exact and is the whole point of the\n * owner: an absent attestation is `DRIVER_NOT_SUPPORTED`, and only AFTER the\n * capability is admitted does an absent namespace become\n * `MIGRATION_INVALID_STATE`. Reversing them would report a missing database\n * name for a driver whose routing was never provable in the first place.\n *\n * PostgreSQL namespaces are proven earlier, when the estate target is resolved\n * — a PostgreSQL driver with no adapter namespace never reaches a live\n * boundary. SQLite has no namespace to prove.\n */\nexport function admitLiveMigrationCapability(\n migrationDriver: BoundMigrationDriver,\n requirement: MigrationLiveRequirement,\n command: string\n): void {\n const { target } = migrationDriver;\n\n if (target.dialect === \"postgresql\") {\n admitPinnedSessionCapability(migrationDriver, requirement, command);\n return;\n }\n\n if (target.dialect === \"sqlite\") {\n admitSqliteFamilyCapability(migrationDriver, requirement, command);\n return;\n }\n\n if (target.dialect !== \"mysql\") {\n return;\n }\n\n if (requirement !== \"read-only\") {\n const attestation = readNamespaceAttestation(\n migrationDriver.executionDriver\n );\n if (attestation === undefined) {\n throw new MigrationError(\n `${command} refused: MySQL \"${migrationDriver.executionDriver.driverName}\" lacks migrationNamespaceAttestation.`,\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n {\n meta: {\n driver: migrationDriver.executionDriver.driverName,\n command,\n target: formatMigrationTarget(target, migrationDriver.namespace),\n },\n }\n );\n }\n }\n\n if (migrationDriver.namespace === undefined) {\n throw new MigrationError(\n `${command} requires MySQL namespace or database.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n driver: migrationDriver.executionDriver.driverName,\n command,\n target: formatMigrationTarget(target),\n },\n }\n );\n }\n}\n\nfunction admitSqliteFamilyCapability(\n migrationDriver: BoundMigrationDriver,\n requirement: MigrationLiveRequirement,\n command: string\n): void {\n const capability = migrationDriver.sqliteMigrationCapability;\n if (\n requirement === \"read-only\" ||\n (capability !== undefined && capability.exclusion !== \"none\")\n )\n return;\n const { driverName } = migrationDriver.executionDriver;\n throw new MigrationError(\n `${command} refused: SQLite \"${driverName}\" ${capability === undefined ? \"has no sqliteMigrationCapability\" : \"is read-only\"}.`,\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n {\n meta: {\n driver: driverName,\n command,\n target: formatMigrationTarget(migrationDriver.target),\n },\n }\n );\n}\n\nfunction admitPinnedSessionCapability(\n migrationDriver: BoundMigrationDriver,\n requirement: MigrationLiveRequirement,\n command: string\n): void {\n const driver = migrationDriver.executionDriver;\n if (\n requirement === \"read-only\" ||\n (requirement === \"batch\" && runsMigrationBatches(driver))\n )\n return;\n const meta = {\n driver: driver.driverName,\n command,\n target: formatMigrationTarget(migrationDriver.target),\n };\n if (!canPinSession(driver)) {\n throw new MigrationError(\n `${command} refused: \"${driver.driverName}\" has no interactive session.`,\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n { meta }\n );\n }\n if (driver.migrationSessionAttestation === \"dedicated-session\") return;\n const pooler = driver[\"migrationSessionEndpoints\"]?.()\n .flatMap(endpointHosts)\n .find((host) => HYPERDRIVE_HOST.test(host) || NEON_POOLER_HOST.test(host));\n if (pooler === undefined) return;\n throw new MigrationError(\n `${command} refused: \"${pooler}\" is a pooler; use direct endpoint or migrationSessionAttestation: \"dedicated-session\".`,\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n { meta }\n );\n}\n\n/** Cloudflare Hyperdrive's local endpoint, as a Worker binding names it. */\nconst HYPERDRIVE_HOST = /\\.hyperdrive\\.local\\.?$/i;\n/** A Neon endpoint id with the pooled-connection suffix. */\nconst NEON_POOLER_HOST = /^ep-[^.]*-pooler\\./i;\n/**\n * A URL's host list and query. Userinfo runs to the LAST `@` before the path,\n * as WHATWG URL (and so `pg-connection-string`) reads an unencoded `@`.\n */\nconst URL_PARTS =\n /^[a-z][a-z\\d+.-]*:\\/\\/(?:[^/?#]*@)?([^/?#]*)[^?#]*\\??([^#]*)/i;\nconst PORT = /:\\d*$/;\n\n/**\n * The host names one configured endpoint names, without ports: a bare host,\n * or every host of a (possibly multi-host) connection URL, including the\n * libpq `host` query parameter that overrides it.\n */\nfunction endpointHosts(endpoint: unknown): string[] {\n if (typeof endpoint !== \"string\") return [];\n const url = URL_PARTS.exec(endpoint);\n const hosts = url\n ? [url[1] ?? \"\", ...new URLSearchParams(url[2]).getAll(\"host\")]\n : [endpoint];\n return hosts.flatMap((list) =>\n list.split(\",\").map((host) => host.replace(PORT, \"\"))\n );\n}\n","/**\n * Client-to-migration-driver binding.\n *\n * Leaf module so runtime commands (`apply`, `status`, `verify`, `log`, `resume`)\n * resolve the bound migration driver without importing `push/planner.ts`\n * or `drivers/base.ts`.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { CLIENT_DIAGNOSTICS } from \"../drivers/execution-context\";\nimport type { DiagnosticDisclosure } from \"../errors\";\nimport type { AnyModel } from \"../schema/model\";\nimport {\n type BoundMigrationDriver,\n getMigrationDriver,\n getRuntimeMigrationDriver,\n} from \"./drivers/registry\";\nimport type { ResolvedMigrationLimits } from \"./limits\";\nimport { MANAGED_TABLES, MIGRATION_LIMITS } from \"./target\";\n\n/**\n * Minimal client interface required for migrations.\n * Allows migration commands to work with any object that has `$driver` and `$schema`.\n */\nexport interface MigrationClient {\n $driver: AnyDriver;\n $schema: Record<string, AnyModel>;\n readonly [MANAGED_TABLES]?: readonly string[] | undefined;\n readonly [MIGRATION_LIMITS]?: ResolvedMigrationLimits | undefined;\n /** The client's own `instrumentation({ diagnostics })`, when it has one. */\n readonly [CLIENT_DIAGNOSTICS]?: DiagnosticDisclosure | undefined;\n}\n\nexport function getPushMigrationDriver(\n client: MigrationClient\n): BoundMigrationDriver {\n return getMigrationDriver(\n client.$driver,\n client[MANAGED_TABLES],\n client[MIGRATION_LIMITS],\n client[CLIENT_DIAGNOSTICS]\n );\n}\n\nexport function getRuntimeClientDriver(\n client: MigrationClient\n): BoundMigrationDriver {\n return getRuntimeMigrationDriver(\n client.$driver,\n client[MANAGED_TABLES],\n client[MIGRATION_LIMITS],\n client[CLIENT_DIAGNOSTICS]\n );\n}\n","/**\n * The steps the operator commands and reset share: the command prologue, the\n * control read with its presence policy, and resuming an unfinished attempt\n * from its confirmed prefix (plan S3). Each caller keeps its own event filter:\n * which ledger rows confirm a step is its own rule.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport {\n admitLiveMigrationCapability,\n type MigrationLiveRequirement,\n} from \"./admission\";\nimport {\n getPushMigrationDriver,\n getRuntimeClientDriver,\n type MigrationClient,\n} from \"./client-driver\";\nimport {\n type MigrationControlRead,\n readControlState,\n refusePartialControl,\n} from \"./control\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport type { MigrationGraph } from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport { assertEstateTargetMatches, withManagedTables } from \"./target\";\nimport { corrupt } from \"./v1-parse-shared\";\nimport type {\n LedgerEventV1,\n MigrationOperationV1,\n MigrationStepV1,\n} from \"./v1-types\";\n\n/**\n * The client's migration driver, proven to address this estate's target, its\n * inventories selecting the estate's own frozen list rather than the client's\n * (which may name tables nothing adopted yet). Each proof restates the tables\n * its states manage (`managedAt`).\n */\nexport function openCommand(\n client: MigrationClient,\n graph: MigrationGraph,\n requirement: MigrationLiveRequirement,\n label: string,\n mode: \"runtime\" | \"full\" = \"runtime\"\n): BoundMigrationDriver {\n const driver =\n mode === \"full\"\n ? getPushMigrationDriver(client)\n : getRuntimeClientDriver(client);\n assertEstateTargetMatches(graph.descriptor.target, driver.target);\n admitLiveMigrationCapability(driver, requirement, label);\n return withManagedTables(driver, graph.descriptor.target.tables);\n}\n\n/**\n * The marker and the open ledger, partial control refused; `bootstrap`\n * admits what bootstrapping completes (both tables absent, or the log lost\n * after an interrupted bootstrap).\n */\nexport async function readCommandControl(\n producer: AnyDriver,\n command: BoundMigrationDriver,\n bootstrap = false\n): Promise<MigrationControlRead> {\n const control = await readControlState(producer, command, { ledger: \"open\" });\n if (!bootstrap || control.presence.kind === \"missing-table\") {\n refusePartialControl(control.presence);\n }\n return control;\n}\n\n/** The length of the confirmed prefix; a confirmed step past a gap is refused. */\nexport function confirmedPrefix(\n confirmed: ReadonlySet<number>,\n refusal: string\n): number {\n let length = 0;\n while (confirmed.has(length)) length += 1;\n if ([...confirmed].some((index) => index >= length)) corrupt(refusal);\n return length;\n}\n\n/**\n * Refuses to resume at an opaque stepwise dispatch announced and never\n * answered (confirmed, or its refusal recorded): it may have committed, and\n * running it again could repeat it.\n */\nexport function refuseAmbiguousNext(\n next: MigrationStepV1 | undefined,\n boundary: \"transactional\" | \"stepwise\" | undefined,\n announced: boolean,\n refusal: string\n): void {\n if (!(next?.retry === \"opaque\" && boundary === \"stepwise\" && announced)) {\n return;\n }\n throw new MigrationError(\n refusal,\n VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT,\n {\n meta: {\n lastConfirmedStep: next.execute.dispatchId,\n effectState: \"may-have-committed\",\n partial: true,\n },\n }\n );\n}\n\n/**\n * Counts one step's `step-confirmed` event into `unanswered`, per `key`: each\n * announcement (effect `none`) counts one, and each recorded refusal (`none`\n * with its `failure`: the server refused the statement whole) answers one. A\n * positive count is a dispatch occurrence that may have committed.\n */\nexport function countUnanswered<K>(\n unanswered: Map<K, number>,\n key: K,\n event: LedgerEventV1\n): void {\n if (event.effectState !== \"none\") return;\n unanswered.set(key, (unanswered.get(key) ?? 0) + (event.failure ? -1 : 1));\n}\n\n/** `operations` without their first `skip` steps. */\nexport function sliceOperations(\n operations: readonly MigrationOperationV1[],\n skip: number\n): MigrationOperationV1[] {\n let remaining = skip;\n return operations.flatMap((operation) => {\n if (remaining >= operation.steps.length) {\n remaining -= operation.steps.length;\n return [];\n }\n const steps = operation.steps.slice(remaining);\n remaining = 0;\n return [{ ...operation, steps }];\n });\n}\n\n/** The authenticated edge an attempt's `step-confirmed` events must name. */\nexport interface AttemptEdge {\n readonly direction: \"forward\" | \"rollback\";\n readonly estateHash: Sha256;\n readonly fromState: Sha256 | null;\n readonly toState: Sha256 | null;\n readonly transitionHash: Sha256;\n readonly sqlHash: Sha256;\n readonly operations: readonly MigrationOperationV1[];\n readonly boundary: \"transactional\" | \"stepwise\";\n}\n\n/**\n * What an unfinished attempt left to run of `edge`: its confirmed prefix of\n * steps, read from the attempt's own `step-confirmed` events, and the\n * operations past it. Progress naming another edge or an unknown dispatch, a\n * confirmed step past a gap, and an announced opaque stepwise step neither\n * confirmed nor answered by its recorded refusal (the server refused it\n * whole: it left nothing) are refused. `noun` names the direction in each\n * refusal.\n */\nexport function remainingSteps(\n ledger: readonly LedgerEventV1[],\n attempt: LedgerEventV1,\n edge: AttemptEdge,\n noun: \"Forward\" | \"Rollback\"\n): { readonly completed: number; readonly operations: MigrationOperationV1[] } {\n const steps = edge.operations.flatMap((operation) =>\n operation.steps.map((step) => ({ operation, step }))\n );\n const byDispatch = new Map(\n steps.map(({ step }, index) => [step.execute.dispatchId, index])\n );\n const committed = new Set<number>();\n // Announcements not answered by a recorded refusal, per step.\n const unanswered = new Map<number, number>();\n for (const event of ledger) {\n if (\n event.attemptId !== attempt.attemptId ||\n event.kind !== \"step-confirmed\"\n )\n continue;\n if (\n event.direction !== edge.direction ||\n event.estateHash !== edge.estateHash ||\n event.fromState !== edge.fromState ||\n event.toState !== edge.toState ||\n event.transitionHash !== edge.transitionHash ||\n event.sqlHash !== edge.sqlHash ||\n !event.dispatchId\n )\n corrupt(`${noun} progress edge mismatch`);\n const index = byDispatch.get(event.dispatchId);\n if (index === undefined || steps[index]!.operation.id !== event.operationId)\n corrupt(`${noun} progress unknown dispatch`);\n if (\n event.effectState === \"committed\" ||\n (steps[index]!.step.retry === \"proven\" &&\n event.effectState === \"none\" &&\n !event.failure)\n ) {\n committed.add(index);\n }\n countUnanswered(unanswered, index, event);\n }\n const completed = confirmedPrefix(\n committed,\n `${noun} progress non-contiguous`\n );\n refuseAmbiguousNext(\n steps[completed]?.step,\n edge.boundary,\n (unanswered.get(completed) ?? 0) > 0,\n `Next ${noun.toLowerCase()} dispatch ambiguous`\n );\n return { completed, operations: sliceOperations(edge.operations, completed) };\n}\n","/**\n * Apply V1: authenticate the graph, lock, refuse drift, execute exact slices,\n * then CAS the marker. Production never evaluates TypeScript.\n */\n\nimport { isVibORMError, MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { MigrationClient } from \"./client-driver\";\nimport {\n type AttemptEvents,\n advanceMarker,\n appendLedger,\n appendLedgerIfCheckHolds,\n attemptEvents,\n CONTROL_TABLES,\n ensureControlTables,\n markerFromPath,\n markerUnmovedCondition,\n markerWrite,\n readControlState,\n readPostgresDecision,\n refuseIncompatibleHistory,\n sameMarker,\n unfinishedAttempts,\n} from \"./control\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport {\n annotateMigrationFailure,\n assertAllChecks,\n checkCondition,\n executeOperations,\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 type { Sha256 } from \"./identity\";\nimport type { introspectManaged } from \"./introspect-managed\";\nimport {\n commitLockedTransaction,\n type MigrationBatch,\n migrationLockFree,\n openMigrationBatch,\n runProgram,\n runsMigrationBatches,\n withLockedMigrationProducer,\n} from \"./pinned-session\";\nimport {\n assertAdoptable,\n assertEmptyManaged,\n assertLockedSinceDecision,\n assertNoDrift,\n managedAt,\n markedSnapshotHash,\n markerStanding,\n proveLive,\n} from \"./proof\";\nimport { fingerprintDeparsed, fingerprintSnapshot } from \"./push-fingerprint\";\nimport { openCommand, readCommandControl, remainingSteps } from \"./resume\";\nimport {\n assertTransactionalBoundaryHonored,\n classifyStoredAtomicity,\n groupContiguousAtomicity,\n refuseSqliteStepwise,\n stepStatements,\n} from \"./runtime-dispatch\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport { catalogCommitBoundaries, UNCHANGED_CATALOG } from \"./statement-safety\";\nimport type { MigrationStorageReader } from \"./storage/contract\";\nimport type { SchemaSnapshot } from \"./types\";\nimport type {\n ApplyV1Options,\n LedgerEventV1,\n MarkerPathEdgeV1,\n MigrationBooleanCheckV1,\n MigrationMarkerV1,\n MigrationOperationV1,\n} from \"./v1-types\";\n\nexport interface ApplyV1Result {\n readonly outcome: \"applied\" | \"noop\" | \"preview\";\n readonly path: readonly Sha256[];\n readonly statements: readonly string[];\n /**\n * Present only when the migration committed but releasing a session lock\n * failed after it (MySQL, PostgreSQL). The session was discarded, so the\n * lock does not outlive it.\n */\n readonly warnings?: readonly string[];\n}\n\nexport async function applyV1(\n client: MigrationClient,\n storage: MigrationStorageReader,\n options: ApplyV1Options = {}\n): Promise<ApplyV1Result> {\n const graph = await loadMigrationGraph(storage);\n const dryRun = options.dryRun === true;\n const driver = openCommand(\n client,\n graph,\n dryRun ? \"read-only\" : \"batch\",\n dryRun ? \"apply({ dryRun: true })\" : \"apply()\"\n );\n const target = resolveStateSelector(graph, options.to);\n\n if (dryRun) {\n const control = await readCommandControl(client.$driver, driver);\n const decision = decide(graph, control.marker, target, options);\n if (!decision || decision.origin === target) {\n return { outcome: \"noop\", path: [], statements: [] };\n }\n const { origin, path, statements } = decision;\n // An edge split at Neki's commit boundaries previews what is left of it.\n const unfinished = unfinishedAttempts(control.ledger);\n const resume = mayResume(unfinished, control.marker)\n ? resumableAttempt(\n driver,\n graph,\n decision,\n unfinished[0]!,\n control.ledger\n )\n : undefined;\n return {\n outcome: \"preview\",\n path,\n statements: resume\n ? routeSql(graph, origin, path, resume).statements\n : statements,\n };\n }\n\n // Set once the path committed: a failure after it is the lock's release.\n const committed: { result?: ApplyV1Result } = {};\n const locked = withLockedMigrationProducer<ApplyV1Result>(\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 refuseIncompatibleHistory(marker, ledger);\n const unfinished = unfinishedAttempts(ledger);\n if (unfinished.length > 0 && !mayResume(unfinished, marker)) {\n throw unfinishedAttemptBlocks();\n }\n const decision = decide(graph, marker, target, options);\n // A transport with no session runs no edge as committed parts.\n const resume =\n unfinished.length === 0 || runsMigrationBatches(pinned)\n ? undefined\n : resumableAttempt(command, graph, decision, unfinished[0]!, ledger);\n if (unfinished.length > 0 && !resume) throw unfinishedAttemptBlocks();\n if (!decision) return { outcome: \"noop\", path: [], statements: [] };\n const { origin, path } = decision;\n const route = routeSql(graph, origin, path, resume);\n const splits = await command.preflightSchemaRequirements(\n [\n requireStateSnapshot(graph, origin),\n ...path.map((stateId) => requireStateSnapshot(graph, stateId)),\n ],\n (sql, params) => pinned._executeRaw(sql, params),\n route.chunks,\n // One request per group holds no part's progress: refused instead.\n !runsMigrationBatches(pinned)\n );\n await assertAdoptable(pinned, command, graph, origin, path);\n // A resumed edge's committed parts are already past the marker's\n // snapshot: the destination proof of its last part proves the rest.\n // Across the first edge: a table it adopts is not proven yet.\n if (resume === undefined && marker) {\n await assertNoDrift(\n pinned,\n managedAt(command, graph, origin, path[0]),\n graph,\n marker\n );\n } else if (resume === undefined) {\n await assertEmptyManaged(\n pinned,\n managedAt(command, graph, null, path[0])\n );\n }\n if (origin === target) {\n return { outcome: \"noop\", path: [], statements: [] };\n }\n // On MySQL the whole path is one sequential program.\n await runProgram(pinned, command, undefined, (producer) =>\n applyPathUnderLock(\n producer,\n command,\n graph,\n marker,\n origin,\n path,\n client.$schema,\n needsBootstrap,\n { splits, resume }\n )\n );\n committed.result = {\n outcome: \"applied\",\n path,\n statements: resume ? route.statements : decision.statements,\n };\n return committed.result;\n },\n driver.target.dialect === \"postgresql\"\n ? (session, lockFree) =>\n provenNoop(\n session,\n lockFree,\n managedAt(driver, graph, target),\n graph,\n target,\n options\n )\n : undefined\n );\n return keepCommittedOutcome(committed, locked);\n}\n\n/**\n * Plan D5 (decision 7): a PostgreSQL apply with nothing to do proves it\n * before the lock, in two statements: the control tables' definition, then\n * the marker, the open attempts and the catalog digest, read in one snapshot\n * while no other command holds the lock (`lockFree`). A database at the\n * target, with nothing open and no drift, was there at that instant, which is\n * all a no-op claims, and it writes nothing a lock would protect. Anything\n * else — another command at work included — or anything this read cannot\n * decide, goes to the locked path, which decides again under the lock.\n */\nasync function provenNoop(\n session: Parameters<typeof introspectManaged>[0],\n lockFree: string,\n driver: BoundMigrationDriver,\n graph: MigrationGraph,\n target: Sha256,\n options: ApplyV1Options\n): Promise<ApplyV1Result | undefined> {\n const decision = await readPostgresDecision(\n session,\n driver,\n lockFree,\n target\n );\n const marker = decision?.marker;\n if (!marker || unfinishedAttempts(decision.ledger).length > 0) return;\n // A refusal thrown here is decided again, and thrown, under the lock.\n if (followsAheadPolicy(graph, marker, options)) {\n return { outcome: \"noop\", path: [], statements: [] };\n }\n if (marker.stateId !== target) return;\n const liveDigest =\n decision.digest ??\n (decision.liveSnapshot\n ? fingerprintSnapshot(decision.liveSnapshot, driver)\n : undefined);\n if (liveDigest === undefined) return;\n // `markedSnapshotHash` proved the snapshot is in the estate. Partial-index\n // predicates compare as the server deparsed them: the live ones in the\n // digest/snapshot, the snapshot's from the record beside the marker.\n const expected = graph.snapshots.get(markedSnapshotHash(graph, marker))!;\n return liveDigest ===\n fingerprintDeparsed(expected, decision.predicates, driver)\n ? { outcome: \"noop\", path: [], statements: [] }\n : undefined;\n}\n\n/**\n * The outcome of a command whose work committed, even when ending its session\n * afterwards failed (releasing a session lock, or closing a locked read): the\n * marker already proves the commit (plan S3).\n */\nasync function keepCommittedOutcome(\n committed: { readonly result?: ApplyV1Result },\n command: Promise<ApplyV1Result>\n): Promise<ApplyV1Result> {\n try {\n return await command;\n } catch (failure) {\n if (committed.result === undefined) throw failure;\n return {\n ...committed.result,\n warnings: [\n `Migration committed, but session close failed (${describeFailure(failure)}).`,\n ],\n };\n }\n}\n\n/** True when `ifAhead: \"noop\"` applies; refuses every other marker this history does not hold. */\nfunction followsAheadPolicy(\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null,\n options: ApplyV1Options\n): boolean {\n const standing = markerStanding(graph, marker);\n if (standing === \"known\") return false;\n if (standing === \"ahead\" && options.ifAhead === \"noop\") return true;\n throw new MigrationError(\n standing === \"ahead\"\n ? `Marker is ahead of history (${marker?.stateId}); deploy newer code or pass apply({ ifAhead: \"noop\" }).`\n : `Marker names unknown state ${marker?.stateId}.`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n}\n\n/**\n * What apply does from `marker`, shared by the dry run and the locked apply:\n * its ahead policy, origin, route and authenticated artifacts. `undefined`\n * when `ifAhead: \"noop\"` applies.\n */\nfunction decide(\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null,\n target: Sha256,\n options: ApplyV1Options\n):\n | { origin: Sha256 | null; path: readonly Sha256[]; statements: string[] }\n | undefined {\n if (followsAheadPolicy(graph, marker, options)) return;\n const origin = marker?.stateId ?? null;\n const path =\n origin === target ? [] : selectRoute(graph, origin, target, options.via);\n return { origin, path, statements: previewStatements(graph, origin, path) };\n}\n\nasync function applyPathUnderLock(\n pinned: import(\"../drivers/driver\").AnyDriver,\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null,\n origin: Sha256 | null,\n path: readonly Sha256[],\n models: MigrationClient[\"$schema\"],\n needsBootstrap: boolean,\n { splits, resume }: { readonly splits: boolean; readonly resume?: Resume }\n): Promise<void> {\n const batched = runsMigrationBatches(pinned);\n if (batched) requireBatchDigest(command);\n const prepared = routeEdges(graph, origin, path).map((edge) => {\n const requested = edge.transition.requestedForwardBoundary;\n assertTransactionalBoundaryHonored(\n pinned.supportsTransactions || batched,\n requested\n );\n const boundary = classifyStoredAtomicity(\n command,\n requested,\n edge.transition.operations,\n edge.blob\n );\n refuseSqliteStepwise(command, requested, edge.to);\n if (batched && boundary === \"stepwise\") {\n refuseBatchedStepwise(pinned, edge.to);\n }\n return { ...edge, boundary };\n });\n\n let current = marker;\n const nextPath = marker ? [...marker.path] : [];\n // Before the program, as statements of their own: one request cannot read\n // what the bootstrap reads (plan D7), and a PostgreSQL bootstrap commits.\n if (needsBootstrap) {\n await ensureControlTables(pinned, command);\n await commitLockedTransaction(pinned, command);\n }\n const statementsOf = ({ transition, blob }: PreparedForwardEdge) =>\n stepStatements(blob, transition.operations);\n const groups = groupContiguousAtomicity(prepared, statementsOf);\n const first = groups[0]?.items[0];\n for (const group of splits || resume\n ? splitAtCatalogBoundaries(graph, groups, splits, resume)\n : groups) {\n if (\"split\" in group) {\n current = await applySplitEdge(\n pinned,\n command,\n graph,\n group.split,\n current,\n nextPath,\n models\n );\n continue;\n }\n if (batched) {\n current = await applyGroupBatch(\n pinned,\n command,\n graph,\n group.items,\n current,\n nextPath,\n models\n );\n continue;\n }\n const running: { attempt?: ForwardAttempt } = {};\n // The edge the group is running, which a failure no statement named is.\n const runningEdge: { to?: Sha256 } = {};\n // A resumed stepwise edge: its attempt stays open, as apply left it.\n const resumed = group.items[0] === first ? resume : undefined;\n const run = async (\n producer: Parameters<typeof appendLedger>[0],\n atomic: boolean\n ) => {\n await assertLockedSinceDecision(\n pinned,\n producer,\n command,\n current,\n resumed && {\n attemptId: resumed.attempt.attemptId,\n steps: resumed.completed,\n }\n );\n if (atomic) {\n current = await executeAtomicGroup(\n producer,\n command,\n graph,\n group.items,\n running,\n current,\n nextPath,\n models\n );\n return;\n }\n // Edge by edge, each step probed and recorded as it runs.\n for (const [index, item] of group.items.entries()) {\n runningEdge.to = item.to;\n const own = index === 0 ? resumed : undefined;\n const attempt = forwardAttempt(graph, item, own?.attempt.attemptId);\n if (own === undefined) {\n await appendLedger(\n producer,\n command,\n attempt.event(\"started\", \"none\")\n );\n }\n await runForwardEdge(\n producer,\n command,\n graph,\n attempt,\n nextPath,\n models,\n true,\n undefined,\n own && {\n operations: own.operations,\n origin: own.completed === 0,\n destination: true,\n },\n item === first &&\n own === undefined &&\n !item.transition.adopts?.length &&\n (!needsBootstrap || command.commitsSchemaChangesAlone())\n );\n current = await commitEdgeArrival(\n producer,\n command,\n graph,\n item,\n current,\n nextPath,\n attempt\n );\n }\n };\n const phase = { committing: false, committed: false };\n const program = {\n transactional: group.boundary === \"transactional\",\n statements: group.items.flatMap(statementsOf),\n phase,\n };\n try {\n // On MySQL the path already runs as one sequential program (`applyV1`).\n await (command.target.dialect === \"mysql\"\n ? run(pinned, false)\n : runProgram(pinned, command, program, run));\n } catch (raised) {\n // A failure no statement named is this group's: its commit, its lock.\n const failure = annotateMigrationFailure(raised, {\n step: \"apply\",\n strategy: group.boundary,\n stateId: running.attempt?.item.to ?? runningEdge.to,\n });\n // Past the commit only the foreign-key restore can fail: it is reported.\n if (phase.committed) throw failure;\n if (\n phase.committing &&\n (await commitLanded(pinned, command, group.items, current, failure))\n ) {\n // Its COMMIT landed: what it builds in the background is waited for.\n await command.awaitIndexBuilds?.(pinned, program.statements);\n continue;\n }\n await recordFailedAttempt(pinned, command, running, failure);\n throw failure;\n }\n }\n}\n\n/**\n * Plan D7, refused while the path is prepared, before any of it runs: a\n * transport with no session runs only transactional groups, each as one\n * request.\n */\nasync function commitEdgeArrival(\n producer: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n item: PreparedForwardEdge,\n current: MigrationMarkerV1 | null,\n nextPath: readonly MarkerPathEdgeV1[],\n attempt: ForwardAttempt\n): Promise<MigrationMarkerV1> {\n const { snapshotHash } = item.state;\n const next = await advanceMarker(\n producer,\n command,\n graph.estateHash,\n current,\n [...nextPath],\n snapshotHash,\n 1,\n await proveLive(\n producer,\n managedAt(command, graph, item.to, item.from),\n graph,\n snapshotHash\n )\n );\n await appendLedger(producer, command, attempt.event(\"applied\", \"committed\"));\n return next;\n}\n\nfunction refuseBatchedStepwise(\n pinned: import(\"../drivers/driver\").AnyDriver,\n toState: Sha256\n): never {\n throw new MigrationError(\n `Driver \"${pinned.driverName}\" cannot run stepwise; use a session driver.`,\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER,\n { meta: { dialect: \"postgresql\", toState, feature: \"stepwise execution\" } }\n );\n}\n\n/** One committed part of a forward edge: its steps, and which checks it runs. */\ninterface ForwardPart {\n readonly operations: readonly MigrationOperationV1[];\n readonly origin: boolean;\n readonly destination: boolean;\n}\n\n/**\n * One forward edge, from its origin checks to its destination checks, its\n * arrival pushed onto `nextPath`; the caller proves the destination, moves\n * the marker and records the arrival. A `probed` edge runs step by step and\n * records each confirmed step; otherwise it runs inside a real transaction,\n * or one request (`batch`), whose rollback is the proof of every step. A\n * `part` of an edge split at Neki's commit boundaries runs only its steps,\n * each recorded in the part's transaction, and the checks it holds.\n */\nasync function runForwardEdge(\n producer: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n attempt: ForwardAttempt,\n nextPath: MarkerPathEdgeV1[],\n models: MigrationClient[\"$schema\"],\n probed: boolean,\n batch?: MigrationBatch,\n part?: ForwardPart,\n provenOrigin = false\n): Promise<void> {\n const { from, to, transition, state, blob, boundary } = attempt.item;\n if (part?.origin ?? true) {\n await assertAllChecks(\n producer,\n blob,\n transition.originChecks,\n command.namespace,\n \"Origin checks failed\",\n batch\n );\n }\n await executeOperations(\n producer,\n blob,\n part?.operations ?? transition.operations,\n probed ? boundary : \"atomic\",\n probed || part\n ? (progress, effect, failure) =>\n appendLedger(\n producer,\n command,\n attempt.event(\n \"step-confirmed\",\n progress.skipped ? \"committed\" : effect,\n progress,\n failure\n )\n )\n : undefined,\n command.namespace,\n { fromState: from, toState: to, step: \"apply\" },\n probed\n ? {\n provenOrigin,\n ...(command.target.dialect === \"postgresql\"\n ? {\n confirmProvenStep: (postcheck, progress) => {\n const { sql, params } = checkCondition(\n blob,\n postcheck,\n command.namespace\n );\n return appendLedgerIfCheckHolds(\n producer,\n command,\n attempt.event(\"step-confirmed\", \"committed\", progress),\n sql,\n params\n );\n },\n }\n : {}),\n }\n : undefined\n );\n if (!(part?.destination ?? true)) return;\n // Manual SQL may store text typed queries cannot compare (`datetime('now')`).\n await command.canonicalizeLiveStorage?.(\n producer,\n transition.operations,\n models,\n requireStateSnapshot(graph, to)\n );\n await assertAllChecks(\n producer,\n blob,\n state.destinationChecks,\n command.namespace,\n \"Destination checks failed\",\n batch\n );\n nextPath.push({\n stateId: to,\n transitionHash: transition.transitionHash,\n baselineBoundary: false,\n });\n}\n\n/**\n * One group inside a real transaction (plan D5). Its rollback is the proof\n * of every step, so the statements run unprobed and leave no progress rows\n * or `started` events; the group's last state is proven once, the marker\n * moves once (by one revision per edge, as edge by edge), and every edge's\n * `applied` event lands in one statement. Between the first DDL and the\n * COMMIT this sends the DDL, the authored checks and three control\n * statements.\n */\nasync function executeAtomicGroup(\n producer: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n items: readonly PreparedForwardEdge[],\n running: { attempt?: ForwardAttempt },\n current: MigrationMarkerV1 | null,\n nextPath: MarkerPathEdgeV1[],\n models: MigrationClient[\"$schema\"],\n batch?: MigrationBatch\n): Promise<MigrationMarkerV1> {\n const arrivals: LedgerEventV1[] = [];\n for (const item of items) {\n running.attempt = forwardAttempt(graph, item);\n await runForwardEdge(\n producer,\n command,\n graph,\n running.attempt,\n nextPath,\n models,\n false,\n batch\n );\n arrivals.push(running.attempt.event(\"applied\", \"committed\"));\n }\n const last = items.at(-1)!;\n const { snapshotHash } = last.state;\n // The destination proves every table the last edge adopts.\n const destination = managedAt(command, graph, last.to, last.from);\n let next: MigrationMarkerV1;\n if (batch) {\n assertDigest(batch, destination, requireStateSnapshot(graph, last.to));\n next = markerFromPath(\n graph.estateHash,\n snapshotHash,\n [...nextPath],\n (current?.revision ?? 0) + items.length\n );\n // The request asserted `current` under its lock first.\n const write = markerWrite(command, current, next);\n await producer._executeRaw(write.sql, write.params);\n } else {\n next = await advanceMarker(\n producer,\n command,\n graph.estateHash,\n current,\n [...nextPath],\n snapshotHash,\n items.length,\n await proveLive(producer, destination, graph, snapshotHash)\n );\n }\n await appendLedger(producer, command, ...arrivals);\n return next;\n}\n\n/**\n * Plan D7: one transactional group as ONE request, on a transport with no\n * session. The request takes the transaction lock, asserts that the marker\n * is still the one this command decided on and that no attempt is open\n * ({@link assertLockedSinceDecision} in SQL), then runs the group as\n * {@link executeAtomicGroup} does, its checks and destination proof asserted\n * in SQL. A request the server refused rolled back; after a lost reply the\n * marker says whether it committed ({@link commitLanded}).\n */\nasync function applyGroupBatch(\n driver: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n items: readonly PreparedForwardEdge[],\n current: MigrationMarkerV1 | null,\n nextPath: MarkerPathEdgeV1[],\n models: MigrationClient[\"$schema\"]\n): Promise<MigrationMarkerV1> {\n const batch = openMigrationBatch(driver, command);\n const unmoved = markerUnmovedCondition(command, current);\n batch.assert(\n unmoved.sql,\n unmoved.params,\n new MigrationError(\n \"Marker moved concurrently; retry.\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n )\n );\n const running: { attempt?: ForwardAttempt } = {};\n const next = await executeAtomicGroup(\n batch.producer,\n command,\n graph,\n items,\n running,\n current,\n nextPath,\n models,\n batch\n );\n try {\n await batch.send();\n } catch (failure) {\n if (\n !(failure instanceof MigrationError) &&\n (await commitLanded(driver, command, items, next, failure))\n ) {\n return next;\n }\n // Refused for the lock or a moved marker, the request ran none of the\n // group: a session refuses both before the attempt, recording nothing.\n const refusedBeforeGroup =\n failure instanceof MigrationError &&\n (failure.code === VibORMErrorCode.MIGRATION_LOCK_FAILED ||\n failure.code === VibORMErrorCode.MIGRATION_MARKER_CONFLICT);\n if (!refusedBeforeGroup) {\n await recordFailedAttempt(driver, command, running, failure);\n }\n throw failure;\n }\n return next;\n}\n\n/**\n * The destination proof inside one request (plan D7): the catalog digest\n * (`catalog-digest.ts`) is the snapshot's fingerprint. Where the digest\n * abstains, the request cannot prove the destination, and is refused.\n */\nfunction requireBatchDigest(\n command: BoundMigrationDriver\n): asserts command is BoundMigrationDriver & {\n readonly catalogDigestQuery: NonNullable<\n BoundMigrationDriver[\"catalogDigestQuery\"]\n >;\n} {\n if (!command.catalogDigestQuery) {\n throw new MigrationError(\n 'Stateless batch drivers require the full \"viborm/migrations/postgres\" entrypoint (catalogDigestQuery is not included in the runtime-only driver).',\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n }\n}\n\nfunction assertDigest(\n batch: MigrationBatch,\n command: BoundMigrationDriver,\n snapshot: SchemaSnapshot\n): void {\n requireBatchDigest(command);\n const digest = command.catalogDigestQuery(CONTROL_TABLES);\n batch.assert(\n `(${digest.sql}) IS NOT NULL`,\n digest.parameters,\n new MigrationError(\n \"Catalog digest abstains; use a session driver.\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n )\n );\n batch.assert(\n `(${digest.sql}) = $7`,\n [...digest.parameters, fingerprintSnapshot(snapshot, command)],\n new MigrationError(\n \"Live schema drifted from snapshot\",\n VibORMErrorCode.MIGRATION_DRIFT\n )\n );\n}\n\n/**\n * Whether a transaction whose COMMIT was sent, and then failed, committed.\n * The marker it compare-and-swapped answers: it commits with the transition\n * or not at all. When even the marker cannot be read, the outcome is the\n * ambiguous commit V11020 it is (plan S3). Without a session (plan D7) it is\n * read only while no command holds the lock, so never while the request\n * whose reply was lost may still run.\n */\nasync function commitLanded(\n pinned: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n items: readonly PreparedForwardEdge[],\n expected: MigrationMarkerV1 | null,\n failure: unknown\n): Promise<boolean> {\n // On a lost connection the pinned view refuses this read (plan S2).\n const marker = await (runsMigrationBatches(pinned)\n ? readPostgresDecision(pinned, command, migrationLockFree(command)).then(\n (decision) => decision?.marker\n )\n : readControlState(pinned, command, {\n ledger: \"open\",\n }).then((control) => control.marker)\n ).catch(() => undefined);\n if (marker === undefined) {\n const fromState = items[0]?.from ?? null;\n throw new MigrationError(\n \"COMMIT reply lost and marker unreadable; check status() or retry apply().\",\n VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT,\n {\n cause: failure instanceof Error ? failure : undefined,\n meta: {\n ...(fromState === null ? {} : { fromState }),\n toState: items.at(-1)?.to,\n effectState: \"may-have-committed\",\n commitCertainty: \"may-have-committed\",\n },\n }\n );\n }\n return marker !== null && sameMarker(marker, expected);\n}\n\n/**\n * Leaves the durable record of a rolled-back attempt, whose own events the\n * rollback took with it: a `failed` event, in a transaction of its own, after\n * bootstrapping the control tables a failed first apply rolled back. The pinned\n * view sends nothing on a lost connection (plan S2), and a record that cannot be written\n * never replaces the failure it records.\n */\nasync function recordFailedAttempt(\n pinned: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n running: { readonly attempt?: ForwardAttempt },\n failure: unknown\n): Promise<void> {\n const { attempt } = running;\n if (attempt === undefined) return;\n const meta = isVibORMError(failure) ? failure.meta : {};\n const event = attempt.event(\n \"failed\",\n \"none\",\n {\n operationId:\n typeof meta.operationId === \"string\" ? meta.operationId : null,\n dispatchId: typeof meta.dispatchId === \"string\" ? meta.dispatchId : null,\n },\n describeFailure(failure)\n );\n try {\n if (runsMigrationBatches(pinned)) {\n // Its control tables were made before the request (plan D7).\n await appendLedger(pinned, command, event);\n return;\n }\n await pinned.withTransaction(async (transaction) => {\n await ensureControlTables(transaction, command);\n await appendLedger(transaction, command, event);\n });\n } catch {\n // Best effort: the caller is owed the failure itself, not this one.\n }\n}\n\nfunction describeFailure(failure: unknown): string {\n if (isVibORMError(failure)) return `${failure.code}: ${failure.message}`;\n return failure instanceof Error ? failure.name : \"a non-error value\";\n}\n\ninterface PreparedForwardEdge extends RouteEdge {\n readonly boundary: \"transactional\" | \"stepwise\";\n}\n\n/** One edge's attempt: the edge, and the builder of its ledger events. */\ninterface ForwardAttempt extends AttemptEvents {\n readonly item: PreparedForwardEdge;\n}\n\nfunction forwardAttempt(\n graph: MigrationGraph,\n item: PreparedForwardEdge,\n attemptId?: Sha256\n): ForwardAttempt {\n return {\n item,\n ...attemptEvents(\n {\n estateHash: graph.estateHash,\n snapshotHash: item.state.snapshotHash,\n sqlHash: item.state.sqlHash,\n fromState: item.from,\n toState: item.to,\n transitionHash: item.transition.transitionHash,\n direction: \"forward\",\n },\n attemptId\n ),\n };\n}\n\nfunction previewStatements(\n graph: MigrationGraph,\n origin: Sha256 | null,\n path: readonly Sha256[]\n): string[] {\n return routeEdges(graph, origin, path).flatMap(({ blob, transition }) =>\n stepStatements(blob, transition.operations)\n );\n}\n\nfunction unfinishedAttemptBlocks(): MigrationError {\n return new MigrationError(\n \"Unfinished attempt blocks work\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n}\n\n/**\n * Whether the open attempts may be one apply resumes: one forward attempt,\n * opened from the marker. Read before the route, so any other open attempt\n * blocks as it always has.\n */\nfunction mayResume(\n unfinished: readonly LedgerEventV1[],\n marker: MigrationMarkerV1 | null\n): boolean {\n const [attempt] = unfinished;\n return (\n unfinished.length === 1 &&\n attempt?.kind === \"started\" &&\n attempt.direction === \"forward\" &&\n attempt.fromState === (marker?.stateId ?? null)\n );\n}\n\n/**\n * An unfinished edge apply resumes: one split at Neki's commit boundaries\n * whose first parts committed, or a stepwise one whose next unconfirmed step\n * can be decided safely (a proven step, an unannounced or server-refused\n * opaque step, or all steps already confirmed).\n */\ninterface Resume {\n readonly attempt: LedgerEventV1;\n /** The steps its committed parts confirmed. */\n readonly completed: number;\n /** The operations past them. */\n readonly operations: readonly MigrationOperationV1[];\n}\n\n/**\n * What apply resumes of `attempt`, which {@link mayResume} admitted, or\n * `undefined`, on the first edge of the route apply selected, on PostgreSQL:\n * - a transactional edge split at Neki's commit boundaries: each committed\n * part recorded its steps in its own transaction, so their prefix is exact;\n * - a stepwise edge whose next unconfirmed step has no ambiguous opaque\n * dispatch in flight: a proven step (re-checked via its postcheck/precheck),\n * an opaque step that was never announced or whose announcement was answered\n * by a recorded server refusal, or an attempt whose steps all committed\n * before destination proof/marker commit. An announced opaque step with no\n * recorded refusal (a lost connection mid-opaque-SQL, `DO`, `CONCURRENTLY`)\n * still blocks.\n * Either way the origin checks ran before the first step, against the\n * origin; the resumed steps run without them, against the confirmed prefix,\n * and the destination checks and proof close the edge.\n */\nfunction resumableAttempt(\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n decision: ReturnType<typeof decide>,\n attempt: LedgerEventV1,\n ledger: readonly LedgerEventV1[]\n): Resume | undefined {\n if (!decision?.path.length || command.target.dialect !== \"postgresql\") {\n return;\n }\n const [edge] = routeEdges(graph, decision.origin, decision.path);\n const { from, to, transition, state, blob } = edge!;\n const boundary = classifyStoredAtomicity(\n command,\n transition.requestedForwardBoundary,\n transition.operations,\n blob\n );\n if (\n attempt.toState !== to ||\n attempt.transitionHash !== transition.transitionHash\n ) {\n return;\n }\n let remaining: ReturnType<typeof remainingSteps>;\n try {\n remaining = remainingSteps(\n ledger,\n attempt,\n {\n direction: \"forward\",\n estateHash: graph.estateHash,\n fromState: from,\n toState: to,\n transitionHash: transition.transitionHash,\n sqlHash: state.sqlHash,\n operations: transition.operations,\n boundary,\n },\n \"Forward\"\n );\n } catch (error) {\n // An announced opaque stepwise step with no recorded refusal may have\n // committed: apply refuses it as an unfinished attempt (V11016).\n if (\n boundary === \"stepwise\" &&\n error instanceof MigrationError &&\n error.code === VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT\n ) {\n return;\n }\n throw error;\n }\n return { attempt, ...remaining };\n}\n\n/**\n * The SQL one transaction runs for an edge, in its order: the origin checks\n * (unless `origin` is false: a resumed edge ran them), `operations`' steps\n * and the destination checks. `before` counts the origin checks.\n */\nfunction edgeSql(\n { transition, state, blob }: RouteEdge,\n operations: readonly MigrationOperationV1[],\n origin: boolean\n): {\n readonly chunks: string[];\n readonly steps: string[];\n readonly before: number;\n} {\n const checks = (list: readonly MigrationBooleanCheckV1[]) =>\n list.map((check) => sliceDispatch(blob, check.query));\n const before = origin ? checks(transition.originChecks) : [];\n const steps = stepStatements(blob, operations);\n return {\n chunks: [...before, ...steps, ...checks(state.destinationChecks)],\n steps,\n before: before.length,\n };\n}\n\n/**\n * What apply runs along `path`, a resumed first edge from its remaining\n * steps: every edge's checks and steps (`chunks`, which PlanetScale's Neki\n * reads for commit boundaries) and the steps alone (`statements`).\n */\nfunction routeSql(\n graph: MigrationGraph,\n origin: Sha256 | null,\n path: readonly Sha256[],\n resume: Resume | undefined\n): { readonly chunks: string[]; readonly statements: string[] } {\n const chunks: string[] = [];\n const statements: string[] = [];\n for (const [index, edge] of routeEdges(graph, origin, path).entries()) {\n const resumed = index === 0 ? resume : undefined;\n const sql = edgeSql(\n edge,\n resumed?.operations ?? edge.transition.operations,\n resumed === undefined\n );\n chunks.push(...sql.chunks);\n statements.push(...sql.steps);\n }\n return { chunks, statements };\n}\n\n/** One edge apply runs as committed parts, alone in its group. */\ninterface SplitEdge {\n readonly attempt: ForwardAttempt;\n /** Whether its attempt is open already: its first parts committed earlier. */\n readonly resumed: boolean;\n /** The steps confirmed before this command. */\n readonly completed: number;\n /**\n * Each part's operations, in order. The origin checks run with the first,\n * the destination checks and the marker with the last, which holds no step\n * when the checks themselves need a commit.\n */\n readonly parts: readonly (readonly MigrationOperationV1[])[];\n}\n\ntype PlannedGroup =\n | ReturnType<typeof groupContiguousAtomicity<PreparedForwardEdge>>[number]\n | { readonly split: SplitEdge };\n\n/** The steps `from` (inclusive) to `to` (exclusive) of `operations`. */\nfunction stepRange(\n operations: readonly MigrationOperationV1[],\n from: number,\n to: number\n): MigrationOperationV1[] {\n let index = 0;\n return operations.flatMap((operation) => {\n const first = index;\n index += operation.steps.length;\n const steps = operation.steps.filter(\n (_, position) => first + position >= from && first + position < to\n );\n return steps.length === 0 ? [] : [{ ...operation, steps }];\n });\n}\n\n/**\n * Plan D5's groups, on PlanetScale's Neki (`splits`), cut where its planner\n * needs a commit (`catalogCommitBoundaries`): an edge joins the group before\n * it while none of its statements needs one; one that needs one only because\n * of that group starts a group of its own; one that needs one because of its\n * own changes runs alone, as committed parts. A resumed first edge runs alone\n * from its remaining steps, on any PostgreSQL. A stepwise group commits each\n * statement already.\n */\nfunction splitAtCatalogBoundaries(\n graph: MigrationGraph,\n groups: ReturnType<typeof groupContiguousAtomicity<PreparedForwardEdge>>,\n splits: boolean,\n resume: Resume | undefined\n): PlannedGroup[] {\n const planned: PlannedGroup[] = [];\n const first = groups[0]?.items[0];\n for (const group of groups) {\n if (group.boundary !== \"transactional\") {\n planned.push(group);\n continue;\n }\n let items: PreparedForwardEdge[] = [];\n let changes = UNCHANGED_CATALOG;\n const flush = () => {\n if (items.length > 0) planned.push({ boundary: group.boundary, items });\n items = [];\n changes = UNCHANGED_CATALOG;\n };\n const read = (chunks: readonly string[], since = UNCHANGED_CATALOG) =>\n splits\n ? catalogCommitBoundaries(chunks, since)\n : { boundaries: [], changes: UNCHANGED_CATALOG };\n for (const item of group.items) {\n const resumed = item === first ? resume : undefined;\n const operations = resumed?.operations ?? item.transition.operations;\n const sql = edgeSql(item, operations, resumed === undefined);\n const joined = read(sql.chunks, changes);\n if (resumed === undefined && joined.boundaries.length === 0) {\n items.push(item);\n changes = joined.changes;\n continue;\n }\n flush();\n const alone = read(sql.chunks);\n if (resumed === undefined && alone.boundaries.length === 0) {\n items = [item];\n changes = alone.changes;\n continue;\n }\n // A commit before an origin check or the first step divides nothing.\n const cuts = [\n ...new Set(\n alone.boundaries\n .map((position) =>\n Math.min(position - sql.before, sql.steps.length)\n )\n .filter((cut) => cut > 0)\n ),\n ];\n const ends = [0, ...cuts, sql.steps.length];\n planned.push({\n split: {\n attempt: forwardAttempt(graph, item, resumed?.attempt.attemptId),\n resumed: resumed !== undefined,\n completed: resumed?.completed ?? 0,\n parts: ends\n .slice(1)\n .map((end, index) => stepRange(operations, ends[index]!, end)),\n },\n });\n }\n flush();\n }\n return planned;\n}\n\n/**\n * One edge as successive committed parts (PlanetScale's Neki), each in its\n * own locked transaction: the first runs the origin checks and opens the\n * attempt (`started`), each records its steps (`step-confirmed`) in the\n * transaction they ran in, and the last runs the destination checks, proves\n * the destination, moves the marker and closes the attempt (`applied`).\n *\n * Between two parts the lock is let go, so each part first proves the marker\n * unmoved and the attempt as far as this command left it. A first part that\n * fails leaves nothing, recorded as one `failed` event, as an atomic group\n * does. A later failure leaves the attempt open at its last committed part,\n * the marker on the edge's origin: `status()` reports it unfinished, and the\n * next `apply()` resumes the remaining parts ({@link resumableAttempt}).\n */\nasync function applySplitEdge(\n pinned: import(\"../drivers/driver\").AnyDriver,\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n { attempt, resumed, completed, parts }: SplitEdge,\n current: MigrationMarkerV1 | null,\n nextPath: MarkerPathEdgeV1[],\n models: MigrationClient[\"$schema\"]\n): Promise<MigrationMarkerV1 | null> {\n const { item } = attempt;\n let confirmed = completed;\n let next = current;\n for (const [index, operations] of parts.entries()) {\n const opens = index === 0 && !resumed;\n const closes = index === parts.length - 1;\n const phase = { committing: false, committed: false };\n // Set once the part holds the lock as this command left it: a failure\n // before that is another command's doing, and records nothing.\n let admitted = false;\n try {\n await runProgram(\n pinned,\n command,\n {\n transactional: true,\n statements: stepStatements(item.blob, operations),\n phase,\n },\n async (producer) => {\n await assertLockedSinceDecision(\n pinned,\n producer,\n command,\n current,\n opens ? false : { attemptId: attempt.attemptId, steps: confirmed }\n );\n admitted = true;\n if (opens) {\n await assertAllChecks(\n producer,\n item.blob,\n item.transition.originChecks,\n command.namespace,\n \"Origin checks failed\"\n );\n await appendLedger(\n producer,\n command,\n attempt.event(\"started\", \"none\")\n );\n }\n await runForwardEdge(\n producer,\n command,\n graph,\n attempt,\n nextPath,\n models,\n false,\n undefined,\n { operations, origin: false, destination: closes }\n );\n if (!closes) return;\n next = await commitEdgeArrival(\n producer,\n command,\n graph,\n item,\n current,\n nextPath,\n attempt\n );\n }\n );\n } catch (failure) {\n if (phase.committed) throw failure;\n if (\n closes &&\n phase.committing &&\n (await commitLanded(pinned, command, [item], next, failure))\n ) {\n return next;\n }\n // Only a first part that rolled back left nothing open to resume: one\n // whose COMMIT failed did when its attempt is open, or unreadable.\n if (\n opens &&\n admitted &&\n !(\n phase.committing &&\n (await attemptOpened(pinned, command, attempt.attemptId))\n )\n ) {\n await recordFailedAttempt(pinned, command, { attempt }, failure);\n }\n throw failure;\n }\n confirmed += operations.reduce(\n (count, operation) => count + operation.steps.length,\n 0\n );\n }\n return next;\n}\n\n/**\n * Whether the attempt `attemptId` is open, read after its first part's\n * COMMIT failed: `true` too when the ledger cannot be read, so a `failed`\n * event never closes an attempt whose part may have committed.\n */\nfunction attemptOpened(\n pinned: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n attemptId: Sha256\n): Promise<boolean> {\n return readControlState(pinned, command, { ledger: \"open\" }).then(\n ({ ledger }) =>\n unfinishedAttempts(ledger).some((event) => event.attemptId === attemptId),\n () => true\n );\n}\n","/**\n * Log V1: read-only ledger event history.\n * Leaf module with zero authoring or push-planner dependencies.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { admitLiveMigrationCapability } from \"./admission\";\nimport { getRuntimeClientDriver, type MigrationClient } from \"./client-driver\";\nimport { readControlState, refusePartialControl } from \"./control\";\nimport { resolveCommandDriver } from \"./pinned-session\";\nimport type { LedgerEventV1 } from \"./v1-types\";\n\nexport async function logV1(\n client: MigrationClient\n): Promise<readonly LedgerEventV1[]> {\n const driver = getRuntimeClientDriver(client);\n admitLiveMigrationCapability(driver, \"read-only\", \"log()\");\n const command = await resolveCommandDriver(client.$driver, driver);\n const control = await readControlState(client.$driver, command);\n if (control.presence.kind !== \"present\") {\n refusePartialControl(control.presence);\n throw new MigrationError(\n \"log requires present control tables\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n return control.ledger;\n}\n","/**\n * Status V1: read-only migration state & pending-route check.\n * Leaf module so callers needing only `status` never pull `differ`, `serializer`,\n * `down`, `prune`, `baseline`, `reanchor`, or `resolve`.\n */\n\nimport { type InvalidIndex, readInvalidIndexes } from \"./catalog-runtime\";\nimport type { MigrationClient } from \"./client-driver\";\nimport { unfinishedAttempts } from \"./control\";\nimport { loadMigrationGraph, selectRoute } from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport { resolveCommandDriver } from \"./pinned-session\";\nimport { managedAt, markerStanding } from \"./proof\";\nimport { openCommand, readCommandControl } from \"./resume\";\nimport type { MigrationStorageReader } from \"./storage/contract\";\nimport type { LedgerEventV1, MigrationMarkerV1 } from \"./v1-types\";\n\nexport interface StatusV1Result {\n readonly control: \"absent\" | \"present\";\n readonly marker: MigrationMarkerV1 | null;\n readonly pending: readonly Sha256[];\n readonly unfinished: boolean;\n /**\n * Present only when the marker names a state this estate does not hold:\n * `\"ahead\"` when its arrival path leaves this history after a state it holds\n * (newer code migrated the database), `\"unknown\"` when nothing on that path\n * belongs here. `pending` is then empty.\n */\n readonly markerState?: \"ahead\" | \"unknown\";\n /** Present only when a managed table carries an INVALID index (PostgreSQL). */\n readonly invalidIndexes?: readonly InvalidIndex[];\n /**\n * The latest `failed` ledger event, present once a rolled-back attempt left\n * one: its `toState`, `dispatchId` and `failure` say what failed and why.\n */\n readonly lastFailure?: LedgerEventV1;\n}\n\nexport async function statusV1(\n client: MigrationClient,\n storage: MigrationStorageReader\n): Promise<StatusV1Result> {\n const graph = await loadMigrationGraph(storage);\n const driver = openCommand(client, graph, \"read-only\", \"status()\");\n const command = await resolveCommandDriver(client.$driver, driver);\n const control = await readCommandControl(client.$driver, command);\n const marked = control.marker?.stateId ?? null;\n const invalidIndexes = await readInvalidIndexes(\n client.$driver,\n marked === null || graph.states.has(marked)\n ? managedAt(command, graph, marked)\n : command\n );\n const listed = invalidIndexes.length === 0 ? {} : { invalidIndexes };\n if (control.presence.kind !== \"present\") {\n return {\n control: \"absent\",\n marker: null,\n pending: [...graph.roots],\n unfinished: false,\n ...listed,\n };\n }\n const { marker, ledger } = control;\n const unfinished = unfinishedAttempts(ledger).length > 0;\n let lastFailure: LedgerEventV1 | undefined;\n for (const event of ledger) {\n if (event.kind === \"failed\") lastFailure = event;\n }\n const standing = markerStanding(graph, marker);\n let pending: Sha256[] = [];\n if (standing === \"known\" && graph.leaves.length === 1) {\n const leaf = graph.leaves[0]!;\n if ((marker?.stateId ?? null) !== leaf) {\n pending = [...selectRoute(graph, marker?.stateId ?? null, leaf)];\n }\n }\n return {\n control: \"present\",\n marker,\n pending,\n unfinished,\n ...(standing === \"known\" ? {} : { markerState: standing }),\n ...listed,\n ...(lastFailure ? { lastFailure } : {}),\n };\n}\n","/**\n * Verify V1: locked live-schema verification against the marked estate state.\n * Leaf module so runtime callers never pull offline authoring or rollback code.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { MigrationClient } from \"./client-driver\";\nimport { loadMigrationGraph, requireStateSnapshot } from \"./graph\";\nimport { withLockedMigrationProducer } from \"./pinned-session\";\nimport { assertNoDrift, managedAt, markerStanding } from \"./proof\";\nimport { openCommand, readCommandControl } from \"./resume\";\nimport type { MigrationStorageReader } from \"./storage/contract\";\n\nexport interface VerifyV1Result {\n readonly ok: boolean;\n /** Present, with `ok: false`, when the marker names a state this estate does not hold. */\n readonly markerState?: \"ahead\" | \"unknown\";\n}\n\nexport async function verifyV1(\n client: MigrationClient,\n storage: MigrationStorageReader\n): Promise<VerifyV1Result> {\n const graph = await loadMigrationGraph(storage);\n const driver = openCommand(client, graph, \"effectful\", \"verify()\");\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const control = await readCommandControl(pinned, command);\n if (control.presence.kind !== \"present\") {\n throw new MigrationError(\n \"verify requires present control tables\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const { marker } = control;\n if (!marker) {\n throw new MigrationError(\n \"verify requires a migration marker\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const standing = markerStanding(graph, marker);\n if (standing !== \"known\") return { ok: false, markerState: standing };\n const markedSnapshot = requireStateSnapshot(graph, marker.stateId);\n await command.preflightSchemaRequirements(\n [markedSnapshot],\n (sql, params) => pinned._executeRaw(sql, params),\n []\n );\n await assertNoDrift(\n pinned,\n managedAt(command, graph, marker.stateId),\n graph,\n marker\n );\n return { ok: true };\n }\n );\n}\n","/**\n * Semantic migration storage. Path-level get/put/delete is gone.\n *\n * Readers return raw bytes. Parsers, not drivers, turn those bytes into\n * trusted domain values. Writers promise strongly consistent listing and\n * conditional create.\n */\n\nimport type { Sha256 } from \"../identity\";\n\nexport interface PublishResult {\n readonly outcome: \"created\" | \"identical\";\n}\n\nexport interface MigrationStorageReader {\n readEstate(): Promise<Uint8Array | null>;\n listStates(): Promise<readonly Sha256[]>;\n listSnapshots(): Promise<readonly Sha256[]>;\n listSql(): Promise<readonly Sha256[]>;\n readState(id: Sha256): Promise<Uint8Array | null>;\n readSnapshot(hash: Sha256): Promise<Uint8Array | null>;\n readSql(hash: Sha256): Promise<Uint8Array | null>;\n}\n\nexport interface MigrationStorageWriter extends MigrationStorageReader {\n publishEstate(bytes: Uint8Array): Promise<PublishResult>;\n publishSnapshot(hash: Sha256, bytes: Uint8Array): Promise<PublishResult>;\n publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult>;\n publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult>;\n}\n\nconst READER_METHODS = [\n \"readEstate\",\n \"listStates\",\n \"listSnapshots\",\n \"listSql\",\n \"readState\",\n \"readSnapshot\",\n \"readSql\",\n] as const;\n\nconst WRITER_METHODS = [\n \"publishEstate\",\n \"publishSnapshot\",\n \"publishSql\",\n \"publishState\",\n] as const;\n\nexport function isMigrationStorageReader(\n value: unknown\n): value is MigrationStorageReader {\n return hasStorageMethods(value, READER_METHODS);\n}\n\nexport function isMigrationStorageWriter(\n value: MigrationStorageReader\n): value is MigrationStorageWriter {\n return hasStorageMethods(value, WRITER_METHODS);\n}\n\nfunction hasStorageMethods(\n value: unknown,\n methods: readonly string[]\n): boolean {\n if (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n ) {\n return false;\n }\n return methods.every(\n (method) => typeof Reflect.get(value, method) === \"function\"\n );\n}\n"],"mappings":"u2BAMA,SAAgB,GAAuC,CACrD,MAAO,CAAE,OAAQ,EAAE,CAAE,MAAO,EAAE,CAAE,CCgBlC,MAEM,GAAa,EAAG,+CAA+C,CAC/D,GAAc,EAAG,UAAU,CAC3B,GAAW,EAAG,gBAAgB,CAqCpC,SAAgB,GACd,EACA,EACwB,CACxB,IAAM,EAAQ,EAAe,EAAO,aAAa,EAAK,OAAO,CAC7D,OAAO,EAAS,EAAM,EAAI,WAAY,EAClC,CAAE,KAAM,QAAS,MAAO,GAAW,EAAO,EAAO,EAAK,CAAE,CACxD,CAAE,KAAM,OAAQ,SAAU,EAAsB,EAAO,EAAK,CAAE,CAGpE,SAAS,GACP,EACA,EACkB,CAClB,IAAM,EAAU,IAAW,oBAEzB,CAAC,EAAS,EAAM,EACf,EAAM,KAAO,OACZ,EAAM,KAAO,UACb,EAAE,GAAW,EAAM,KAAO,YAE5B,EAAO,4BAA4B,CACrC,IAAM,EAAS,GACb,EACA,EAA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aACA,eACD,CAED,SAAgB,GACd,EACiC,CACjC,OAAO,GAAkB,EAAO,GAAe,CAGjD,SAAgB,GACd,EACiC,CACjC,OAAO,GAAkB,EAAO,GAAe,CAGjD,SAAS,GACP,EACA,EACS,CAOT,OALE,IAAU,MACT,OAAO,GAAU,UAAY,OAAO,GAAU,WAExC,GAEF,EAAQ,MACZ,GAAW,OAAO,QAAQ,IAAI,EAAO,EAAO,EAAK,WACnD"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{r as e,t}from"./transaction-operation-CaWzo7gE.mjs";import{N as n,i as r,t as i,y as a}from"./error-mapping-B9rSvgG9.mjs";import{S as o,a as s,b as c,t as l}from"./base-17NSFtrA.mjs";import{c as u,d,l as f,o as p,p as m,s as h,u as g,y as ee}from"./validation-ATmgN5RE.mjs";import{n as _,t as v}from"./transaction-Bv5nyp-U.mjs";import{s as y,t as b}from"./normalized-result-D7nVkF36.mjs";import{r as x}from"./routed-operations-CcKOdn51.mjs";function S(e,t,n){if(e.kind===`foreignKey`)return new a(e.message,{meta:{model:t,operation:n}});if(e.kind===`nestedWrite`){let t=new f(e.message,e.relation??``);return e.lg&&(t.meta.lg=!0),t}if(e.kind===`notFound`)return new g(t,n);if(e.kind===`forbidden`)return new p(t,n,e.reason===void 0?void 0:{reason:e.reason});let r=new _(e.message,{meta:{model:t,operation:n}});return e.lg&&(r.meta.lg=!0),r}async function C(e,t,n,r=[]){if(!(e instanceof u))return e;let a=e.meta.statementIndex;if(typeof a==`number`){let n=t.find(e=>e.gd===a);return n?S(n.failure,n.model,n.operation):e}if(t.length>0&&i(r,n.dialect,new Set(t.map(e=>e.gd))))return e;for(let e of t){let t=(await n._execute(e.mv,r[e.gd]?.context)).rows.length>0;if(e.pz===`exists`?!t:t)return S(e.failure,e.model,e.operation)}let[o]=t;return o?t.every(e=>w(e,o))?S(o.failure,o.model,o.operation):e:new f(h,``,{code:`V7006`,cause:e})}function w(e,t){return e.model===t.model&&e.operation===t.operation&&e.failure.kind===t.failure.kind&&e.failure.message===t.failure.message&&e.failure.relation===t.failure.relation&&e.failure.reason===t.failure.reason&&e.failure.lg===t.failure.lg}function te(t,n,r,i){let a,o;try{let e=t.length;if(!Number.isInteger(e)||e<0||e>4294967295)throw new v;let n=Array(e);for(let r=0;r<e;r+=1)n[r]=t[r];a=n}catch(e){o=e}let s=t=>{if(a===void 0)throw o;if(le(a,n),a.length===0)return Promise.resolve(a);if(t===void 0)for(let t of[`input`,`plan`])for(let n of a)e(n).mz(n,t);return ne(a,n,r,i,t)},c=n.el?.rq;if(c===void 0)return T(a,n,s);let l={};return T(a,n,()=>c.run({kind:`batch`,operation:`$transaction([...])`,context:i,certainty:()=>l.certainty},()=>s(l)))}function T(t,n,r){let i=n.el;if(i?.fields===void 0&&i?.watch===void 0)return r();let a=[...t??[]];return r().then(async t=>{let n=[];for(let[r,i]of a.entries()){let a=e(i);try{a.hg&&(t[r]=await a.hg(i,t[r]))}catch(e){n.push(e)}}if(n.length===1)throw n[0];if(n.length>1)throw AggregateError(n,`Array members failed after commit.`,{cause:n[0]});return t})}function ne(e,t,n,r,i){let{driver:a}=t,o=!a.supportsTransactions&&a.supportsBatch;o||se(a);let s=t.el,c=s?.dh;return c&&(s?.rq?o||c.oz:c.qv?.(e))?re(e,t,n,r,i,c,o):o?D(e,a,n,r):E(e,t,n,r,i)}async function re(t,n,r,i,a,o,s){let{driver:c}=n,l=$(n,a??{}),u=t.map(t=>({operation:t,owner:e(t),child:N()})),d=await n.el?.rq?.members(u.map(e=>[{...e.owner.unit(e.operation),certainty:()=>e.certainty},()=>e.child.promise.then(O,O).then(()=>k(e))]));try{for(let e of u)e.owner.pp(e.operation,c);for(let e of[`input`,`plan`])for(let t of u)await t.owner.ow(t.operation,c,()=>t.owner.mz(t.operation,e))}catch(e){for(let t of u)t.child.reject(e);throw e}let f=await o.oz?.(u,l);if(f!==void 0)throw j(f[0],f.slice(1));let p;try{p=await(s?D(t,c,r,i,u,l,a):E(t,n,r,i,a,u,l))}catch(e){for(let t of u)t.child.reject(e);throw e}return await d?.done,p}function E(t,n,r,i,a,o,s){let c=t;return Q(n,r,i,async n=>{for(let r=0;r<t.length;r+=1){let i=t[r],a=o?.[r];if(a===void 0){c[r]=await e(i).fh(i,n);continue}a.owner.jm(i,n,a.notifications).then(a.child.resolve,a.child.reject);try{c[r]=await k(a)}catch(e){await A(o.slice(r+1),[e])}}return c},s,a)}async function D(t,n,r,i,a,o,s){if(a===void 0)for(let r of t)e(r).pp(r,n);let c,l=[],u=async e=>{if(!c){c=e,s&&(s.certainty=e);for(let t of a){t.certainty=e;try{await t.notifications?.[e===`committed`?`committed`:`mayHaveCommitted`]()}catch(e){l.push(e)}}try{await o?.outcomes?.publish(e)}catch(e){l.push(e)}}},d=async(e,t)=>{if(a===void 0)return e;t&&await u(`may-have-committed`),await A(a,[c?M(e,c):e],l)},f,p,m;try{({queries:f,s7:p,parsers:m}=await ie(t,n))}catch(e){throw await d(e)}let h;try{h=await ae(n,f,p,r,i,a&&n.supportsOrderedCommittedSegments?()=>u(`committed`):void 0),a&&await u(`committed`),oe(n,h,f.length)}catch(e){throw await d(e,!0)}let g=t;for(let e=0;e<m.length;e+=1){let t=a?.[e];if(t===void 0)g[e]=await m[e](h);else try{t.child.resolve(await m[e](h))}catch(e){t.child.reject(M(e,`committed`))}}return a&&await A(a,[],l.map(e=>M(e,`committed`)),g),g}const O=()=>void 0;function k(e){return e.query??e.child.promise}async function A(e,t,n=[],r=[]){for(let n of e)n.child.reject(t[0]);for(let[n,i]of(await Promise.allSettled(e.map(k))).entries())i.status===`fulfilled`?r[n]=i.value:t.push(i.reason);if(t.push(...n),t.length>0)throw j(t[0],t.slice(1))}function j(e,t){let n=t.filter(t=>t!==e);return n.length===0?e:AggregateError([e,...n],`Array transaction and post-work failed.`,{cause:e})}function M(e,t){return s(e)?r(e,t):e}function N(){let e,t,n=new Promise((n,r)=>{e=n,t=r});return n.catch(O),{promise:n,resolve:e,reject:t}}async function ie(t,n){let r=[],i=[],a=[];for(let o of t){let t=e(o),s=await t.ow(o,n,async()=>{let e=t.prepare(o,n);return e?{prepared:e}:{bm:await t.prepareBatch(o)}}),c=r.length;if(s.prepared){r.push(s.prepared),a.push(e=>t.ow(o,n,()=>{let r=e[c];if(!r)throw P(n,`omitted result for "${t.operation(o)}"`,{operation:t.operation(o)});return t.parseResult(o,r)}));continue}let{bm:l}=s;if(!l)throw ce(n);let u=l.queries.length;for(let e of l.queries)r.push(e);for(let e of l.s7??[])i.push({...e,gd:c+e.gd});a.push(e=>t.ow(o,n,()=>l.parseResult(e.slice(c,c+u))))}return{queries:r,s7:i,parsers:a}}async function ae(e,t,n,r,i,a){try{return await e._executeBatch(t,r,i,a)}catch(r){throw await C(r,n,e,t)}}function oe(e,t,n){b(t,n,{provider:e.driverName,operation:`$transaction([...])`})}function se(e){if(!(e.supportsTransactions||e.supportsBatch))throw P(e,`lacks transactions and atomic batch`)}function ce(e){return P(e,`cannot batch atomically without transactions`)}function P(e,t,n={method:`$transaction([...])`}){return new _(`Driver "${e.driverName}" ${t}.`,{meta:{driver:e.driverName,...n}})}function le(e,n){for(let r of e){if(typeof r!=`object`||!r)throw new v;let e=t(r);if(e===void 0)throw new v;if(e.clientId(r)!==n.clientId)throw d.clientMismatch(e.model(r),e.operation(r));if(e.gx(r)!==n.gx)throw d.scopeMismatch(e.model(r),e.operation(r))}}const F=Symbol(`viborm.call`),I=Symbol(`viborm.scope`),L=Symbol(`viborm.attempt`),R=e=>typeof e==`object`&&!!e,z=e=>typeof e==`object`&&!!e&&`engine`in e;function B(e){let t=Reflect.get(e,F);return R(t)?t:void 0}function V(e){return Reflect.get(e,L)}function H(e){let t=Reflect.get(e,I);return z(t)?t:void 0}function U(e){return B(e)?.of?.engine??H(e)?.engine}const W=`called run() after its second moment returned`;function G(e,t,n,r,i,a,o){return e!==void 0||o?r||o?K(e,t,n,r,i,a,o,q):q(e,t,e=>n(void 0,e),a?.hm,a?.ml):n()}function K(e,t,n,r,i,a,o,s){let c=o?[o]:e?.call?.m8,l=c?.[0]?.tell?.(c,i),u=!1,d,f=e=>async()=>{u=!0,i||(d=e),await l?.(e)},p={committed:f(`committed`),mayHaveCommitted:f(`may-have-committed`)},m=async e=>{let t=await n(p,e);return r&&!u&&await p.committed(),t};return s&&e&&t?.length?s(e,t,m,()=>d??a?.hm?.(),a?.ml):m()}function q(e,t,n,r,i){let a=(o,s)=>{let c=t?.[o];return c===void 0?n(s):ue(e,c,e=>a(o+1,e??s),r,i,()=>n(s))};return a(0)}async function ue(e,t,n,r,i,a){let{extension:o}=t,s=e.mode===`direct`,c=s&&e.kind===`model`&&x(e.operation),l=c,u,d,f=t=>(d===void 0&&(d=J(o,e,t),i?.(d)),d),p={open:!0,failed:!1,done:!1,direct:s,c3:c,certainty:r,start(e){if(!p.open)throw f(`called run() more than once`);if(p.done)throw f(W);return p.open=!1,p.failed=!1,u=(async()=>n(e))(),u.then(void 0,()=>{p.failed=!0}),u}},m=Object.defineProperties(()=>{if(!p.done)return p.start();if(!l)throw f(W);return l=!1,(async()=>a())()},{input:{get:()=>e.input},mode:{value:e.mode},[F]:{value:e.kind===`model`?e.call:void 0},[L]:{value:p}}),h;try{h={value:await t.handler(e,m)}}catch(e){h={reason:e}}p.done=!0;let g=`reason`in h&&(d===void 0||h.reason!==d)?de(o,e,h.reason,r?.()):void 0;if(u===void 0){if(g!==void 0)throw g;if(e.mode===`array`||e.kind!==`model`||!x(e.operation))throw J(o,e,`returned without run()`)}else g!==void 0&&!p.failed&&i?.(g),await u;if(`value`in h&&d===void 0)return h.value;throw d??g}function de(e,t,n,r){return o(n)?n:J(e,t,`failed`,c(n),r)}function J(e,t,n,r,i){return new m(`Extension "${e}" around() for ${t.kind===`model`?`${t.model}.${t.operation}`:t.operation} ${n}.`,{...r&&{cause:r},meta:{method:`around`,model:t.model,operation:t.operation,...i===void 0?{}:{commitCertainty:i}}})}var fe=class{zd=[];publish(e){return X(this.zd.filter(e=>e.ok),{certainty:e})}async end({parent:e,root:t},n,i){if(!i)return e?Y(e).zd.push(...this.zd.filter(e=>e.ok)):await this.publish(`committed`),n;let{certainty:a}=t;if(e||a===void 0)throw n;let o=s(n)?r(n,a):n;try{await this.publish(a)}catch(e){throw ee(o,e)}throw o}};function Y(e){return e.outcomes??=new fe,e.outcomes}function pe(e,t){if(t===void 0)return t=>X(e,{certainty:t});for(let n of e)(n.collect?.(t)??t.outcomes)?.zd.push(n);return async()=>{for(let t of e)t.ok=!0}}async function X(e,t){let n;for(let{extension:r,listener:i}of e)try{await i(t)}catch(e){n??=e instanceof l?e:new m(`Extension "${r}" settled() failed (${t.certainty}).`,{cause:c(e),meta:{method:`settled`,commitCertainty:t.certainty}})}if(n)throw n}function Z(t){return t.some(t=>{let{cq:n,registration:r}=e(t).around(t);return n?.length||r})}async function me(e,t){for(let n of e){let{write:e,registration:r}=n.owner.around(n.operation);if(r===void 0)continue;let i=K(void 0,void 0,e=>(n.notifications=e,n.child.promise),e,t,void 0,r);n.query=i,i.catch(he)}}const he=()=>void 0;function ge(e,t,n){let r=e.map(e=>e.owner.around(e.operation));return _e(e,(i,a,o)=>{let{context:s,cq:c,write:l,registration:u}=r[e.indexOf(i)];return c?.length||u?n(s,c,a,l,t,o,u):a()})}async function _e(e,t){let n,r=e.length,i=N();r===0&&i.resolve();for(let a of e){let e=e=>{let t=a.admissionFailures??=[];t.includes(e)||t.push(e),n??={failure:e},i.reject(e)},o;try{o=t(a,e=>(a.notifications=e,--r,r===0&&i.resolve(),a.child.promise),{ml:e,hm:()=>a.certainty})}catch(t){e(t),o=Promise.reject(t)}a.query=o,o.catch(e)}try{if(await i.promise,await Promise.resolve(),n)throw n.failure;return}catch(t){for(let n of e)n.child.reject(t);await Promise.allSettled(e.map(k));let n=[];for(let t of e)for(let e of t.admissionFailures??[])n.includes(e)||n.push(e);return n}}const ve={rank:-1},ye={rank:1,cw:K,qv:Z,oz:me},be={rank:2,cw:G,qv:Z,oz:(e,t)=>ge(e,t,G)};function xe(e,t,n){n&&(e.collect=n),(e.dh===void 0||t.rank>e.dh.rank)&&(e.dh=t)}function Q(e,t,r,i,a,o=a?.root??{}){let s=e.el,c=e.transaction,l,u=e=>t=>{if(e||c||(o.certainty=`committed`),!l?.outcomes){if(e)throw t;return t}let n=l.outcomes.end(l,t,e);return n.catch(()=>void 0),n},d=e.driver.withTransaction(t=>(l=a??$(e,o),i(t,l)),t,c||!(s?.dh||s?.methods)?r:n(r,{oq:()=>{o.certainty=`may-have-committed`},committed:()=>{o.certainty=`committed`}}));return c?y(d,u()):d.then(u(),u(!0))}function $(e,t){let n={parent:e.transaction,root:t};return e.el?.collect?.(n),n}export{Q as a,pe as c,V as d,B as f,S as g,te as h,xe as i,F as l,H as m,be as n,Y as o,U as p,ve as r,X as s,ye as t,I as u};
|
|
1
|
+
import{r as e,t}from"./transaction-operation-CaWzo7gE.mjs";import{N as n,i as r,t as i,y as a}from"./error-mapping-B9rSvgG9.mjs";import{S as o,a as s,b as c,t as l}from"./base-17NSFtrA.mjs";import{c as u,d,l as f,o as p,p as m,s as h,u as g,y as ee}from"./validation-ATmgN5RE.mjs";import{n as _,t as v}from"./transaction-Bv5nyp-U.mjs";import{s as y,t as b}from"./normalized-result-D7nVkF36.mjs";import{r as x}from"./routed-operations-CcKOdn51.mjs";function S(e,t,n){if(e.kind===`foreignKey`)return new a(e.message,{meta:{model:t,operation:n}});if(e.kind===`nestedWrite`){let t=new f(e.message,e.relation??``);return e.lj&&(t.meta.lj=!0),t}if(e.kind===`notFound`)return new g(t,n);if(e.kind===`forbidden`)return new p(t,n,e.reason===void 0?void 0:{reason:e.reason});let r=new _(e.message,{meta:{model:t,operation:n}});return e.lj&&(r.meta.lj=!0),r}async function C(e,t,n,r=[]){if(!(e instanceof u))return e;let a=e.meta.statementIndex;if(typeof a==`number`){let n=t.find(e=>e.gy===a);return n?S(n.failure,n.model,n.operation):e}if(t.length>0&&i(r,n.dialect,new Set(t.map(e=>e.gy))))return e;for(let e of t){let t=(await n._execute(e.fc,r[e.gy]?.context)).rows.length>0;if(e.mg===`exists`?!t:t)return S(e.failure,e.model,e.operation)}let[o]=t;return o?t.every(e=>w(e,o))?S(o.failure,o.model,o.operation):e:new f(h,``,{code:`V7006`,cause:e})}function w(e,t){return e.model===t.model&&e.operation===t.operation&&e.failure.kind===t.failure.kind&&e.failure.message===t.failure.message&&e.failure.relation===t.failure.relation&&e.failure.reason===t.failure.reason&&e.failure.lj===t.failure.lj}function te(t,n,r,i){let a,o;try{let e=t.length;if(!Number.isInteger(e)||e<0||e>4294967295)throw new v;let n=Array(e);for(let r=0;r<e;r+=1)n[r]=t[r];a=n}catch(e){o=e}let s=t=>{if(a===void 0)throw o;if(le(a,n),a.length===0)return Promise.resolve(a);if(t===void 0)for(let t of[`input`,`plan`])for(let n of a)e(n).fq(n,t);return ne(a,n,r,i,t)},c=n.ed?.ss;if(c===void 0)return T(a,n,s);let l={};return T(a,n,()=>c.run({kind:`batch`,operation:`$transaction([...])`,context:i,certainty:()=>l.certainty},()=>s(l)))}function T(t,n,r){let i=n.ed;if(i?.fields===void 0&&i?.watch===void 0)return r();let a=[...t??[]];return r().then(async t=>{let n=[];for(let[r,i]of a.entries()){let a=e(i);try{a.gs&&(t[r]=await a.gs(i,t[r]))}catch(e){n.push(e)}}if(n.length===1)throw n[0];if(n.length>1)throw AggregateError(n,`Array members failed after commit.`,{cause:n[0]});return t})}function ne(e,t,n,r,i){let{driver:a}=t,o=!a.supportsTransactions&&a.supportsBatch;o||se(a);let s=t.ed,c=s?.ud;return c&&(s?.ss?o||c.lf:c.zp?.(e))?re(e,t,n,r,i,c,o):o?D(e,a,n,r):E(e,t,n,r,i)}async function re(t,n,r,i,a,o,s){let{driver:c}=n,l=$(n,a??{}),u=t.map(t=>({operation:t,owner:e(t),child:N()})),d=await n.ed?.ss?.members(u.map(e=>[{...e.owner.unit(e.operation),certainty:()=>e.certainty},()=>e.child.promise.then(O,O).then(()=>k(e))]));try{for(let e of u)e.owner.ml(e.operation,c);for(let e of[`input`,`plan`])for(let t of u)await t.owner.ll(t.operation,c,()=>t.owner.fq(t.operation,e))}catch(e){for(let t of u)t.child.reject(e);throw e}let f=await o.lf?.(u,l);if(f!==void 0)throw j(f[0],f.slice(1));let p;try{p=await(s?D(t,c,r,i,u,l,a):E(t,n,r,i,a,u,l))}catch(e){for(let t of u)t.child.reject(e);throw e}return await d?.done,p}function E(t,n,r,i,a,o,s){let c=t;return Q(n,r,i,async n=>{for(let r=0;r<t.length;r+=1){let i=t[r],a=o?.[r];if(a===void 0){c[r]=await e(i).hp(i,n);continue}a.owner.jz(i,n,a.notifications).then(a.child.resolve,a.child.reject);try{c[r]=await k(a)}catch(e){await A(o.slice(r+1),[e])}}return c},s,a)}async function D(t,n,r,i,a,o,s){if(a===void 0)for(let r of t)e(r).ml(r,n);let c,l=[],u=async e=>{if(!c){c=e,s&&(s.certainty=e);for(let t of a){t.certainty=e;try{await t.notifications?.[e===`committed`?`committed`:`mayHaveCommitted`]()}catch(e){l.push(e)}}try{await o?.outcomes?.publish(e)}catch(e){l.push(e)}}},d=async(e,t)=>{if(a===void 0)return e;t&&await u(`may-have-committed`),await A(a,[c?M(e,c):e],l)},f,p,m;try{({queries:f,a5:p,parsers:m}=await ie(t,n))}catch(e){throw await d(e)}let h;try{h=await ae(n,f,p,r,i,a&&n.supportsOrderedCommittedSegments?()=>u(`committed`):void 0),a&&await u(`committed`),oe(n,h,f.length)}catch(e){throw await d(e,!0)}let g=t;for(let e=0;e<m.length;e+=1){let t=a?.[e];if(t===void 0)g[e]=await m[e](h);else try{t.child.resolve(await m[e](h))}catch(e){t.child.reject(M(e,`committed`))}}return a&&await A(a,[],l.map(e=>M(e,`committed`)),g),g}const O=()=>void 0;function k(e){return e.query??e.child.promise}async function A(e,t,n=[],r=[]){for(let n of e)n.child.reject(t[0]);for(let[n,i]of(await Promise.allSettled(e.map(k))).entries())i.status===`fulfilled`?r[n]=i.value:t.push(i.reason);if(t.push(...n),t.length>0)throw j(t[0],t.slice(1))}function j(e,t){let n=t.filter(t=>t!==e);return n.length===0?e:AggregateError([e,...n],`Array transaction and post-work failed.`,{cause:e})}function M(e,t){return s(e)?r(e,t):e}function N(){let e,t,n=new Promise((n,r)=>{e=n,t=r});return n.catch(O),{promise:n,resolve:e,reject:t}}async function ie(t,n){let r=[],i=[],a=[];for(let o of t){let t=e(o),s=await t.ll(o,n,async()=>{let e=t.prepare(o,n);return e?{prepared:e}:{bz:await t.prepareBatch(o)}}),c=r.length;if(s.prepared){r.push(s.prepared),a.push(e=>t.ll(o,n,()=>{let r=e[c];if(!r)throw P(n,`omitted result for "${t.operation(o)}"`,{operation:t.operation(o)});return t.parseResult(o,r)}));continue}let{bz:l}=s;if(!l)throw ce(n);let u=l.queries.length;for(let e of l.queries)r.push(e);for(let e of l.a5??[])i.push({...e,gy:c+e.gy});a.push(e=>t.ll(o,n,()=>l.parseResult(e.slice(c,c+u))))}return{queries:r,a5:i,parsers:a}}async function ae(e,t,n,r,i,a){try{return await e._executeBatch(t,r,i,a)}catch(r){throw await C(r,n,e,t)}}function oe(e,t,n){b(t,n,{provider:e.driverName,operation:`$transaction([...])`})}function se(e){if(!(e.supportsTransactions||e.supportsBatch))throw P(e,`lacks transactions and atomic batch`)}function ce(e){return P(e,`cannot batch atomically without transactions`)}function P(e,t,n={method:`$transaction([...])`}){return new _(`Driver "${e.driverName}" ${t}.`,{meta:{driver:e.driverName,...n}})}function le(e,n){for(let r of e){if(typeof r!=`object`||!r)throw new v;let e=t(r);if(e===void 0)throw new v;if(e.clientId(r)!==n.clientId)throw d.clientMismatch(e.model(r),e.operation(r));if(e.bf(r)!==n.bf)throw d.scopeMismatch(e.model(r),e.operation(r))}}const F=Symbol(`viborm.call`),I=Symbol(`viborm.scope`),L=Symbol(`viborm.attempt`),R=e=>typeof e==`object`&&!!e,z=e=>typeof e==`object`&&!!e&&`engine`in e;function B(e){let t=Reflect.get(e,F);return R(t)?t:void 0}function V(e){return Reflect.get(e,L)}function H(e){let t=Reflect.get(e,I);return z(t)?t:void 0}function U(e){return B(e)?.of?.engine??H(e)?.engine}const W=`called run() after its second moment returned`;function G(e,t,n,r,i,a,o){return e!==void 0||o?r||o?K(e,t,n,r,i,a,o,q):q(e,t,e=>n(void 0,e),a?.hz,a?.mv):n()}function K(e,t,n,r,i,a,o,s){let c=o?[o]:e?.call?.g1,l=c?.[0]?.tell?.(c,i),u=!1,d,f=e=>async()=>{u=!0,i||(d=e),await l?.(e)},p={committed:f(`committed`),mayHaveCommitted:f(`may-have-committed`)},m=async e=>{let t=await n(p,e);return r&&!u&&await p.committed(),t};return s&&e&&t?.length?s(e,t,m,()=>d??a?.hz?.(),a?.mv):m()}function q(e,t,n,r,i){let a=(o,s)=>{let c=t?.[o];return c===void 0?n(s):ue(e,c,e=>a(o+1,e??s),r,i,()=>n(s))};return a(0)}async function ue(e,t,n,r,i,a){let{extension:o}=t,s=e.mode===`direct`,c=s&&e.kind===`model`&&x(e.operation),l=c,u,d,f=t=>(d===void 0&&(d=J(o,e,t),i?.(d)),d),p={open:!0,failed:!1,done:!1,direct:s,u1:c,certainty:r,start(e){if(!p.open)throw f(`called run() more than once`);if(p.done)throw f(W);return p.open=!1,p.failed=!1,u=(async()=>n(e))(),u.then(void 0,()=>{p.failed=!0}),u}},m=Object.defineProperties(()=>{if(!p.done)return p.start();if(!l)throw f(W);return l=!1,(async()=>a())()},{input:{get:()=>e.input},mode:{value:e.mode},[F]:{value:e.kind===`model`?e.call:void 0},[L]:{value:p}}),h;try{h={value:await t.handler(e,m)}}catch(e){h={reason:e}}p.done=!0;let g=`reason`in h&&(d===void 0||h.reason!==d)?de(o,e,h.reason,r?.()):void 0;if(u===void 0){if(g!==void 0)throw g;if(e.mode===`array`||e.kind!==`model`||!x(e.operation))throw J(o,e,`returned without run()`)}else g!==void 0&&!p.failed&&i?.(g),await u;if(`value`in h&&d===void 0)return h.value;throw d??g}function de(e,t,n,r){return o(n)?n:J(e,t,`failed`,c(n),r)}function J(e,t,n,r,i){return new m(`Extension "${e}" around() for ${t.kind===`model`?`${t.model}.${t.operation}`:t.operation} ${n}.`,{...r&&{cause:r},meta:{method:`around`,model:t.model,operation:t.operation,...i===void 0?{}:{commitCertainty:i}}})}var fe=class{zz=[];publish(e){return X(this.zz.filter(e=>e.ok),{certainty:e})}async end({parent:e,root:t},n,i){if(!i)return e?Y(e).zz.push(...this.zz.filter(e=>e.ok)):await this.publish(`committed`),n;let{certainty:a}=t;if(e||a===void 0)throw n;let o=s(n)?r(n,a):n;try{await this.publish(a)}catch(e){throw ee(o,e)}throw o}};function Y(e){return e.outcomes??=new fe,e.outcomes}function pe(e,t){if(t===void 0)return t=>X(e,{certainty:t});for(let n of e)(n.collect?.(t)??t.outcomes)?.zz.push(n);return async()=>{for(let t of e)t.ok=!0}}async function X(e,t){let n;for(let{extension:r,listener:i}of e)try{await i(t)}catch(e){n??=e instanceof l?e:new m(`Extension "${r}" settled() failed (${t.certainty}).`,{cause:c(e),meta:{method:`settled`,commitCertainty:t.certainty}})}if(n)throw n}function Z(t){return t.some(t=>{let{dv:n,registration:r}=e(t).around(t);return n?.length||r})}async function me(e,t){for(let n of e){let{write:e,registration:r}=n.owner.around(n.operation);if(r===void 0)continue;let i=K(void 0,void 0,e=>(n.notifications=e,n.child.promise),e,t,void 0,r);n.query=i,i.catch(he)}}const he=()=>void 0;function ge(e,t,n){let r=e.map(e=>e.owner.around(e.operation));return _e(e,(i,a,o)=>{let{context:s,dv:c,write:l,registration:u}=r[e.indexOf(i)];return c?.length||u?n(s,c,a,l,t,o,u):a()})}async function _e(e,t){let n,r=e.length,i=N();r===0&&i.resolve();for(let a of e){let e=e=>{let t=a.admissionFailures??=[];t.includes(e)||t.push(e),n??={failure:e},i.reject(e)},o;try{o=t(a,e=>(a.notifications=e,--r,r===0&&i.resolve(),a.child.promise),{mv:e,hz:()=>a.certainty})}catch(t){e(t),o=Promise.reject(t)}a.query=o,o.catch(e)}try{if(await i.promise,await Promise.resolve(),n)throw n.failure;return}catch(t){for(let n of e)n.child.reject(t);await Promise.allSettled(e.map(k));let n=[];for(let t of e)for(let e of t.admissionFailures??[])n.includes(e)||n.push(e);return n}}const ve={rank:-1},ye={rank:1,dm:K,zp:Z,lf:me},be={rank:2,dm:G,zp:Z,lf:(e,t)=>ge(e,t,G)};function xe(e,t,n){n&&(e.collect=n),(e.ud===void 0||t.rank>e.ud.rank)&&(e.ud=t)}function Q(e,t,r,i,a,o=a?.root??{}){let s=e.ed,c=e.transaction,l,u=e=>t=>{if(e||c||(o.certainty=`committed`),!l?.outcomes){if(e)throw t;return t}let n=l.outcomes.end(l,t,e);return n.catch(()=>void 0),n},d=e.driver.withTransaction(t=>(l=a??$(e,o),i(t,l)),t,c||!(s?.ud||s?.methods)?r:n(r,{lu:()=>{o.certainty=`may-have-committed`},committed:()=>{o.certainty=`committed`}}));return c?y(d,u()):d.then(u(),u(!0))}function $(e,t){let n={parent:e.transaction,root:t};return e.ed?.collect?.(n),n}export{Q as a,pe as c,V as d,B as f,S as g,te as h,xe as i,F as l,H as m,be as n,Y as o,U as p,ve as r,X as s,ye as t,I as u};
|
|
2
2
|
//# sourceMappingURL=coordination-BxMskOgi.mjs.map
|
package/dist/d1.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $a as QueryExecutionContext, C as DriverResultParser, Di as LinkedClientConfig, Gr as Schema, Ja as TransactionOptionSupport, Xa as BatchQuery, Za as CommittedBatchNotification, b as SqliteMigrationCapability, eo as QueryResult, h as Driver, pt as VibORMClient, st as DriverConfig, t as DatabaseAdapter, ut as NoExtraDriverConfigKeys } from "./database-adapter-
|
|
1
|
+
import { $a as QueryExecutionContext, C as DriverResultParser, Di as LinkedClientConfig, Gr as Schema, Ja as TransactionOptionSupport, Xa as BatchQuery, Za as CommittedBatchNotification, b as SqliteMigrationCapability, eo as QueryResult, h as Driver, pt as VibORMClient, st as DriverConfig, t as DatabaseAdapter, ut as NoExtraDriverConfigKeys } from "./database-adapter-cW0nmWM6.mjs";
|
|
2
2
|
import { D1Database, D1DatabaseSession } from "@cloudflare/workers-types";
|
|
3
3
|
|
|
4
4
|
//#region src/drivers/d1/index.d.ts
|
package/dist/d1.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{h as e}from"./error-mapping-B9rSvgG9.mjs";import{p as t}from"./validation-ATmgN5RE.mjs";import{i as n,n as r}from"./normalized-result-D7nVkF36.mjs";import{t as i}from"./bind-parameter-capacity-BAFQM9Jt.mjs";import{f as a,n as o,u as s}from"./client-
|
|
1
|
+
import{h as e}from"./error-mapping-B9rSvgG9.mjs";import{p as t}from"./validation-ATmgN5RE.mjs";import{i as n,n as r}from"./normalized-result-D7nVkF36.mjs";import{t as i}from"./bind-parameter-capacity-BAFQM9Jt.mjs";import{f as a,n as o,u as s}from"./client-DkNRAOuH.mjs";import{r as c}from"./provider-parameter-snapshot-DnJ6Av9y.mjs";import{t as l}from"./sqlite-adapter-B7r7w3CS.mjs";import{f as u,h as d,r as f,t as p,u as m}from"./driver-PkP_1p80.mjs";import{l as h,o as g,r as _}from"./sqlite-utils-BAUMCrok.mjs";import{n as v,t as y}from"./sqlite-statement-classifier-CBmKy8Ta.mjs";const b={database:!0};function x(e){return _(e).map(e=>typeof e==`bigint`?e.toString():e)}const S=new Set(`aggregate count create createManyAndReturn delete deleteManyAndReturn exist findFirst findMany findUnique groupBy update updateManyAndReturn upsert`.split(` `));function C(e,n){let r=e.operation??`execute`;return new t(`Driver "d1" malformed payload for "${r}": ${n}.`,{meta:{driver:`d1`,...e,operation:r}})}function w(e,t){let r=n(e)?e.meta:void 0;if(!n(e)||e.success!==!0||e.results!==null&&!(Array.isArray(e.results)&&e.results.every(n))||!n(r)||!Number.isSafeInteger(r.changes)||r.changes<0||!Number.isInteger(r.last_row_id))throw C(t,`invalid results/meta`)}function T(e,t,n,r){let i=n.operation??`execute`;w(e,n);let a;if(e.results===null){if(r&&S.has(i)||y(t)!==`no-rows`)throw C(n,`null results`);a=[]}else a=e.results;let o=v(t)&&Number.isSafeInteger(e.meta.last_row_id)?e.meta.last_row_id:void 0;return{rows:a,rowCount:e.meta.changes===0?a.length:e.meta.changes,...o!==void 0&&o>0?{insertId:o}:{}}}function E(e){let{result:t}=e;return[e,t,t.parseField,t.parseRelation,t.parseResult]}const D=new WeakMap;function O(e){if(!(e instanceof j))return!1;let t=D.get(e);if(!t)return!1;let{adapter:n}=e,{result:r}=n;return Object.getPrototypeOf(e)===j.prototype&&e._execute===M&&e.execute===N&&e.executeTypedStatement===P&&e.result===h&&e.result.parseField===g&&e.result.parseRelation===void 0&&e.result.parseResult===void 0&&t[0]===n&&t[1]===r&&t[2]===r.parseField&&t[3]===r.parseRelation&&t[4]===r.parseResult}async function k(e,t,n,r){let i=x(n);return T(await e.prepare(t).bind(...i).run(),t,r,!0)}function A(e,t,n){return e.executeTypedStatement(t,n,async(t,n,i,a)=>{if(!O(e)){let o=await e.execute(t,n,i,a);return r(o,{provider:e.driverName,operation:a.operation??`execute`}),{kind:`borrowed`,result:o}}let o=x(i),c=await t.prepare(n).bind(...o).raw({columnNames:!0}),[l,...u]=Array.isArray(c)?c:[],d=l??[];if(!(Array.isArray(c)&&Array.isArray(d)&&d.every(e=>typeof e==`string`)))throw C(a,`malformed positional rows`);return s(u,d,{provider:e.driverName,operation:a.operation??`execute`}),{kind:`positional`,rows:u,columns:d}})}var j=class extends f{static get name(){return`D1Driver`}adapter=new l({temporaryObjects:!1,deepExpressions:!1,sharedRelationBodies:!0,compoundSelectTerms:5,relationsPerStatement:256,countsCascadedChanges:!0});maxBindParametersPerStatement=100;result=h;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;sqliteMigrationCapability=p;_o;constructor(e){super(`sqlite`,`d1`),this._o=e,this.client=e.database,D.set(this,E(this.adapter)),a(this,(e,t)=>A(this,e,t),O)}async initClient(){return this._o.database}async closeClient(e){}async execute(e,t,n,r){return k(e,t,n,r??{operation:`execute`})}async executeRaw(e,t,n,r){let a=n??[];return i({values:a},this.driverName,this.maxBindParametersPerStatement,`raw statement`),k(e,t,a,r??{operation:`executeRaw`})}transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`D1 batch has no configurable tx`,timeout:!1,timeoutReason:`D1 batch has no interactive body`,maxWait:`unsupported`,maxWaitReason:`D1 batch has no connection wait`}}transaction(t,n){return Promise.reject(e(this.driverName))}async executeBatch(e,t,n,r){let a=n??{operation:`executeBatch`},o=[];for(let n of t){let t=n.context??a;c(n)&&i({values:n.params??[]},this.driverName,this.maxBindParametersPerStatement,`raw statement`);try{let t=n.params?x(n.params):[];o.push(e.prepare(n.sql).bind(...t))}catch(e){throw u(this,e,n.sql,m(n),t,!0)}}let s=await e.batch(o);if(await r?.(),!Array.isArray(s)||s.length!==t.length){let e=Array.isArray(s)?s.length:0;throw C(a,`expected ${t.length} results, got ${e}`)}let l=[];for(let e=0;e<s.length;e+=1){let n=t[e];if(!n)throw C(a,`missing query ${e}`);l.push(T(s[e],n.sql,n.context??a,!1))}return l}};const M=j.prototype._execute,N=j.prototype.execute,P=j.prototype.executeTypedStatement;function F(e){d(e,`d1`,b);let{database:t}=e;return o(e,new j({database:t}))}export{j as D1Driver,F as createClient};
|
|
2
2
|
//# sourceMappingURL=d1.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as sqlTag, n as Sql } from "./sql-
|
|
1
|
+
import { c as sqlTag, n as Sql } from "./sql-C-SBCGCx.mjs";
|
|
2
2
|
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
3
3
|
|
|
4
4
|
//#region src/schema/scalars/native-types.d.ts
|
|
@@ -5065,7 +5065,7 @@ declare class DecimalScalar<out State$1 extends ScalarState<"decimal">> extends
|
|
|
5065
5065
|
* a schema document round-trips to the same declaration. A value outside the
|
|
5066
5066
|
* declared domain fails at the call that wrote it, not at the first write.
|
|
5067
5067
|
*/
|
|
5068
|
-
default<V$2 extends DefaultValueInput<State$1>>(value: V$2): DecimalScalar<Omit<DecimalScalarState<State$1>, "optional" | "
|
|
5068
|
+
default<V$2 extends DefaultValueInput<State$1>>(value: V$2): DecimalScalar<Omit<DecimalScalarState<State$1>, "optional" | "hasDefault" | "default"> & {
|
|
5069
5069
|
readonly hasDefault: true;
|
|
5070
5070
|
readonly default: unknown;
|
|
5071
5071
|
readonly optional: true;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as e,t}from"./value-guards-CBVIJXlI.mjs";import{a as n,i as r,r as i}from"./datetime-values-D_G6m5_o.mjs";const a=864e5,o=2440587.5;function s(e){return e.startsWith(`0000-`)?`0001${e.slice(4)} BC`:e}function c(n){if(e(n))return Number.isFinite(n)?n:void 0;if(t(n)){let e=Number(n);return Number.isSafeInteger(e)?e:void 0}}function l(e,t){if(t===`text`)return e;let n=Date.parse(e);return t===`epochMillis`?n:n/a+o}function u(e,t){let n=c(e);if(n===void 0)return;let i=t===`epochMillis`?n:Math.round((n-o)*a);if(r(i))return new Date(i)}const d=/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?(?::?(\d{2}))?)?(?: (BC))?$/;function f(e,t,n){let r=0;for(let i=t;i<t+n;i+=1){let t=e.charCodeAt(i)-48;if(t<0||t>9)return-1;r=r*10+t}return r}function p(e){let t=e.length;if(t<19)return!1;let a=e.charCodeAt(10);if(e.charCodeAt(4)!==45||e.charCodeAt(7)!==45||a!==84&&a!==32||e.charCodeAt(13)!==58||e.charCodeAt(16)!==58)return!1;let o=f(e,0,4),s=f(e,5,2),c=f(e,8,2),l=f(e,11,2),u=f(e,14,2),d=f(e,17,2);if(o<100||s<0||c<0||l<0||u<0||d<0)return!1;let p=19,m=0;if(p<t&&e.charCodeAt(p)===46){p+=1;let n=0;for(;p<t;){let t=e.charCodeAt(p)-48;if(t<0||t>9)break;n===0?m+=t*100:n===1?m+=t*10:n===2&&(m+=t),n+=1,p+=1}if(n===0||n>6)return!1}let h=0;if(p<t){let n=e.charCodeAt(p);if(n===90)p+=1;else if(n===43||n===45){if(p+=1,p+2>t)return!1;let r=f(e,p,2);if(r<0||r>23)return!1;p+=2;let i=0,a=0;if(p<t&&e.charCodeAt(p)!==32){if(e.charCodeAt(p)===58&&(p+=1),p+2>t||(i=f(e,p,2),i<0||i>59))return!1;if(p+=2,p<t&&e.charCodeAt(p)!==32){if(e.charCodeAt(p)===58&&(p+=1),p+2>t||(a=f(e,p,2),a<0||a>59))return!1;p+=2}}h=(n===45?-1:1)*(r*3600+i*60+a)*1e3}else return!1;if(p!==t)return!1}if(!(n(o,s,c)&&i(l,u,d)))return;let g=Date.UTC(o,s-1,c,l,u,d,m)-h;return r(g)?new Date(g):void 0}function m(e){let t=p(e);if(t!==!1)return t;let a=d.exec(e);if(!a)return;let o=e=>Number(a[e]??0),s=a[13]?1-o(1):o(1),c=o(2),l=o(3),u=o(4),f=o(5),m=o(6),h=o(10),g=o(11),_=o(12);if(!(n(s,c,l)&&i(u,f,m))||h>23||g>59||_>59)return;let v=new Date(0);v.setUTCFullYear(s,c-1,l),v.setUTCHours(u,f,m,Number((a[7]??``).padEnd(3,`0`).slice(0,3)));let y=(h*3600+g*60+_)*1e3,b=v.getTime()-(a[9]===`-`?-y:y);return r(b)?new Date(b):void 0}const h=e=>new Date(e).toISOString().slice(0,23).replace(`T`,` `);export{s as a,l as i,m as n,h as r,u as t};
|
|
2
|
+
//# sourceMappingURL=datetime-physical-codec-Ci0dyOot.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"datetime-physical-codec-Ci0dyOot.mjs","names":[],"sources":["../src/validation/primitives/datetime-physical-codec.ts"],"sourcesContent":["/**\n * The ONE physical datetime codec.\n *\n * A datetime's LOGICAL value is an instant, and every layer above this one\n * spells it as a validated ISO-8601 string or a `Date`. Its PHYSICAL value is\n * whatever the column it lands in actually holds, and SQLite makes that a\n * DECLARED choice with three answers: timestamp TEXT, an INTEGER count of epoch\n * milliseconds, or a REAL Julian day. This module owns the conversion between\n * the two, so value lowering and result decoding cannot disagree about what a\n * column holds.\n *\n * The form is declared and never inferred, because a physical value cannot name\n * its own vocabulary: `2460324.9375` is 2024-01-15T10:30:00Z as a Julian day and\n * an instant in 1970 as milliseconds, and `1705314600000` is that same instant\n * as milliseconds and a date no calendar reaches as a Julian day.\n */\n\nimport { isBigInt, isNumber } from \"../value-guards\";\nimport {\n isDateTimeClock,\n isDateTimeInstant,\n isGregorianCalendarDate,\n} from \"./datetime-values\";\n\n/**\n * The three physical spellings a datetime column can hold.\n *\n * `text` is the timestamp text every dialect stores by default, and its\n * conversion is the identity — the ISO string IS the physical value. The other\n * two are numbers, and each has an exact arithmetic.\n */\nexport type DateTimePhysicalForm = \"text\" | \"epochMillis\" | \"julianDay\";\n\n/**\n * The two forms whose physical value is a NUMBER rather than timestamp text.\n *\n * Named separately because the decode entry accepts only these: the textual\n * grammar a provider timestamp is held to belongs to the result boundary that\n * already owns it for every dialect, and duplicating it here would give one\n * spelling two readers.\n */\nexport type DateTimeNumericForm = Exclude<DateTimePhysicalForm, \"text\">;\n\nconst MILLISECONDS_PER_DAY = 86_400_000;\n\n/** The Julian day of 1970-01-01T00:00:00Z, where the Unix epoch begins. */\nconst UNIX_EPOCH_JULIAN_DAY = 2_440_587.5;\n\n/** PostgreSQL uses historical years: the admitted ISO year 0000 is 1 BC. */\nexport function encodePostgresTemporal(iso: string): string {\n return iso.startsWith(\"0000-\") ? `0001${iso.slice(4)} BC` : iso;\n}\n\n/**\n * The number a provider returned for a numeric datetime column, or `undefined`\n * when it returned something else.\n *\n * `bigint` is admitted because the SQLite family reads INTEGER columns in a\n * BigInt mode so values past 2^53 survive — an epoch-millisecond column is read\n * through that same mode. Every public DateTime instant is a safe integer, so a\n * bigint that does not survive the round trip is already outside the domain and\n * is refused here rather than rounded into it.\n */\nfunction physicalNumber(value: unknown): number | undefined {\n if (isNumber(value)) return Number.isFinite(value) ? value : undefined;\n if (isBigInt(value)) {\n // `Number(bigint)` is exact for every magnitude below 2^53, so the safe\n // test alone decides survival — an unsafe result is already outside the\n // public DateTime domain and there is no second case to check.\n const asNumber = Number(value);\n return Number.isSafeInteger(asNumber) ? asNumber : undefined;\n }\n return undefined;\n}\n\n/**\n * The physical value one VALIDATED ISO-8601 timestamp lands in a column as.\n *\n * The ISO boundary (`validateIsoTimestamp`) already owns \"this string names an\n * instant\", and every value lowered here has crossed it. REAL/Julian storage\n * needs no second admission branch: every millisecond in the four-digit public\n * DateTime domain survives its Julian-day double round trip. Behavior on any\n * other string is unspecified rather than re-guarded — one guard per invariant.\n */\nexport function encodePhysicalDateTime(\n iso: string,\n form: DateTimePhysicalForm\n): string | number {\n if (form === \"text\") return iso;\n const epochMilliseconds = Date.parse(iso);\n return form === \"epochMillis\"\n ? epochMilliseconds\n : epochMilliseconds / MILLISECONDS_PER_DAY + UNIX_EPOCH_JULIAN_DAY;\n}\n\n/**\n * The instant one physical number holds, or `undefined` when the provider\n * returned a value this column's declared form cannot hold.\n *\n * A Julian day is a COUNT OF DAYS in a double, so its resolution near the\n * present is about fifty microseconds and a millisecond is not exactly\n * representable in it. The instant is therefore rounded to the nearest\n * millisecond — the same precision the logical value has — and then held to the\n * public four-digit instant range, so a day number outside the DateTime domain\n * is a malformed row rather than an extended-year `Date`.\n */\nexport function decodePhysicalDateTime(\n value: unknown,\n form: DateTimeNumericForm\n): Date | undefined {\n const physical = physicalNumber(value);\n if (physical === undefined) return undefined;\n const epochMilliseconds =\n form === \"epochMillis\"\n ? physical\n : Math.round((physical - UNIX_EPOCH_JULIAN_DAY) * MILLISECONDS_PER_DAY);\n if (!isDateTimeInstant(epochMilliseconds)) return undefined;\n return new Date(epochMilliseconds);\n}\n\nconst TIMESTAMP_TEXT =\n /^(\\d{4})-(\\d{2})-(\\d{2})[T ](\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?(?:(Z)|([+-])(\\d{2})(?::?(\\d{2}))?(?::?(\\d{2}))?)?(?: (BC))?$/;\n\n/** The digits `value` holds at `[at, at + count)`, or -1 where one is not a digit. */\nfunction digitsAt(value: string, at: number, count: number): number {\n let parsed = 0;\n for (let index = at; index < at + count; index += 1) {\n const digit = value.charCodeAt(index) - 48;\n if (digit < 0 || digit > 9) return -1;\n parsed = parsed * 10 + digit;\n }\n return parsed;\n}\n\n/**\n * Standard provider timestamps (`YYYY-MM-DD[T ]HH:MM:SS[.ffffff][Z|[+-]HH[:MM[:SS]]]`)\n * read by character without regex or throwaway `Date` allocations: `false` for\n * `BC` eras, years below 100 (which `Date.UTC` would read as 19xx), or any\n * spelling outside this grammar. The general grammar reads both; the domain\n * rules are the same.\n */\nfunction decodeFastTimestamp(value: string): Date | undefined | false {\n const len = value.length;\n if (len < 19) return false;\n const sep = value.charCodeAt(10);\n if (\n value.charCodeAt(4) !== 45 || // -\n value.charCodeAt(7) !== 45 || // -\n (sep !== 84 && sep !== 32) || // T or space\n value.charCodeAt(13) !== 58 || // :\n value.charCodeAt(16) !== 58 // :\n )\n return false;\n const year = digitsAt(value, 0, 4);\n const month = digitsAt(value, 5, 2);\n const day = digitsAt(value, 8, 2);\n const hour = digitsAt(value, 11, 2);\n const minute = digitsAt(value, 14, 2);\n const second = digitsAt(value, 17, 2);\n if (\n year < 100 ||\n month < 0 ||\n day < 0 ||\n hour < 0 ||\n minute < 0 ||\n second < 0\n )\n return false;\n let pos = 19;\n let millisecond = 0;\n if (pos < len && value.charCodeAt(pos) === 46 /* . */) {\n pos += 1;\n let frac = 0;\n while (pos < len) {\n const digit = value.charCodeAt(pos) - 48;\n if (digit < 0 || digit > 9) break;\n if (frac === 0) millisecond += digit * 100;\n else if (frac === 1) millisecond += digit * 10;\n else if (frac === 2) millisecond += digit;\n frac += 1;\n pos += 1;\n }\n if (frac === 0 || frac > 6) return false;\n }\n let offsetMs = 0;\n if (pos < len) {\n const tz = value.charCodeAt(pos);\n if (tz === 90 /* Z */) {\n pos += 1;\n } else if (tz === 43 /* + */ || tz === 45 /* - */) {\n pos += 1;\n if (pos + 2 > len) return false;\n const offsetHour = digitsAt(value, pos, 2);\n if (offsetHour < 0 || offsetHour > 23) return false;\n pos += 2;\n let offsetMinute = 0;\n let offsetSecond = 0;\n if (pos < len && value.charCodeAt(pos) !== 32) {\n if (value.charCodeAt(pos) === 58 /* : */) pos += 1;\n if (pos + 2 > len) return false;\n offsetMinute = digitsAt(value, pos, 2);\n if (offsetMinute < 0 || offsetMinute > 59) return false;\n pos += 2;\n if (pos < len && value.charCodeAt(pos) !== 32) {\n if (value.charCodeAt(pos) === 58 /* : */) pos += 1;\n if (pos + 2 > len) return false;\n offsetSecond = digitsAt(value, pos, 2);\n if (offsetSecond < 0 || offsetSecond > 59) return false;\n pos += 2;\n }\n }\n offsetMs =\n (tz === 45 ? -1 : 1) *\n (offsetHour * 3600 + offsetMinute * 60 + offsetSecond) *\n 1000;\n } else {\n return false;\n }\n if (pos !== len) return false;\n }\n if (\n !(\n isGregorianCalendarDate(year, month, day) &&\n isDateTimeClock(hour, minute, second)\n )\n )\n return undefined;\n const epoch =\n Date.UTC(year, month - 1, day, hour, minute, second, millisecond) -\n offsetMs;\n return isDateTimeInstant(epoch) ? new Date(epoch) : undefined;\n}\n\n/** The provider timestamp grammar; the domain rules are the codec's. */\nexport function decodeProviderTimestamp(value: string): Date | undefined {\n const fast = decodeFastTimestamp(value);\n if (fast !== false) return fast;\n const match = TIMESTAMP_TEXT.exec(value);\n if (!match) return undefined;\n const num = (index: number) => Number(match[index] ?? 0);\n const year = match[13] ? 1 - num(1) : num(1);\n const month = num(2);\n const day = num(3);\n const hour = num(4);\n const minute = num(5);\n const second = num(6);\n const offsetHour = num(10);\n const offsetMinute = num(11);\n const offsetSecond = num(12);\n if (\n !(\n isGregorianCalendarDate(year, month, day) &&\n isDateTimeClock(hour, minute, second)\n ) ||\n offsetHour > 23 ||\n offsetMinute > 59 ||\n offsetSecond > 59\n )\n return undefined;\n const parsed = new Date(0);\n // setUTCFullYear keeps years 0..99 literal; Date.UTC reinterprets them as 1900..1999.\n parsed.setUTCFullYear(year, month - 1, day);\n parsed.setUTCHours(\n hour,\n minute,\n second,\n Number((match[7] ?? \"\").padEnd(3, \"0\").slice(0, 3))\n );\n const offset = (offsetHour * 3600 + offsetMinute * 60 + offsetSecond) * 1000;\n const epoch = parsed.getTime() - (match[9] === \"-\" ? -offset : offset);\n return isDateTimeInstant(epoch) ? new Date(epoch) : undefined;\n}\n\n/** MySQL DATETIME stores the admitted instant as a naive UTC wall clock. */\nexport const encodeMySqlDateTime = (iso: string): string =>\n new Date(iso).toISOString().slice(0, 23).replace(\"T\", \" \");\n"],"mappings":"mHA2CA,MAAM,EAAuB,MAGvB,EAAwB,UAG9B,SAAgB,EAAuB,EAAqB,CAC1D,OAAO,EAAI,WAAW,QAAQ,CAAG,OAAO,EAAI,MAAM,EAAE,CAAC,KAAO,EAa9D,SAAS,EAAe,EAAoC,CAC1D,GAAI,EAAS,EAAM,CAAE,OAAO,OAAO,SAAS,EAAM,CAAG,EAAQ,IAAA,GAC7D,GAAI,EAAS,EAAM,CAAE,CAInB,IAAM,EAAW,OAAO,EAAM,CAC9B,OAAO,OAAO,cAAc,EAAS,CAAG,EAAW,IAAA,IAcvD,SAAgB,EACd,EACA,EACiB,CACjB,GAAI,IAAS,OAAQ,OAAO,EAC5B,IAAM,EAAoB,KAAK,MAAM,EAAI,CACzC,OAAO,IAAS,cACZ,EACA,EAAoB,EAAuB,EAcjD,SAAgB,EACd,EACA,EACkB,CAClB,IAAM,EAAW,EAAe,EAAM,CACtC,GAAI,IAAa,IAAA,GAAW,OAC5B,IAAM,EACJ,IAAS,cACL,EACA,KAAK,OAAO,EAAW,GAAyB,EAAqB,CACtE,KAAkB,EAAkB,CACzC,OAAO,IAAI,KAAK,EAAkB,CAGpC,MAAM,EACJ,mIAGF,SAAS,EAAS,EAAe,EAAY,EAAuB,CAClE,IAAI,EAAS,EACb,IAAK,IAAI,EAAQ,EAAI,EAAQ,EAAK,EAAO,GAAS,EAAG,CACnD,IAA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ACb,EAAS,EAAI,EAAE,CACf,EAAS,EAAI,EAAE,CACf,EAAa,EAAI,GAAG,CACpB,EAAe,EAAI,GAAG,CACtB,EAAe,EAAI,GAAG,CAC5B,GACE,EACE,EAAwB,EAAM,EAAO,EAAI,EACzC,EAAgB,EAAM,EAAQ,EAAO,GAEvC,EAAa,IACb,EAAe,IACf,EAAe,GAEf,OACF,IAAM,EAAS,IAAI,KAAK,EAAE,CAE1B,EAAO,eAAe,EAAM,EAAQ,EAAG,EAAI,CAC3C,EAAO,YACL,EACA,EACA,EACA,QAAQ,EAAM,IAAM,IAAI,OAAO,EAAG,IAAI,CAAC,MAAM,EAAG,EAAE,CAAC,CACpD,CACD,IAAM,GAAU,EAAa,KAAO,EAAe,GAAK,GAAgB,IAClE,EAAQ,EAAO,SAAS,EAAI,EAAM,KAAO,IAAM,CAAC,EAAS,GAC/D,OAAO,EAAkB,EAAM,CAAG,IAAI,KAAK,EAAM,CAAG,IAAA,GAItD,MAAa,EAAuB,GAClC,IAAI,KAAK,EAAI,CAAC,aAAa,CAAC,MAAM,EAAG,GAAG,CAAC,QAAQ,IAAK,IAAI"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{s as e}from"./value-guards-CBVIJXlI.mjs";const t=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/,n=/^0+/,r=/0+$/,i=/^[+-]/;function a(e){let[t=``,a=``]=e.replace(i,``).split(`.`),o=t.replace(n,``)||`0`,s=a.replace(r,``);return o===`0`&&s===``?`0`:`${e.startsWith(`-`)?`-`:``}${o}${s===``?``:`.${s}`}`}function o(e){return typeof e==`string`?t.test(e)?a(e):void 0:x(e)}const s=10n;function c(e){return s**BigInt(e)}function l(e,t,n){let r=e/t,i=e%t*2n;return i>t?r+1n:i<t?r:n===`half-up`||r%2n!=0n?r+1n:r}const u=`decimal string (no exponent/number)`,d=`Expected Decimal or ${u}`,ee=`Expected Decimal, bigint, or ${u}`;function f(e,t){let n=e<0n;return p(n,(n?-e:e).toString(),t)}function p(e,t,n){let r=e?`-`:``;if(n===0)return`${r}${t}`;let i=t.padStart(n+1,`0`),a=i.length-n;return`${r}${i.slice(0,a)}.${i.slice(a)}`}function m(e,t,n){let r=e<0n;return p(r,l((r?-e:e)*c(n),c(t),`half-up`).toString(),n)}function h(e){let t=e.indexOf(`.`);if(t===-1)return[BigInt(e),0];let n=e.length-t-1;return[BigInt(e.slice(0,t)+e.slice(t+1)),n]}let g,_;var v=class e{static get name(){return`ExactDecimal`}#e;#t;value;constructor(e,t){let n;if(typeof e==`bigint`){let r=e,i=t??0;for(;i>0&&r%s===0n;)r/=s,i--;this.#e=r,this.#t=r===0n?0:i,n=f(this.#e,this.#t)}else if(g(e))this.#e=e.#e,this.#t=e.#t,n=e.value;else{let t=o(e);if(t===void 0)throw TypeError(ee);let[r,i]=h(t);this.#e=r,this.#t=i,n=t}this.value=n,Object.defineProperty(this,`value`,{writable:!1,configurable:!1})}static{g=e=>typeof e==`object`&&!!e&&#e in e,_=e=>e.value}#n(e){return this.#e*c(e-this.#t)}#r(t){let n=new e(t),r=Math.max(this.#t,n.#t);return[this.#n(r),n.#n(r),r]}plus(t){let[n,r,i]=this.#r(t);return new e(n+r,i)}minus(t){let[n,r,i]=this.#r(t);return new e(n-r,i)}times(t){let n=new e(t);return new e(this.#e*n.#e,this.#t+n.#t)}div(t,n=20,r=`half-up`){let i=new e(t);if(i.#e===0n)throw RangeError(`Division by zero`);let a=this.#e*c(i.#t+n),o=i.#e*c(this.#t),s=a<0n!=o<0n,u=l(a<0n?-a:a,o<0n?-o:o,r);return new e(s?-u:u,n)}cmp(e){let[t,n]=this.#r(e);return t<n?-1:t>n?1:0}eq(e){return this.cmp(e)===0}lt(e){return this.cmp(e)===-1}lte(e){return this.cmp(e)!==1}gt(e){return this.cmp(e)===1}gte(e){return this.cmp(e)!==-1}abs(){return new e(this.#e<0n?-this.#e:this.#e,this.#t)}neg(){return new e(-this.#e,this.#t)}toString(){return f(this.#e,this.#t)}toFixed(e){return e===void 0?this.toString():m(this.#e,this.#t,e)}toNumber(){return Number(this.toString())}valueOf(){return this.toString()}toJSON(){return this.toString()}[Symbol.for(`nodejs.util.inspect.custom`)](){return`Decimal("${this.value}")`}};const y=v;function b(e){let[t,n]=h(e);return new v(t,n)}function x(e){return g(e)?_(e):void 0}function te(e,t){return new v(e,t)}function S(e,t){let[n,r]=h(e);return(n*c(t-r)).toString()}function C(e,t,n){let r=e.indexOf(`.`),i=r===-1?0:e.length-r-1;if(i>n)return`'${e}' exceeds scale ${n} (${i} fractional digits)`;let a=e.startsWith(`-`)?1:0,o;if(e[a]!==`0`)o=(r===-1?e.length:r)-a+n;else{let t=r+1;for(;e[t]===`0`;)t++;o=r===-1?0:n-(t-r-1)}if(o>t)return`'${e}' exceeds precision ${t} (${o} digits)`}function w(e,t){return e===void 0||t===void 0?e===t:e.precision===t.precision&&e.scale===t.scale}const T=o,E=b,D=S,O=/^(?:0|-?[1-9]\d*)$/;function k(t,n,r){if(!(e(t)&&O.test(t)))return;let i=t.startsWith(`-`)?t.length-1:t.length;if(!(r!==void 0&&i>r))return te(BigInt(t),n)}function A(e,t,n){let r=k(e,t,n);return r===void 0?void 0:x(r)}const ne=/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/;function j(t,n,r=1/0){if(!(e(t)&&ne.test(t)))return;let i=o(t);return C(i,r,n)===void 0?i:void 0}function M(e,t){return j(e,t.scale,t.precision)}function N(e,t,n){return n===`coefficient`?S(e,t):e}function P(e,t,n){return N(e,t.scale,n)}function F(e,t,n,r){return n===`text`?j(e,t,r):A(e,t,r)}function I(e,t,n,r){if(n===`coefficient`)return k(e,t,r);let i=j(e,t,r);return i===void 0?void 0:b(i)}function L(e,t,n){return F(e,t.scale,n,t.precision)}function R(e,t,n){return I(e,t.scale,n,t.precision)}function z(e,t,n){let r=Array(e.length);for(let[i,a]of e.entries()){let e=o(a);if(e===void 0)return;r[i]=N(e,t.scale,n)}return r}function B(e,t,n){if(n===`coefficient`)return Y(e,t.scale,t.precision);try{if(!Array.isArray(e))return;let n=e.length;if(!Number.isSafeInteger(n)||n<0)return;let r=Array(n);for(let i=0;i<n;i++){if(!Object.hasOwn(e,i))return;let n=M(e[i],t);if(n===void 0)return;r[i]=n}return r}catch{return}}function V(e,t,n){return F(e,t.scale,n)}function H(e,t,n){return I(e,t.scale,n)}const U={pg:{precision:1e3,scale:1e3},mysql:{precision:65,scale:30,sum:65},sqlite:{precision:18,scale:18,sum:18}};function W(e,t){let n=U[e],{precision:r,scale:i}=t,a=X(t);return r>n.precision?`${a} exceeds max precision ${n.precision}`:i>n.scale?`${a} exceeds max scale ${n.scale}`:n.sum!==void 0&&r+i>n.sum?`${a} requires precision + scale <= ${n.sum}`:void 0}function G(e,{precision:t,scale:n}){return e===`sqlite`?`INTEGER`:`${e===`pg`?`NUMERIC`:`DECIMAL`}(${t},${n})`}function K(e,t,n){let{scale:r}=n;if(e===`sqlite`)return S(t,r);let i=t.indexOf(`.`);return r===0?i===-1?t:t.slice(0,i):i===-1?`${t}.${`0`.repeat(r)}`:t.padEnd(i+1+r,`0`)}function q(e,t,n){return e===`pg`?`{${t.map(e=>K(`pg`,e,n)).join(`,`)}}`:J(t,n.scale)}function J(e,t){return JSON.stringify(e.map(e=>S(e,t)))}function Y(t,n,r){if(!e(t))return;let i;try{i=JSON.parse(t)}catch{return}if(!Array.isArray(i))return;let a=Array(i.length);for(let[e,t]of i.entries()){let i=A(t,n,r);if(i===void 0)return;a[e]=i}return a}function X(e){return`precision ${e.precision}, scale ${e.scale}`}const re=/^-?\d+$/;function ie(e,t,n){let r=Z(e),i=Z(t);if(r===void 0||i===void 0||r<=0||i<0||i>r)return;let a={precision:r,scale:i};return W(n,a)===void 0?a:void 0}function Z(t){let n=typeof t==`number`?t:e(t)&&re.test(t)?Number(t):NaN;return Number.isSafeInteger(n)?n:void 0}const Q=-621672192e5,$=0xe677d21fdbff;function ae(e){return Number.isInteger(e)&&e>=Q&&e<=$}function oe(e,t,n){if(!(Number.isInteger(e)&&Number.isInteger(t)&&Number.isInteger(n))||t<1||t>12||n<1)return!1;let r=31;return t===2?r=ce(e)?29:28:(t===4||t===6||t===9||t===11)&&(r=30),n<=r}function se(e,t,n){return Number.isInteger(e)&&Number.isInteger(t)&&Number.isInteger(n)&&e>=0&&e<=23&&t>=0&&t<=59&&n>=0&&n<=59}function ce(e){return e%4==0&&(e%100!=0||e%400==0)}export{d as C,C as D,x as E,E as S,o as T,D as _,oe as a,ie as b,K as c,B as d,V as f,z as g,P as h,ae as i,q as l,W as m,Q as n,T as o,X as p,se as r,G as s,$ as t,L as u,R as v,y as w,w as x,H as y};
|
|
2
|
+
//# sourceMappingURL=datetime-values-D_G6m5_o.mjs.map
|