viborm 1.16.0 → 1.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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-C-zjj19U.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-C4qmW7xf.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-BMjJiBFm.d.mts → database-adapter-cW0nmWM6.d.mts} +1 -1
- 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-CHaVF7Vn.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-BvTixv-m.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-JpbiHdMb.mjs.map → every-tAZuZ50K.mjs.map} +1 -1
- package/dist/execution-context-couU2tgh.mjs +1 -1
- package/dist/{exports-DYnTfvQo.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-q3Rf_Xv8.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-DvcCUw7l.mjs.map +1 -0
- 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-BfF8xwfP.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-Bu63iAfT.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-Dlz3-2JC.d.mts → verify-v1-CJFrJ4lx.d.mts} +10 -183
- package/dist/version-nEOMCWfV.mjs +2 -0
- package/dist/{version-0BDwfy7C.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-D7sWgUt2.mjs +0 -2
- package/dist/client-D7sWgUt2.mjs.map +0 -1
- package/dist/client-DEfFqv4S.mjs +0 -9
- package/dist/client-DEfFqv4S.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-JpbiHdMb.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-q3Rf_Xv8.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-DEZ0uhK2.mjs +0 -3
- package/dist/libsql-DEZ0uhK2.mjs.map +0 -1
- package/dist/light-D2wNSbzY.mjs +0 -2
- package/dist/memory-BaGWNdvk.mjs +0 -2
- package/dist/memory-BaGWNdvk.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-BFPF8xyv.mjs +0 -9
- package/dist/mysql-BFPF8xyv.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-DQQE2ys_.mjs +0 -34
- package/dist/postgres-DQQE2ys_.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-Bcsz0EJv.mjs +0 -2
- package/dist/provider-limits-Bcsz0EJv.mjs.map +0 -1
- 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-ettLu5xG.mjs +0 -33
- package/dist/serializer-ettLu5xG.mjs.map +0 -1
- package/dist/snowflake-BfF8xwfP.mjs +0 -2
- package/dist/sql-Bu63iAfT.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-DY74AUeD.mjs +0 -2
- package/dist/surrealql-DY74AUeD.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-0BDwfy7C.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":"runtime-Dfkv59_p.mjs","names":[],"sources":["../src/migrations/drivers/mysql/catalog.ts","../src/migrations/drivers/mysql/control.ts","../src/migrations/drivers/mysql/introspect.ts","../src/migrations/drivers/mysql/pinned-session.ts","../src/migrations/drivers/mysql/decimal-recovery.ts","../src/migrations/drivers/mysql/runtime.ts"],"sourcesContent":["/**\n * MySQL catalog targeting (plan §5.2).\n *\n * Every MySQL migration catalog read filters on ONE exact database, and this\n * module owns which database that is. It replaces `DATABASE()`, whose answer is\n * the connection's ambient default — a fact the ORM never configured and a\n * proxy or a pooled session can change under it.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\n\n/**\n * The configured database name, on the shared safe-metadata allowlist's own\n * `namespace` key (`src/errors/diagnostics.ts`). The message states which\n * database it is; this makes it readable programmatically too.\n */\nconst namespaceMeta = (namespace: string) => ({\n dialect: \"mysql\",\n namespace,\n});\n\n/**\n * The one existence proof. `SCHEMA_NAME` comes back so the caller can speak the\n * server's own spelling in later catalog filters.\n *\n * The comparison is case-insensitive because `lower_case_table_names` can make\n * a differently cased configured value name the same physical database; the\n * candidate set it produces is then resolved by the rules below, never guessed.\n */\nconst SCHEMATA_QUERY = `\nSELECT SCHEMA_NAME\nFROM information_schema.SCHEMATA\nWHERE LOWER(SCHEMA_NAME) = LOWER(?)\nORDER BY SCHEMA_NAME\n`;\n\n/**\n * One catalog row, as UNTRUSTED transport data.\n *\n * `SCHEMA_NAME` is typed `unknown` on purpose. MySQL declares the column NOT\n * NULL, but the value reaching this module has crossed a driver: a\n * serverless/HTTP MySQL transport, or any custom `_executeRaw`, can answer with\n * `null` or a number. Declaring the server's own DDL here would be a claim this\n * module cannot make, so the narrowing below makes it instead.\n */\ninterface SchemataRow {\n SCHEMA_NAME: unknown;\n}\n\n/** Executes one catalog statement with its bound values. */\nexport type CatalogReader = <T>(\n sql: string,\n params?: unknown[]\n) => Promise<{ rows: T[] }>;\n\n/**\n * Proves the configured database exists and returns the catalog's own spelling\n * of it (§5.2).\n *\n * Three refusals, all before any snapshot, tracking or DDL effect:\n *\n * 1. no configured database — a MySQL estate is database-relative on purpose,\n * so an unbound driver has nothing to read a catalog against. Every COMMAND\n * that reaches here has already been refused by the shared live-capability\n * admission owner (`src/migrations/admission.ts`), `introspect(client)`\n * included. This arm's unique coverage is the UNBOUND REGISTERED SINGLETON,\n * which the migration layer deliberately keeps usable by name for\n * artifact-only work: `mysqlMigrationDriver.introspect(reader)` reaches this\n * reader with no client, no context and therefore no admission owner in\n * front of it. It is also what narrows the base class's optional\n * `namespace?: string` to the `string` every filter below binds, without an\n * assertion.\n * 2. no candidate row — a missing database is not an empty database, and\n * publishing an empty inventory for one would plan a full rebuild against a\n * database that does not exist.\n * 3. more than one case-only candidate and none byte-exact — the server would\n * pick one by its own collation rules; choosing for it would silently bind\n * the estate to a database the configuration never named.\n *\n * The returned spelling is command-local: it is a projection of the configured\n * target under this server's identity rules, it is never stored, and it\n * disappears with the pinned session that resolved it. Within that command it\n * is what EVERY statement naming the database renders from — the `USE`, the\n * catalog filters, the tracking table and the live DDL alike — because refusal\n * 3 has already established that only one database answers to the configured\n * name here, and the server accepts only its own spelling of it. Runtime ORM\n * SQL is outside this: it renders from the adapter's immutable configured\n * value, which nothing in this module projects.\n */\nexport async function resolveCatalogNamespace(\n executeRaw: CatalogReader,\n namespace: string | undefined\n): Promise<string> {\n if (namespace === undefined) {\n throw new MigrationError(\n \"MySQL adapter declares no database; configure namespace or database.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: \"mysql\", type: \"unbound-database\" } }\n );\n }\n\n const { rows } = await executeRaw<SchemataRow>(SCHEMATA_QUERY, [namespace]);\n const candidates = rows\n .map((row) => row.SCHEMA_NAME)\n .filter((name): name is string => typeof name === \"string\");\n\n if (candidates.length === 0) {\n throw new MigrationError(\n `MySQL database \"${namespace}\" does not exist or is not visible.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { ...namespaceMeta(namespace), type: \"missing-database\" } }\n );\n }\n\n const exact = candidates.find((candidate) => candidate === namespace);\n if (exact !== undefined) return exact;\n\n const [folded] = candidates;\n if (candidates.length === 1 && folded !== undefined) return folded;\n\n throw new MigrationError(\n `MySQL database \"${namespace}\" matches ${candidates.length} case-variant databases (${candidates.join(\", \")}); specify exact casing.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n ...namespaceMeta(namespace),\n type: \"ambiguous-database\",\n candidates,\n },\n }\n );\n}\n","/**\n * MySQL control-plane presence, authentication, and SQL syntax.\n */\n\nimport type { AnyDriver } from \"../../../drivers/driver\";\nimport { boundCatalogNamespace, qualifiedName } from \"../../catalog-runtime\";\nimport {\n CONTROL_TABLES,\n type ControlDialect,\n invalidControlState,\n normalizeSingletonCheck,\n sqlControlDefinition,\n} from \"../../control-types\";\nimport { readFlag } from \"../../v1-parse-shared\";\nimport type { BoundMigrationDriver } from \"..\";\nimport { assertSqlControlAuthentic } from \"../sql-control\";\n\nasync function mysqlTablePresent(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n tableName: string\n): Promise<boolean> {\n const result = await producer._executeRaw<Record<string, unknown>>(\n \"SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = ? AND table_name = ?)\",\n [boundCatalogNamespace(driver), tableName]\n );\n if (result.rows.length !== 1) {\n throw invalidControlState(\"Control catalog probe must return 1 row\");\n }\n return readFlag(Object.values(result.rows[0]!)[0]) === true;\n}\n\nexport const mysqlControlDialect: ControlDialect = {\n placeholder: () => \"?\",\n jsonField: (field) => `JSON_UNQUOTE(JSON_EXTRACT(payload, '$.${field}'))`,\n markerMatch: (_first, { revision, pathHash }) => ({\n sql: \"CAST(JSON_UNQUOTE(JSON_EXTRACT(payload, '$.revision')) AS UNSIGNED) = ? AND JSON_UNQUOTE(JSON_EXTRACT(payload, '$.pathHash')) = ?\",\n params: [revision, pathHash],\n }),\n createTableSql: (driver, table) =>\n `CREATE TABLE IF NOT EXISTS ${qualifiedName(driver, CONTROL_TABLES[table])} ${sqlControlDefinition(\"mysql\", table)}`,\n async inspectPresence(producer, driver) {\n const statePresent = await mysqlTablePresent(\n producer,\n driver,\n CONTROL_TABLES.state\n );\n const logPresent = await mysqlTablePresent(\n producer,\n driver,\n CONTROL_TABLES.log\n );\n return { statePresent, logPresent };\n },\n assertAuthentic(producer, driver, scope) {\n return assertSqlControlAuthentic(\n producer,\n driver,\n scope,\n async () => {\n const result = await producer._executeRaw<{ definition: unknown }>(\n `SELECT cc.CHECK_CLAUSE AS definition\nFROM information_schema.TABLE_CONSTRAINTS tc\nJOIN information_schema.CHECK_CONSTRAINTS cc\n ON cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA\n AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME\nWHERE tc.CONSTRAINT_SCHEMA = ?\n AND tc.TABLE_NAME = ?\n AND tc.CONSTRAINT_TYPE = 'CHECK'\nORDER BY tc.CONSTRAINT_NAME`,\n [driver.namespace, CONTROL_TABLES.state]\n );\n return (\n result.rows.length === 1 &&\n normalizeSingletonCheck(result.rows[0]?.definition) === \"singleton=1\"\n );\n },\n () =>\n producer._executeRaw<Record<string, unknown>>(\n \"SELECT EXISTS (SELECT 1 FROM information_schema.TRIGGERS WHERE TRIGGER_SCHEMA = ? AND EVENT_OBJECT_TABLE IN (?, ?)) AS attached\",\n [driver.namespace, CONTROL_TABLES.state, CONTROL_TABLES.log]\n )\n );\n },\n};\n","/**\n * MySQL Schema Introspection\n *\n * Reads the current database schema from MySQL's information_schema,\n * returning a normalized SchemaSnapshot.\n */\n\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport { mysqlStringLiteral } from \"../../../adapters/databases/mysql/string-literal\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport {\n readMysqlDecimalListMarker,\n readStoredDecimalDescriptor,\n} from \"../../decimal\";\nimport { decodeUtf8 } from \"../../identity\";\nimport { RAW_INDEX_MARKER_PREFIX, readRawIndexMarker } from \"../../raw-index\";\nimport type {\n ColumnDef,\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n PrimaryKeyDef,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n ViewDef,\n} from \"../../types\";\nimport {\n holdsAutoViewBody,\n type LiveAutoKeeper,\n type LiveAutoTable,\n readAutoViews,\n readKeeperMarker,\n readViewComment,\n readViewMarker,\n} from \"../../view\";\nimport { groupBy, groupByNested, mapReferentialAction } from \"../utils\";\nimport { type CatalogReader, resolveCatalogNamespace } from \"./catalog\";\nimport {\n MYSQL_PRINTED_CHARACTERS,\n mysqlEnumType,\n parseMySqlEnumValues,\n} from \"./type-mapping\";\nimport type {\n MySQLColumn,\n MySQLForeignKey,\n MySQLIndex,\n MySQLPrimaryKey,\n MySQLTable,\n MySQLView,\n} from \"./types\";\n\n// =============================================================================\n// SQL QUERIES\n// =============================================================================\n\n// Every filter below binds the resolved database as DATA (§5.2). The name is\n// never spliced into the statement, and `DATABASE()` — the connection's ambient\n// default, which the ORM never configured — appears nowhere.\n// A table's comment rides along: one that is a view's marker holds a view\n// kept by triggers (`.materialized({ refresh: \"auto\" })`).\nconst TABLES_QUERY =\n \"SELECT TABLE_NAME, TABLE_COMMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME\";\n\nconst VIEWS_QUERY =\n \"SELECT TABLE_NAME, VIEW_DEFINITION FROM information_schema.VIEWS WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME\";\n\nconst AUTO_KEEPERS_QUERY =\n \"SELECT TRIGGER_NAME, EVENT_OBJECT_TABLE, ACTION_STATEMENT FROM information_schema.TRIGGERS WHERE TRIGGER_SCHEMA = ? AND ACTION_STATEMENT LIKE '%viborm_view_%' ORDER BY TRIGGER_NAME\";\n\nconst COLUMNS_QUERY =\n \"SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, COLUMN_TYPE, IS_NULLABLE, COLUMN_DEFAULT, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE, SRS_ID, EXTRA, COLUMN_COMMENT FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME, ORDINAL_POSITION\";\n\nconst PRIMARY_KEYS_QUERY =\n \"SELECT tc.TABLE_NAME, tc.CONSTRAINT_NAME, kcu.COLUMN_NAME, kcu.ORDINAL_POSITION FROM information_schema.TABLE_CONSTRAINTS tc JOIN information_schema.KEY_COLUMN_USAGE kcu ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA AND tc.TABLE_NAME = kcu.TABLE_NAME WHERE tc.TABLE_SCHEMA = ? AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY tc.TABLE_NAME, kcu.ORDINAL_POSITION\";\n\nconst INDEXES_QUERY =\n \"SELECT TABLE_NAME, INDEX_NAME, COLUMN_NAME, NON_UNIQUE, INDEX_TYPE, INDEX_COMMENT, SEQ_IN_INDEX FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = ? AND INDEX_NAME != 'PRIMARY' ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX\";\n\nconst FOREIGN_KEYS_QUERY =\n \"SELECT tc.TABLE_SCHEMA, tc.TABLE_NAME, tc.CONSTRAINT_NAME, kcu.COLUMN_NAME, kcu.REFERENCED_TABLE_SCHEMA, kcu.REFERENCED_TABLE_NAME, kcu.REFERENCED_COLUMN_NAME, rc.DELETE_RULE, rc.UPDATE_RULE, kcu.ORDINAL_POSITION FROM information_schema.TABLE_CONSTRAINTS tc JOIN information_schema.KEY_COLUMN_USAGE kcu ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA AND tc.TABLE_NAME = kcu.TABLE_NAME JOIN information_schema.REFERENTIAL_CONSTRAINTS rc ON rc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME AND rc.CONSTRAINT_SCHEMA = tc.TABLE_SCHEMA WHERE tc.CONSTRAINT_TYPE = 'FOREIGN KEY' AND (tc.TABLE_SCHEMA = ? OR kcu.REFERENCED_TABLE_SCHEMA = ?) ORDER BY tc.TABLE_NAME, tc.CONSTRAINT_NAME, kcu.ORDINAL_POSITION\";\n\n// =============================================================================\n// CONSTANTS\n// =============================================================================\n\n/**\n * The MySQL storage whose literal default the catalog already reports the way\n * the estate spells it: a number is a number, and a `BIT` default is reported\n * as its own `b'…'` literal. Every other type's literal default is a QUOTED\n * string in DDL, and `information_schema` reports it with the quotes gone.\n */\nconst MYSQL_NUMERIC_DATA_TYPES = new Set([\n \"bigint\",\n \"bit\",\n \"decimal\",\n \"double\",\n \"float\",\n \"int\",\n \"integer\",\n \"mediumint\",\n \"numeric\",\n \"real\",\n \"smallint\",\n \"tinyint\",\n]);\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\nfunction formatColumnType(col: MySQLColumn): string {\n if (col.DATA_TYPE.toLowerCase() === \"point\") {\n const srid = readSrid(col);\n return srid === undefined ? \"POINT\" : `POINT SRID ${srid}`;\n }\n\n // An ENUM's values ARE its type. `information_schema` prints its own\n // rendering of them — `enum('a','b')`, no space after the comma — so the\n // parsed values are re-spelled through the estate's ONE enum speller and the\n // two snapshots name one type. A COLUMN_TYPE that parses to no values at all\n // is not an enum MySQL could have created; it stays exactly as read.\n if (col.DATA_TYPE === \"enum\") {\n const values = parseMySqlEnumValues(col.COLUMN_TYPE);\n return values ? mysqlEnumType(values) : col.COLUMN_TYPE;\n }\n\n // For types with modifiers (unsigned, zerofill) or size info in COLUMN_TYPE,\n // prefer COLUMN_TYPE to preserve full type specification\n // Examples: \"int unsigned\", \"bigint unsigned zerofill\", \"varbinary(255)\", \"bit(8)\", \"timestamp(6)\"\n const columnType = col.COLUMN_TYPE.toLowerCase();\n const hasModifiers =\n columnType.includes(\"unsigned\") ||\n columnType.includes(\"zerofill\") ||\n // Has parentheses with size/precision info (but not enum which is handled above)\n (columnType.includes(\"(\") && col.DATA_TYPE !== \"enum\");\n\n if (hasModifiers) {\n return col.COLUMN_TYPE;\n }\n\n // Fallback: construct from DATA_TYPE with precision info\n if (col.DATA_TYPE === \"varchar\" && col.CHARACTER_MAXIMUM_LENGTH) {\n return `VARCHAR(${col.CHARACTER_MAXIMUM_LENGTH})`;\n }\n if (col.DATA_TYPE === \"char\" && col.CHARACTER_MAXIMUM_LENGTH) {\n return `CHAR(${col.CHARACTER_MAXIMUM_LENGTH})`;\n }\n if (col.DATA_TYPE === \"decimal\" && col.NUMERIC_PRECISION) {\n if (col.NUMERIC_SCALE !== null && col.NUMERIC_SCALE !== undefined) {\n return `DECIMAL(${col.NUMERIC_PRECISION},${col.NUMERIC_SCALE})`;\n }\n return `DECIMAL(${col.NUMERIC_PRECISION})`;\n }\n\n return col.DATA_TYPE.toUpperCase();\n}\n\nfunction readSrid(col: MySQLColumn): number | undefined {\n if (col.SRS_ID === null || col.SRS_ID === undefined) return undefined;\n const value = Number(col.SRS_ID);\n if (Number.isSafeInteger(value) && value >= 0 && value <= 4_294_967_295) {\n return value;\n }\n throw new MigrationError(\n `Invalid MySQL SRID on \"${col.TABLE_NAME}\".\"${col.COLUMN_NAME}\".`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n dialect: \"mysql\",\n table: col.TABLE_NAME,\n column: col.COLUMN_NAME,\n type: \"invalid-catalog-srid\",\n },\n }\n );\n}\n\nfunction isAutoIncrement(extra: string): boolean {\n return extra.toLowerCase().includes(\"auto_increment\");\n}\n\n/**\n * The declared decimal domain of a MySQL column, or `undefined`.\n *\n * Two carriers, because MySQL stores the two shapes differently. A scalar is\n * `DECIMAL(p,s)` and the catalog reports the pair directly. A list is `JSON`,\n * which carries nothing, so its domain lives in the deterministic column\n * comment — matched EXACTLY (§6.2): a comment that merely mentions a decimal is\n * a comment, not a descriptor, and reading one as a descriptor would attach a\n * domain to a column VibORM never declared one on.\n */\nfunction readDecimalDomain(col: MySQLColumn): DecimalDescriptor | undefined {\n if (col.DATA_TYPE === \"decimal\" && col.NUMERIC_PRECISION !== null) {\n const descriptor = readStoredDecimalDescriptor(\n col.NUMERIC_PRECISION,\n col.NUMERIC_SCALE ?? 0,\n \"mysql\"\n );\n if (descriptor !== undefined) return descriptor;\n throw new MigrationError(\n `MySQL \"${col.TABLE_NAME}\".\"${col.COLUMN_NAME}\" DECIMAL(${String(col.NUMERIC_PRECISION)},${String(col.NUMERIC_SCALE ?? 0)}) is outside VibORM's fixed-decimal domain.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n dialect: \"mysql\",\n table: col.TABLE_NAME,\n column: col.COLUMN_NAME,\n type: \"invalid-catalog-decimal-domain\",\n },\n }\n );\n }\n if (col.DATA_TYPE !== \"json\") return undefined;\n return readMysqlDecimalListMarker(col.COLUMN_COMMENT);\n}\n\n/**\n * MySQL deparses an expression-backed string literal as `_charset\\\\'value\\\\'`.\n * The introducer is CAPTURED because it names the encoding of the bytes that\n * follow it (see {@link decodeIntroducedLiteral}).\n */\nconst MYSQL_STRING_EXPRESSION_DEFAULT = /^_([A-Za-z0-9_]+)\\\\'([\\s\\S]*)\\\\'$/;\n\n/** One backslash escape, with the character it escapes. */\nconst MYSQL_ESCAPE_SEQUENCE = /\\\\([\\s\\S]?)/g;\n\n/** Each byte read as the codepoint of the same number. */\nfunction decodeSingleByte(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => String.fromCharCode(byte)).join(\"\");\n}\n\n/**\n * MySQL's `latin1` IS Windows-1252, not ISO-8859-1: the 32 bytes 0x80–0x9F are\n * printable characters there (0x93 is U+201C), and the five cp1252 leaves\n * undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D) MySQL maps to the same-numbered\n * control. Every other byte is the codepoint of its own number.\n */\nconst CP1252_HIGH: readonly number[] = [\n 0x20_ac, 0x81, 0x20_1a, 0x01_92, 0x20_1e, 0x20_26, 0x20_20, 0x20_21, 0x02_c6,\n 0x20_30, 0x01_60, 0x20_39, 0x01_52, 0x8d, 0x01_7d, 0x8f, 0x90, 0x20_18,\n 0x20_19, 0x20_1c, 0x20_1d, 0x20_22, 0x20_13, 0x20_14, 0x02_dc, 0x21_22,\n 0x01_61, 0x20_3a, 0x01_53, 0x9d, 0x01_7e, 0x01_78,\n];\nfunction decodeLatin1(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) =>\n String.fromCharCode(\n byte >= 0x80 && byte <= 0x9f ? (CP1252_HIGH[byte - 0x80] ?? byte) : byte\n )\n ).join(\"\");\n}\n\n/**\n * How an introducer's bytes are READ — one entry per charset, because the\n * charset is what says what a byte MEANS.\n *\n * MySQL names the charset of the DDL the literal arrived in and FREEZES it in\n * the stored expression, so the writing SESSION decides what reaches this\n * inverse, whatever the reading one speaks (measured: a column created over a\n * `latin1` connection reports `_latin1` to an ordinary utf8mb4 connection,\n * `closure-repair-2/t3/receipts/probe-frozen-introducer.log`). The UTF-8 family\n * is decoded; `ascii` and `binary` map each byte to the codepoint of the same\n * number, so the catalog's text already IS the value; `latin1` is read as the\n * Windows-1252 MySQL means by it ({@link decodeLatin1}). A charset\n * outside this table — `cp1251`, say, where the same byte is a different\n * letter — is not read at all: either reading would be a guess there, and a\n * wrong guess calls two different defaults equal.\n */\nconst MYSQL_INTRODUCER_DECODERS: ReadonlyMap<\n string,\n (bytes: Uint8Array) => string\n> = new Map([\n [\"utf8\", decodeUtf8],\n [\"utf8mb3\", decodeUtf8],\n [\"utf8mb4\", decodeUtf8],\n [\"latin1\", decodeLatin1],\n [\"ascii\", decodeSingleByte],\n [\"binary\", decodeSingleByte],\n]);\n\n/**\n * The printed literal behind the catalog's text, or `undefined` when the text\n * is not the byte sequence the introducer promises.\n *\n * `information_schema.COLUMNS.COLUMN_DEFAULT` hands an EXPRESSION default's\n * text back one codepoint per BYTE: `café ☕` arrives as the nine codepoints\n * `63 61 66 c3 a9 20 e2 98 95` — the UTF-8 bytes of the value, each read as a\n * character — while the SAME column carries a LITERAL default's value decoded\n * (measured on 8.4.11: `HEX(COLUMN_DEFAULT)` shows the expansion server-side,\n * and `SHOW CREATE TABLE` prints the true text, so the loss is MySQL's own\n * rendering of a stored expression, not the connection's character set and not\n * the driver). Those bytes are the literal, in the charset the introducer\n * names, so they are read back with THAT charset\n * ({@link MYSQL_INTRODUCER_DECODERS}) rather than re-decoded by a rule of this\n * module's invention.\n *\n * An unknown charset, an out-of-byte-range codepoint, or an invalid byte\n * sequence keeps the catalog's own text. These checks do not prove provenance:\n * the measured mysql2 byte-expanded spelling of `é` and already-decoded text\n * whose literal characters are `é` both present `c3 a9`, a valid UTF-8\n * sequence. Content alone cannot distinguish them. This decoder therefore\n * describes the measured mysql2 catalog representation; other transport\n * representations are unverified, and valid UTF-8-shaped already-decoded text\n * can be transformed rather than fail closed.\n */\nfunction decodeIntroducedLiteral(\n introducer: string,\n printed: string\n): string | undefined {\n const decode = MYSQL_INTRODUCER_DECODERS.get(introducer.toLowerCase());\n if (decode === undefined) return undefined;\n const codes = [...printed].map((character) => character.codePointAt(0) ?? 0);\n if (codes.some((code) => code > 0xff)) return undefined;\n try {\n return decode(Uint8Array.from(codes));\n } catch {\n return undefined;\n }\n}\n\n/** `undefined` for a body carrying an escape MySQL's printer does not write. */\nfunction unescapeOneLayer(body: string): string | undefined {\n let owned = true;\n const unescaped = body.replace(\n MYSQL_ESCAPE_SEQUENCE,\n (_match: string, escaped: string) => {\n const character = MYSQL_PRINTED_CHARACTERS.get(escaped);\n if (character === undefined) {\n owned = false;\n return escaped;\n }\n return character;\n }\n );\n return owned ? unescaped : undefined;\n}\n\n/**\n * The VALUE behind MySQL's deparse of a string default, or `undefined` when\n * the catalog text carries an escape this inverse does not own.\n *\n * The text is escaped TWICE — once by MySQL printing the string literal inside\n * the expression, once by `information_schema` printing that expression — so a\n * declared `it's` arrives as the characters `_utf8mb4\\'it\\\\\\'s\\'` (measured on\n * MySQL 8.4.11). Each pass undoes one layer, through the table MySQL's printer\n * writes (`MYSQL_PRINTED_CHARACTERS`). An escape outside that table is not one\n * this server printed for a value the estate spelled, so inverting it would be\n * a guess, and a wrong guess calls two different defaults equal.\n *\n * The BYTES come first ({@link decodeIntroducedLiteral}), because the catalog\n * spells them one per codepoint and every escape MySQL prints is ASCII: the\n * layers are the same after the decode, and only a text that is those bytes\n * reaches them.\n */\nfunction deparsedStringValue(columnDefault: string): string | undefined {\n const deparsed = MYSQL_STRING_EXPRESSION_DEFAULT.exec(columnDefault);\n const introducer = deparsed?.[1];\n const body = deparsed?.[2];\n const printed =\n introducer === undefined || body === undefined\n ? undefined\n : decodeIntroducedLiteral(introducer, body);\n const literal = printed === undefined ? undefined : unescapeOneLayer(printed);\n return literal === undefined ? undefined : unescapeOneLayer(literal);\n}\n\n/**\n * The column's default, in the ONE spelling the estate uses.\n *\n * MySQL reports a default in two vocabularies and neither is the estate's. A\n * LITERAL default comes back as the bare VALUE — `member`, `x'y` — with the\n * quotes DDL required stripped off. An EXPRESSION default (every default on a\n * TEXT, BLOB, JSON or GEOMETRY column, since those refuse a literal) comes back\n * as MySQL's deparse of the expression, where a string literal is printed\n * `_charset\\\\'value\\\\'`. Both are translated here, at the one boundary that\n * reads the catalog, into what `finalizeMySQLColumn` spells on the desired\n * side; otherwise a default nobody touched reads as a changed column on every\n * push, and the final push attestation refuses the schema it just created.\n *\n * A deparse this inverse does not own keeps MySQL's own catalog text, which\n * stays different from the desired side: the column is re-planned and the push\n * then FAILS at the final attestation with `MIGRATION_DRIFT`. That is the\n * fail-closed direction — the same one the decimal-list container took when it\n * could not be re-encoded byte for byte — and it refuses a default nobody\n * proved equal instead of reporting a schema the database does not hold.\n */\nfunction cleanDefault(col: MySQLColumn): string | undefined {\n const columnDefault = col.COLUMN_DEFAULT;\n if (columnDefault === null) return undefined;\n if (col.EXTRA.toUpperCase().includes(\"DEFAULT_GENERATED\")) {\n const value = deparsedStringValue(columnDefault);\n return value === undefined\n ? columnDefault\n : `(${mysqlStringLiteral(value)})`;\n }\n return MYSQL_NUMERIC_DATA_TYPES.has(col.DATA_TYPE.toLowerCase())\n ? columnDefault\n : mysqlStringLiteral(columnDefault);\n}\n\n/**\n * Refuses every foreign key with one endpoint outside the selected database\n * (§5.2), before the snapshot exists.\n *\n * Both directions are refused for the same reason: the estate's own DDL cannot\n * express, drop or recreate a constraint whose other half lives in a database\n * this client does not manage, so a reset, a push, or a generated down would\n * plan work that is either impossible or destructive to a stranger's schema.\n *\n * This runs BEFORE the rows are grouped, because the grouped set is also what\n * hides MySQL's auto-created FK indexes from the snapshot: admitting a foreign\n * row here would silently change which indexes the differ sees.\n */\nfunction admitContainedForeignKeys(\n rows: readonly MySQLForeignKey[],\n namespace: string,\n tables?: readonly string[]\n): void {\n for (const row of rows) {\n if (\n tables !== undefined &&\n !(row.TABLE_SCHEMA === namespace && tables.includes(row.TABLE_NAME)) &&\n !(\n row.REFERENCED_TABLE_SCHEMA === namespace &&\n tables.includes(row.REFERENCED_TABLE_NAME)\n )\n )\n continue;\n if (\n row.TABLE_SCHEMA === namespace &&\n row.REFERENCED_TABLE_SCHEMA === namespace\n ) {\n continue;\n }\n throw new MigrationError(\n `Cross-database FK \"${row.CONSTRAINT_NAME}\": \\`${row.TABLE_SCHEMA}\\`.\\`${row.TABLE_NAME}\\` references \\`${row.REFERENCED_TABLE_SCHEMA}\\`.\\`${row.REFERENCED_TABLE_NAME}\\` outside \"${namespace}\".`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n // BOTH endpoints are reported (§5.2), each on its own allowlisted\n // channel: the referencing one on `table`, the referenced one on\n // `referencedTable`, beside the database this client manages.\n meta: {\n dialect: \"mysql\",\n type: \"cross-database-foreign-key\",\n constraint: row.CONSTRAINT_NAME,\n namespace,\n table: `${row.TABLE_SCHEMA}.${row.TABLE_NAME}`,\n referencedTable: `${row.REFERENCED_TABLE_SCHEMA}.${row.REFERENCED_TABLE_NAME}`,\n },\n }\n );\n }\n}\n\n// =============================================================================\n// INTROSPECTION\n// =============================================================================\n\nexport async function introspect(\n executeRaw: CatalogReader,\n namespace: string | undefined,\n managedTables?: readonly string[]\n): Promise<SchemaSnapshot> {\n // The database is proven to exist BEFORE anything is read, so an absent one\n // can never be published as an empty inventory (§5.2). Its returned spelling\n // is what every filter below binds and what the containment comparison uses:\n // under `lower_case_table_names` the server's spelling is the identity the\n // catalog rows actually carry.\n const catalogNamespace = await resolveCatalogNamespace(executeRaw, namespace);\n\n // One after another: these run on the command's ONE pinned session, and a\n // connection runs one statement at a time. mysql2 queues overlapping\n // queries silently, but the overlap bought nothing.\n const scope = [catalogNamespace];\n const tablesResult = await executeRaw<MySQLTable>(TABLES_QUERY, scope);\n const columnsResult = await executeRaw<MySQLColumn>(COLUMNS_QUERY, scope);\n const primaryKeysResult = await executeRaw<MySQLPrimaryKey>(\n PRIMARY_KEYS_QUERY,\n scope\n );\n const indexesResult = await executeRaw<MySQLIndex>(INDEXES_QUERY, scope);\n const foreignKeysResult = await executeRaw<MySQLForeignKey>(\n FOREIGN_KEYS_QUERY,\n [catalogNamespace, catalogNamespace]\n );\n const viewsResult = await executeRaw<MySQLView>(VIEWS_QUERY, scope);\n\n admitContainedForeignKeys(\n foreignKeysResult.rows,\n catalogNamespace,\n managedTables\n );\n\n // Group results\n const columnsByTable = groupBy(columnsResult.rows, (col) => col.TABLE_NAME);\n const pkByTable = groupBy(primaryKeysResult.rows, (pk) => pk.TABLE_NAME);\n const indexesByTable = groupByNested(\n indexesResult.rows,\n (idx) => idx.TABLE_NAME,\n (idx) => idx.INDEX_NAME\n );\n const fkByTable = groupByNested(\n foreignKeysResult.rows.filter((fk) => fk.TABLE_SCHEMA === catalogNamespace),\n (fk) => fk.TABLE_NAME,\n (fk) => fk.CONSTRAINT_NAME\n );\n // Track enum definitions found in columns\n const enumDefs: EnumDef[] = [];\n const seenEnums = new Set<string>();\n\n // Build tables\n const tables: TableDef[] = [];\n\n for (const table of tablesResult.rows) {\n const tableName = table.TABLE_NAME;\n\n // Build columns\n const columns: ColumnDef[] = [];\n for (const col of columnsByTable.get(tableName) || []) {\n if (\n (managedTables === undefined || managedTables.includes(tableName)) &&\n (col.EXTRA.toUpperCase().includes(\"VIRTUAL GENERATED\") ||\n col.EXTRA.toUpperCase().includes(\"STORED GENERATED\"))\n )\n throw new MigrationError(\n `Unsupported generated MySQL column \"${tableName}.${col.COLUMN_NAME}\".`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n table: tableName,\n column: col.COLUMN_NAME,\n feature: \"generated column\",\n },\n }\n );\n // Extract enum values if this is an enum column\n // MySQL has no standalone enum object, so the inline type IS the\n // identity — and it is the identity the DESIRED snapshot registers too\n // (`serializer.ts` names an enum by `getEnumColumnType`). Naming it\n // anything else here, as a derived `table$column$enum` did, made every\n // enum-bearing schema carry two enum definitions that could never match.\n if (col.DATA_TYPE === \"enum\") {\n const values = parseMySqlEnumValues(col.COLUMN_TYPE);\n const enumName = values && mysqlEnumType(values);\n if (values && enumName && !seenEnums.has(enumName)) {\n enumDefs.push({ name: enumName, values });\n seenEnums.add(enumName);\n }\n }\n\n const managed =\n managedTables === undefined || managedTables.includes(tableName);\n const decimal = managed ? readDecimalDomain(col) : undefined;\n columns.push({\n name: col.COLUMN_NAME,\n type: managed ? formatColumnType(col) : col.COLUMN_TYPE,\n nullable: col.IS_NULLABLE === \"YES\",\n default: managed ? cleanDefault(col) : undefined,\n autoIncrement: isAutoIncrement(col.EXTRA),\n decimal,\n });\n }\n\n // Build primary key\n let primaryKey: PrimaryKeyDef | undefined;\n const pkCols = pkByTable.get(tableName);\n if (pkCols && pkCols.length > 0) {\n pkCols.sort((a, b) => a.ORDINAL_POSITION - b.ORDINAL_POSITION);\n const firstPkCol = pkCols[0];\n if (firstPkCol) {\n primaryKey = {\n columns: pkCols.map((pk) => pk.COLUMN_NAME),\n name: firstPkCol.CONSTRAINT_NAME,\n };\n }\n }\n\n // Build indexes\n const indexes: IndexDef[] = [];\n const tableIndexes = indexesByTable.get(tableName);\n // MySQL auto-creates an index named after each FK constraint; it isn't a\n // user index and can't be dropped while the FK exists, so hide it\n const fkNames = new Set(fkByTable.get(tableName)?.keys() ?? []);\n if (tableIndexes) {\n for (const [indexName, indexCols] of tableIndexes) {\n if (fkNames.has(indexName)) {\n continue;\n }\n indexCols.sort((a, b) => a.SEQ_IN_INDEX - b.SEQ_IN_INDEX);\n const firstCol = indexCols[0];\n // A raw index is its marker, whatever its key parts are.\n const raw = firstCol?.INDEX_COMMENT?.startsWith(RAW_INDEX_MARKER_PREFIX)\n ? readRawIndexMarker(\n firstCol.INDEX_COMMENT.slice(RAW_INDEX_MARKER_PREFIX.length),\n indexName\n )\n : undefined;\n if (raw) {\n indexes.push(raw);\n continue;\n }\n if (firstCol) {\n const rawIndexType = firstCol.INDEX_TYPE.toLowerCase();\n // MySQL INFORMATION_SCHEMA reports RTREE for spatial indexes, normalize to \"spatial\"\n const indexType = rawIndexType === \"rtree\" ? \"spatial\" : rawIndexType;\n indexes.push({\n name: indexName,\n columns: indexCols.map((idx) => idx.COLUMN_NAME),\n unique: firstCol.NON_UNIQUE === 0,\n // MySQL uses BTREE, HASH, FULLTEXT, SPATIAL (reported as RTREE) - preserve all supported types\n type:\n indexType === \"btree\" ||\n indexType === \"hash\" ||\n indexType === \"fulltext\" ||\n indexType === \"spatial\"\n ? (indexType as \"btree\" | \"hash\" | \"fulltext\" | \"spatial\")\n : undefined,\n });\n }\n }\n }\n\n // Build foreign keys\n const foreignKeys: ForeignKeyDef[] = [];\n const tableFks = fkByTable.get(tableName);\n if (tableFks) {\n for (const [constraintName, fkCols] of tableFks) {\n fkCols.sort((a, b) => a.ORDINAL_POSITION - b.ORDINAL_POSITION);\n const firstFk = fkCols[0];\n if (firstFk) {\n foreignKeys.push({\n name: constraintName,\n columns: fkCols.map((fk) => fk.COLUMN_NAME),\n referencedTable: firstFk.REFERENCED_TABLE_NAME,\n referencedColumns: fkCols.map((fk) => fk.REFERENCED_COLUMN_NAME),\n onDelete: mapReferentialAction(firstFk.DELETE_RULE),\n onUpdate: mapReferentialAction(firstFk.UPDATE_RULE),\n });\n }\n }\n }\n\n // MySQL HAS ONE UNIQUE NAMESPACE, so a unique is reported ONCE — as an\n // index, above, from STATISTICS. TABLE_CONSTRAINTS lists the very same\n // object a second time (its `UNIQUE` constraint face), and filing that\n // second face here made every unique-bearing MySQL schema churn forever:\n // whichever bucket the desired side did not use looked like a stray object\n // and the differ planned a drop for it (measured on docker MySQL 8 — a\n // spurious `dropIndex` for a declared unique constraint, a spurious\n // `dropUniqueConstraint` for a declared unique index).\n //\n // The desired side is canonicalized to match by the driver's\n // `finalizeTable`, which rewrites every unique constraint into a unique\n // index. Both sides now speak indexes, so a unique round-trips unchanged.\n //\n // The bucket stays in the shape (every dialect's snapshot carries it) and\n // is always empty for MySQL. TABLE_CONSTRAINTS is no longer queried at all:\n // it can report nothing the STATISTICS rows above do not already carry.\n const uniqueConstraints: UniqueConstraintDef[] = [];\n\n tables.push({\n name: tableName,\n columns,\n primaryKey,\n indexes,\n foreignKeys,\n uniqueConstraints,\n });\n }\n\n // A view is VibORM's when its definition ends with the marker. MySQL does\n // not check what a view reads when one is dropped, so its reads are not\n // read here: push takes a declared view's from its declaration.\n const views: ViewDef[] = viewsResult.rows.flatMap((row) => {\n const hash = readViewMarker(row.VIEW_DEFINITION);\n return hash === undefined\n ? []\n : [{ name: row.TABLE_NAME, hash, dependsOn: [] }];\n });\n // A table whose comment is a view's marker holds a view kept by triggers,\n // which is the view and not a table.\n const autoTables: LiveAutoTable[] = [];\n for (const row of tablesResult.rows) {\n const hash = readViewComment(row.TABLE_COMMENT);\n const at = tables.findIndex(({ name }) => name === row.TABLE_NAME);\n if (hash === undefined || at < 0) continue;\n autoTables.push({\n name: row.TABLE_NAME,\n hash,\n indexes: tables[at]!.indexes,\n });\n tables.splice(at, 1);\n }\n if (autoTables.length > 0 || holdsAutoViewBody(views)) {\n // What keeps such a view, or is left of one, is read only where one is.\n const autoKeepersResult = await executeRaw<{\n TRIGGER_NAME: string;\n EVENT_OBJECT_TABLE: string;\n ACTION_STATEMENT: string | null;\n }>(AUTO_KEEPERS_QUERY, scope);\n const keepers = autoKeepersResult.rows.flatMap((row): LiveAutoKeeper[] => {\n const hash = readKeeperMarker(row.ACTION_STATEMENT);\n return hash === undefined\n ? []\n : [\n {\n kind: \"trigger\",\n name: row.TRIGGER_NAME,\n table: row.EVENT_OBJECT_TABLE,\n hash,\n },\n ];\n });\n views.push(...readAutoViews(autoTables, keepers, views));\n views.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n }\n\n // MySQL doesn't have standalone enum types, but we track them for compatibility\n return {\n tables,\n enums: enumDefs.length > 0 ? enumDefs : undefined,\n ...(views.length > 0 ? { views } : {}),\n };\n}\n","/**\n * MySQL pinned migration session: lock identity, exact lock proofs, the one\n * admitted target selection, and the session's exact-value proof.\n *\n * This module is §13's single exempted `USE` producer. Every other `USE` in the\n * shipped source is a defect, and the architecture census enforces that by\n * naming THIS path — `PINNED_ARTIFACT_SESSION_OWNERS` — and nothing else. The\n * exemption is sound only because the statement below can be reached solely\n * from a pinned migration session, where the owner, lifetime, lock, target and\n * cleanup are one physical connection that is destroyed afterwards\n * (`MySQL2Driver.pinnedSession`).\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport type { CatalogRead } from \"../../target\";\n\n/**\n * MySQL's `GET_LOCK` name limit. Longer names are an error on 8.0+ and were\n * silently truncated before, which would have collapsed two databases onto one\n * lock name — the exact accident the hash below prevents.\n */\nconst LOCK_NAME_LIMIT = 64;\n\nconst LOCK_NAME_PREFIX = \"viborm_migration_\";\n\n/** `_` + eight hex digits. */\nconst LOCK_HASH_LENGTH = 9;\n\nconst LOCK_NAME_BUDGET =\n LOCK_NAME_LIMIT - LOCK_NAME_PREFIX.length - LOCK_HASH_LENGTH;\n\n/** Every character MySQL identifiers admit that a lock name should not carry. */\nconst NON_LOCK_NAME_CHARACTERS = /[^a-z0-9_]/g;\n\nconst FNV_OFFSET_BASIS = 0x81_1c_9d_c5;\nconst FNV_PRIME = 0x01_00_01_93;\n\n/**\n * A deterministic 32-bit FNV-1a hash, as eight lowercase hex digits.\n *\n * The lock name has to survive truncation without two databases colliding, and\n * a cryptographic digest would be a runtime dependency for a value nothing\n * secret depends on: this is a collision-spreading suffix, not a secret.\n */\nfunction hashLockScope(value: string): string {\n let hash = FNV_OFFSET_BASIS;\n for (let index = 0; index < value.length; index += 1) {\n // FNV-1a IS an XOR followed by a multiply; any other spelling is a\n // different function.\n // biome-ignore lint/suspicious/noBitwiseOperators: FNV-1a is defined as XOR-then-multiply.\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, FNV_PRIME);\n }\n // The unsigned shift is how JavaScript reads a 32-bit result back as a\n // non-negative integer.\n // biome-ignore lint/suspicious/noBitwiseOperators: reads the 32-bit result as unsigned.\n return (hash >>> 0).toString(16).padStart(8, \"0\");\n}\n\n/**\n * The lock name for one MySQL database.\n *\n * The scope is a CONSERVATIVE lowercase form of the configured database name.\n * Under `lower_case_table_names=1` two spellings of one database are the same\n * database, and letting them take different lock names would let two migration\n * commands run concurrently against it. Lowercasing may also serialize two\n * genuinely distinct case-sensitive databases that differ only in case; that is\n * the deliberate trade — a lock taken too widely is slow, a lock taken too\n * narrowly is wrong.\n *\n * The hash is computed over the WHOLE lowercased name, so two names sharing a\n * truncated prefix still get different locks.\n */\nexport function mysqlMigrationLockName(namespace: string): string {\n const scope = namespace.toLowerCase();\n const readable = scope\n .replace(NON_LOCK_NAME_CHARACTERS, \"_\")\n .slice(0, LOCK_NAME_BUDGET);\n return `${LOCK_NAME_PREFIX}${readable}_${hashLockScope(scope)}`;\n}\n\n/**\n * `GET_LOCK` with a stable `acquired` alias.\n *\n * The alias exists so the caller reads ONE known column instead of guessing at\n * a provider-shaped name built from the expression text.\n */\nexport function mysqlAcquireLockStatement(\n namespace: string,\n timeoutSeconds: number,\n quote: (value: string) => string\n): string {\n return `SELECT GET_LOCK(${quote(mysqlMigrationLockName(namespace))}, ${timeoutSeconds}) AS acquired`;\n}\n\n/** `RELEASE_LOCK` with a stable `released` alias, for the same reason. */\nexport function mysqlReleaseLockStatement(\n namespace: string,\n quote: (value: string) => string\n): string {\n return `SELECT RELEASE_LOCK(${quote(mysqlMigrationLockName(namespace))}) AS released`;\n}\n\n/**\n * The exact arms of a MySQL lock answer.\n *\n * `GET_LOCK` returns `1` when the lock was taken, `0` when the wait timed out,\n * and `NULL` on error. Treating all three as success is what made the previous\n * owner report a timeout as an acquired lock. `RELEASE_LOCK` answers the same\n * three ways about a release.\n *\n * The row itself is provider-shaped data: a value may arrive as a number, as a\n * decimal string (mysql2 returns `BIGINT`-family values as strings when\n * `supportBigNumbers` is on), or not at all. Exactly one row carrying a value\n * that parses to the number 1 is the proof; everything else — `0`, `NULL`, a\n * missing column, a missing row, more than one row, unparseable text — is not.\n */\nexport function mysqlLockAnswer(\n rows: readonly unknown[],\n column: \"acquired\" | \"released\"\n): boolean {\n if (rows.length !== 1) {\n return false;\n }\n const row = rows[0];\n if (typeof row !== \"object\" || row === null) {\n return false;\n }\n const value: unknown = Reflect.get(row, column);\n if (typeof value === \"number\") {\n return value === 1;\n }\n if (typeof value === \"string\") {\n return Number(value) === 1;\n }\n return false;\n}\n\n/**\n * Selects the migration target on the pinned session.\n *\n * Generated MySQL artifacts are database-RELATIVE by design (§13): one estate\n * deploys to `app_dev`, `app_test` and `app_prod`. Executing them verbatim on a\n * connection whose default database is something else lands the migration in\n * that other database, which is why the target is selected here — on the one\n * connection that runs the artifact, immediately before it, every time, never\n * once for the session. A manual artifact is allowed to issue its own `USE`\n * precisely because the next artifact re-selects the target anyway.\n *\n * The identifier is quoted with the migration driver's own quoter, and the name\n * itself passed the ASCII database-name grammar at driver construction.\n */\nexport function mysqlSelectTargetStatement(\n namespace: string,\n quoteIdentifier: (name: string) => string\n): string {\n return `USE ${quoteIdentifier(namespace)}`;\n}\n\nconst MYSQL_VERSION = /^(\\d+)\\.(\\d+)\\.(\\d+)/;\n\n/**\n * PROVES this pinned session fails on an out-of-range value instead of\n * truncating it (plan 3.3), once per session, before any statement it\n * protects: outside a strict mode MySQL stores an overflowing `DECIMAL`\n * clamped, with a warning (measured on 8.4), and migration work runs DDL and\n * manual artifacts outside the ORM's guarded assignments. CHECK constraints\n * must be enforced too (MySQL 8.0.16+).\n */\nexport async function proveMySQLExactValueSession(\n read: CatalogRead,\n estate: string\n): Promise<void> {\n const { rows } = await read<unknown>(\n \"SELECT @@SESSION.sql_mode AS sql_mode, VERSION() AS server_version\"\n );\n const row = rows[0];\n const mode: unknown =\n typeof row === \"object\" && row !== null\n ? Reflect.get(row, \"sql_mode\")\n : undefined;\n const declared = typeof mode === \"string\" ? mode : \"\";\n const serverVersion: unknown =\n typeof row === \"object\" && row !== null\n ? Reflect.get(row, \"server_version\")\n : undefined;\n const renderedVersion =\n typeof serverVersion === \"string\" ? serverVersion : \"<unreported>\";\n if (!supportsEnforcedMySQLChecks(renderedVersion)) {\n throw new MigrationError(\n `MySQL ${renderedVersion} unsupported: fixed-decimal conversions require MySQL 8.0.16+ for enforced CHECK constraints.`,\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n {\n meta: {\n dialect: \"mysql\",\n type: \"unenforced-check-constraints\",\n target: estate,\n },\n }\n );\n }\n const hasStrictMode = declared.split(\",\").some((mode) => {\n const token = mode.trim();\n return token === \"STRICT_TRANS_TABLES\" || token === \"STRICT_ALL_TABLES\";\n });\n if (hasStrictMode) {\n return;\n }\n throw new MigrationError(\n `MySQL sql_mode \"${declared}\" lacks STRICT_TRANS_TABLES or STRICT_ALL_TABLES; enable strict mode.`,\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n {\n meta: {\n dialect: \"mysql\",\n type: \"non-strict-sql-mode\",\n target: estate,\n },\n }\n );\n}\n\n/** MySQL began enforcing CHECK constraints in 8.0.16. */\nfunction supportsEnforcedMySQLChecks(version: string): boolean {\n if (version.toLowerCase().includes(\"mariadb\")) {\n return false;\n }\n const match = MYSQL_VERSION.exec(version);\n if (match === null) {\n return false;\n }\n const major = Number(match[1]);\n const minor = Number(match[2]);\n const patch = Number(match[3]);\n return major > 8 || (major === 8 && (minor > 0 || patch >= 16));\n}\n","import type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport {\n decimalConversionConstraintName,\n mysqlDecimalFitsCatalogCheck,\n mysqlDecimalListFitsCatalogCheck,\n readMysqlDecimalListMarker,\n readStoredDecimalDescriptor,\n} from \"../../decimal\";\nimport type { CatalogRead } from \"../../target\";\n\nconst RESERVED_PREFIX = \"viborm_decimal_\";\nconst RESERVED_NAME = /^viborm_decimal_([sl])_(\\d+)_(\\d+)$/;\nconst CATALOG_CHARACTER_SET_INTRODUCER = /^_[a-zA-Z0-9]+(?=')/;\nconst WHITESPACE = /\\s/;\n\nconst CONSTRAINTS_QUERY =\n \"SELECT tc.TABLE_NAME, tc.CONSTRAINT_NAME, tc.ENFORCED, cc.CHECK_CLAUSE FROM information_schema.TABLE_CONSTRAINTS tc JOIN information_schema.CHECK_CONSTRAINTS cc ON cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME WHERE tc.CONSTRAINT_SCHEMA = ? AND tc.CONSTRAINT_TYPE = 'CHECK' AND LEFT(tc.CONSTRAINT_NAME, 15) = ? ORDER BY tc.TABLE_NAME, tc.CONSTRAINT_NAME\";\n\nconst COLUMNS_QUERY =\n \"SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME, ORDINAL_POSITION\";\n\ninterface ConstraintRow {\n readonly TABLE_NAME: unknown;\n readonly CONSTRAINT_NAME: unknown;\n readonly ENFORCED: unknown;\n readonly CHECK_CLAUSE: unknown;\n}\n\ninterface ColumnRow {\n readonly TABLE_NAME: unknown;\n readonly COLUMN_NAME: unknown;\n readonly DATA_TYPE: unknown;\n readonly COLUMN_COMMENT: unknown;\n}\n\ninterface ProvenConstraint {\n readonly tableName: string;\n readonly constraintName: string;\n}\n\ninterface RecoveryColumn {\n readonly name: string;\n readonly dataType: string;\n readonly comment: string;\n}\n\nfunction refuseReservedConstraint(\n constraintName: string,\n tableName: string,\n reason: string\n): never {\n throw new MigrationError(\n `MySQL CHECK \"${constraintName}\" on \"${tableName}\" invalid reserved decimal proof: ${reason}.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n dialect: \"mysql\",\n type: \"decimal-conversion-constraint-collision\",\n table: tableName,\n constraint: constraintName,\n },\n }\n );\n}\n\nfunction readString(\n value: unknown,\n constraintName: string,\n tableName: string,\n field: string\n): string {\n if (typeof value === \"string\") return value;\n refuseReservedConstraint(\n constraintName,\n tableName,\n `its catalog ${field} is not a string`\n );\n}\n\n/**\n * MySQL stores CHECK clauses in a normalized spelling: keywords are lower-case,\n * redundant grouping parentheses are added, `CHARACTER SET` becomes `CHARSET`,\n * and string literals acquire a connection-character-set introducer. These are\n * presentation changes only. Removing precisely those tokens leaves the exact\n * generated expression comparable without accepting another predicate.\n */\nfunction normalizeCheckClause(clause: string): string {\n // CHECK_CLAUSE escapes each catalog-rendered string delimiter as `\\'` on\n // mysql2. None of VibORM's fixed proof literals contains an apostrophe, so\n // this removes only the provider's delimiter escape, never literal content.\n const rendered = clause.replaceAll(\"\\\\'\", \"'\");\n let normalized = \"\";\n let index = 0;\n while (index < rendered.length) {\n const char = rendered[index];\n if (char === \"'\") {\n const start = index;\n index++;\n while (index < rendered.length) {\n if (rendered[index] === \"\\\\\" && index + 1 < rendered.length) {\n index += 2;\n continue;\n }\n if (rendered[index] === \"'\" && rendered[index + 1] === \"'\") {\n index += 2;\n continue;\n }\n if (rendered[index] === \"'\") {\n index++;\n break;\n }\n index++;\n }\n normalized += rendered.slice(start, index);\n continue;\n }\n if (char === \"`\") {\n const end = rendered.indexOf(\"`\", index + 1);\n if (end < 0) return clause;\n normalized += rendered.slice(index, end + 1);\n index = end + 1;\n continue;\n }\n if (WHITESPACE.test(char ?? \"\")) {\n index++;\n continue;\n }\n if (char === \"_\") {\n const introducer = CATALOG_CHARACTER_SET_INTRODUCER.exec(\n rendered.slice(index)\n );\n if (introducer !== null) {\n index += introducer[0].length;\n continue;\n }\n }\n normalized += char?.toLowerCase() ?? \"\";\n index++;\n }\n return normalized;\n}\n\nfunction expectedConstraint(\n column: RecoveryColumn,\n kind: \"s\" | \"l\",\n descriptor: DecimalDescriptor\n): string {\n const quotedColumn = `\\`${column.name}\\``;\n return kind === \"s\"\n ? mysqlDecimalFitsCatalogCheck(\n quotedColumn,\n `DECIMAL(${descriptor.precision},${descriptor.scale})`\n )\n : mysqlDecimalListFitsCatalogCheck(quotedColumn, descriptor);\n}\n\nfunction readDescriptor(\n match: RegExpExecArray,\n constraintName: string,\n tableName: string\n): DecimalDescriptor {\n const descriptor = readStoredDecimalDescriptor(match[2], match[3], \"mysql\");\n if (descriptor === undefined) {\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its name declares a decimal domain this provider does not admit\"\n );\n }\n const kind = match[1] === \"s\" ? \"scalar\" : \"list\";\n if (decimalConversionConstraintName(kind, descriptor) !== constraintName) {\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its name is not the canonical spelling of its decimal proof\"\n );\n }\n return descriptor;\n}\n\nfunction proveConstraint(\n row: ConstraintRow,\n columnsByTable: ReadonlyMap<string, readonly RecoveryColumn[]>\n): ProvenConstraint {\n const rawName =\n typeof row.CONSTRAINT_NAME === \"string\"\n ? row.CONSTRAINT_NAME\n : \"<unreported>\";\n const rawTable =\n typeof row.TABLE_NAME === \"string\" ? row.TABLE_NAME : \"<unreported>\";\n const constraintName = readString(\n row.CONSTRAINT_NAME,\n rawName,\n rawTable,\n \"CONSTRAINT_NAME\"\n );\n const tableName = readString(\n row.TABLE_NAME,\n constraintName,\n rawTable,\n \"TABLE_NAME\"\n );\n const clause = readString(\n row.CHECK_CLAUSE,\n constraintName,\n tableName,\n \"CHECK_CLAUSE\"\n );\n const enforced = readString(\n row.ENFORCED,\n constraintName,\n tableName,\n \"ENFORCED\"\n );\n if (enforced !== \"YES\") {\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its CHECK is not enforced\"\n );\n }\n const nameMatch = RESERVED_NAME.exec(constraintName);\n if (nameMatch === null) {\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its name does not match the complete reserved proof identity\"\n );\n }\n const kind = nameMatch[1] === \"s\" ? \"s\" : \"l\";\n const descriptor = readDescriptor(nameMatch, constraintName, tableName);\n\n const columns = columnsByTable.get(tableName) ?? [];\n const actualClause = normalizeCheckClause(clause);\n for (const column of columns) {\n const expected = expectedConstraint(column, kind, descriptor);\n if (normalizeCheckClause(expected) !== actualClause) continue;\n if (kind === \"s\") {\n if (\n column.dataType === \"decimal\" ||\n column.dataType === \"int\" ||\n column.dataType === \"bigint\"\n ) {\n return { tableName, constraintName };\n }\n refuseReservedConstraint(\n constraintName,\n tableName,\n `its scalar proof is attached to impossible ${column.dataType} storage`\n );\n }\n if (column.dataType !== \"json\") {\n refuseReservedConstraint(\n constraintName,\n tableName,\n `its list proof is attached to impossible ${column.dataType} storage`\n );\n }\n let current: DecimalDescriptor | undefined;\n try {\n current = readMysqlDecimalListMarker(column.comment);\n } catch {\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its JSON column carries an invalid decimal-list marker\"\n );\n }\n if (\n current !== undefined &&\n current.scale === descriptor.scale &&\n current.precision >= descriptor.precision\n ) {\n return { tableName, constraintName };\n }\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its JSON column does not carry a compatible source or target decimal-list marker\"\n );\n }\n\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its concrete CHECK predicate does not match that proof identity\"\n );\n}\n\nfunction groupColumns(\n rows: readonly ColumnRow[]\n): Map<string, RecoveryColumn[]> {\n const columnsByTable = new Map<string, RecoveryColumn[]>();\n for (const row of rows) {\n const tableName = typeof row.TABLE_NAME === \"string\" ? row.TABLE_NAME : \"\";\n const columnName =\n typeof row.COLUMN_NAME === \"string\" ? row.COLUMN_NAME : \"\";\n const dataType = typeof row.DATA_TYPE === \"string\" ? row.DATA_TYPE : \"\";\n const comment =\n typeof row.COLUMN_COMMENT === \"string\" ? row.COLUMN_COMMENT : \"\";\n if (tableName === \"\" || columnName === \"\" || dataType === \"\") continue;\n const columns = columnsByTable.get(tableName) ?? [];\n columns.push({\n name: columnName,\n dataType: dataType.toLowerCase(),\n comment,\n });\n columnsByTable.set(tableName, columns);\n }\n return columnsByTable;\n}\n\n/**\n * Plans the removal of authenticated remnants of a MySQL decimal conversion.\n *\n * The migration lock excludes another VibORM command. Every reserved row is\n * proven before the first DROP is returned, so a user-owned collision or a\n * malformed catalog answer cannot make cleanup partially mutate the estate.\n * Execution belongs to the sequential-program owner: MySQL can commit a DROP\n * before reporting a connection failure, and only that owner can state the\n * resulting uncertain boundary honestly.\n */\nexport async function planInterruptedMySQLDecimalRecovery(\n read: CatalogRead,\n namespace: string,\n quoteIdentifier: (name: string) => string\n): Promise<readonly string[]> {\n const { rows } = await read<ConstraintRow>(CONSTRAINTS_QUERY, [\n namespace,\n RESERVED_PREFIX,\n ]);\n if (rows.length === 0) return [];\n if (rows.length > 1) {\n const first = rows[0];\n refuseReservedConstraint(\n typeof first?.CONSTRAINT_NAME === \"string\"\n ? first.CONSTRAINT_NAME\n : \"<unreported>\",\n typeof first?.TABLE_NAME === \"string\" ? first.TABLE_NAME : \"<unreported>\",\n `the catalog contains ${rows.length} reserved proofs, although one locked conversion can leave at most one`\n );\n }\n\n const columns = await read<ColumnRow>(COLUMNS_QUERY, [namespace]);\n const columnsByTable = groupColumns(columns.rows);\n const proven = rows.map((row) => proveConstraint(row, columnsByTable));\n\n return proven.map(\n (constraint) =>\n `ALTER TABLE ${quoteIdentifier(namespace)}.${quoteIdentifier(constraint.tableName)} DROP CHECK ${quoteIdentifier(constraint.constraintName)}`\n );\n}\n","/**\n * Lightweight MySQL Runtime Migration Driver\n *\n * Implements only what live migration execution (`apply`, `status`, `verify`,\n * `log`) needs: introspection, database namespace proof, named locks, strict\n * session proof, interrupted decimal recovery, preflight, and adoption hazards.\n *\n * Imports ZERO DDL generators, ZERO `MySQLAdapter`, ZERO `compile.ts`,\n * ZERO `native-rename.ts`, ZERO `drivers/base.ts`.\n */\n\nimport { mysqlStringLiteral } from \"../../../adapters/databases/mysql/string-literal\";\nimport type { AnyDriver } from \"../../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport type { CatalogRead, CommandNamespaceResolver } from \"../../target\";\nimport type { SchemaSnapshot } from \"../../types\";\nimport {\n type LiveRelation,\n refuseRelationCollision,\n viewRelationNames,\n} from \"../../view\";\nimport { type AdoptionHazard, RuntimeMigrationDriver } from \"../runtime-base\";\nimport type { MigrationCapabilities } from \"../types\";\nimport { type CatalogReader, resolveCatalogNamespace } from \"./catalog\";\nimport { mysqlControlDialect } from \"./control\";\nimport { planInterruptedMySQLDecimalRecovery } from \"./decimal-recovery\";\nimport { introspect as introspectMySQL } from \"./introspect\";\nimport {\n mysqlAcquireLockStatement,\n mysqlLockAnswer,\n mysqlReleaseLockStatement,\n mysqlSelectTargetStatement,\n proveMySQLExactValueSession,\n} from \"./pinned-session\";\nimport { runSequentialProgram } from \"./sequential-program\";\n\nexport const MYSQL_TABLE_ENGINE = \"InnoDB\";\nexport const MYSQL_TABLE_COLLATION = \"utf8mb4_0900_bin\";\nexport const MYSQL_LOCK_TIMEOUT_SECONDS = 30;\n\nexport const MYSQL_CAPABILITIES: MigrationCapabilities = {\n supportsNativeEnums: true,\n supportsAddEnumValueInTransaction: false,\n supportsIndexTypes: [\"btree\", \"fulltext\", \"spatial\"],\n supportsNativeArrays: false,\n supportsAddForeignKeyViaAlter: true,\n introspectionReadsConstraintNames: true,\n};\n\nexport function mysqlRequireLockScope(\n driver: Pick<RuntimeMigrationDriver, \"namespace\">\n): string {\n if (driver.namespace === undefined) {\n throw new MigrationError(\n \"MySQL migration driver is not bound to a database; configure namespace or database.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: \"mysql\", type: \"unbound-database\" } }\n );\n }\n return driver.namespace;\n}\n\nexport async function mysqlPreflightSchemaRequirements(\n driver: Pick<RuntimeMigrationDriver, \"namespace\">,\n snapshots: readonly SchemaSnapshot[],\n executeRaw: CatalogReader\n): Promise<boolean> {\n const names = new Set(\n snapshots.flatMap((snapshot) => [\n ...snapshot.tables.map((table) => table.name),\n ...(snapshot.views ?? []).flatMap(viewRelationNames),\n ])\n );\n if (names.size === 0) return false;\n const namespace = await resolveCatalogNamespace(executeRaw, driver.namespace);\n const relations = await executeRaw<{\n TABLE_NAME: string;\n TABLE_TYPE: string;\n VIEW_DEFINITION: string | null;\n TABLE_COMMENT: string | null;\n }>(\n \"SELECT t.TABLE_NAME, t.TABLE_TYPE, v.VIEW_DEFINITION, t.TABLE_COMMENT FROM information_schema.TABLES t LEFT JOIN information_schema.VIEWS v ON v.TABLE_SCHEMA = t.TABLE_SCHEMA AND v.TABLE_NAME = t.TABLE_NAME WHERE t.TABLE_SCHEMA = ?\",\n [namespace]\n );\n refuseRelationCollision(\n \"MySQL\",\n snapshots,\n relations.rows.flatMap((row): LiveRelation[] =>\n names.has(row.TABLE_NAME)\n ? [\n {\n name: row.TABLE_NAME,\n kind: row.TABLE_TYPE === \"VIEW\" ? \"view\" : \"table\",\n definition: row.VIEW_DEFINITION,\n comment: row.TABLE_COMMENT ?? undefined,\n },\n ]\n : []\n )\n );\n return false;\n}\n\nexport async function mysqlAdoptionHazards(\n driver: Pick<RuntimeMigrationDriver, \"namespace\">,\n tables: readonly string[],\n executeRaw: CatalogReader\n): Promise<readonly AdoptionHazard[]> {\n if (tables.length === 0) return [];\n const namespace = await resolveCatalogNamespace(executeRaw, driver.namespace);\n const placeholders = tables.map(() => \"?\").join(\", \");\n const scope = [namespace, ...tables];\n const shapes = await executeRaw<{\n tbl: string;\n ENGINE: string | null;\n TABLE_COLLATION: string | null;\n }>(\n `SELECT TABLE_NAME AS tbl, ENGINE, TABLE_COLLATION FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME IN (${placeholders})`,\n scope\n );\n const triggers = await executeRaw<{ tbl: string; name: string }>(\n `SELECT EVENT_OBJECT_TABLE AS tbl, TRIGGER_NAME AS name FROM information_schema.TRIGGERS WHERE EVENT_OBJECT_SCHEMA = ? AND EVENT_OBJECT_TABLE IN (${placeholders}) ORDER BY TRIGGER_NAME`,\n scope\n );\n const checks = await executeRaw<{ tbl: string; name: string }>(\n `SELECT TABLE_NAME AS tbl, CONSTRAINT_NAME AS name FROM information_schema.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA = ? AND TABLE_NAME IN (${placeholders}) AND CONSTRAINT_TYPE = 'CHECK' ORDER BY CONSTRAINT_NAME`,\n scope\n );\n const collated = await executeRaw<{ tbl: string; name: string }>(\n `SELECT TABLE_NAME AS tbl, COLUMN_NAME AS name FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME IN (${placeholders}) AND COLLATION_NAME IS NOT NULL AND COLLATION_NAME <> ? ORDER BY ORDINAL_POSITION`,\n [...scope, MYSQL_TABLE_COLLATION]\n );\n const shapeByTable = new Map(shapes.rows.map((r) => [r.tbl, r]));\n const group = (rows: readonly { tbl: string; name: string }[]) => {\n const map = new Map<string, string[]>();\n for (const row of rows) {\n let bucket = map.get(row.tbl);\n if (!bucket) {\n bucket = [];\n map.set(row.tbl, bucket);\n }\n bucket.push(row.name);\n }\n return map;\n };\n const triggersByTable = group(triggers.rows);\n const checksByTable = group(checks.rows);\n const collatedByTable = group(collated.rows);\n const hazards: AdoptionHazard[] = [];\n for (const table of tables) {\n const shape = shapeByTable.get(table);\n const features = [\n ...(triggersByTable.get(table) ?? []).map((name) => `trigger \"${name}\"`),\n ...(checksByTable.get(table) ?? []).map(\n (name) => `CHECK constraint \"${name}\"`\n ),\n ...(shape?.ENGINE && shape.ENGINE !== MYSQL_TABLE_ENGINE\n ? [`ENGINE=${shape.ENGINE}`]\n : []),\n ...(shape?.TABLE_COLLATION &&\n shape.TABLE_COLLATION !== MYSQL_TABLE_COLLATION\n ? [`the table collation ${shape.TABLE_COLLATION}`]\n : []),\n ...(collatedByTable.get(table) ?? []).map(\n (name) => `a collation on column \"${name}\"`\n ),\n ];\n hazards.push(...features.map((feature) => ({ table, feature })));\n }\n return hazards;\n}\n\nexport async function mysqlProveSession<T extends RuntimeMigrationDriver>(\n driver: T,\n read: CatalogRead\n): Promise<T> {\n await proveMySQLExactValueSession(\n read,\n `database \"${driver.namespace ?? \"(unbound)\"}\"`\n );\n const namespace = mysqlRequireLockScope(driver);\n let taken = false;\n let planned: Promise<readonly string[]> | undefined;\n const command: T = Object.create(driver);\n Object.defineProperty(command, \"programPreamble\", {\n value: async (producer: AnyDriver): Promise<readonly string[]> => {\n if (taken) return [];\n if (planned !== undefined) {\n await planned;\n return [];\n }\n planned = planInterruptedMySQLDecimalRecovery(\n (sql, params) => producer._executeRaw(sql, params),\n namespace,\n (name) => driver.escapeIdentifier(name)\n );\n try {\n const statements = await planned;\n taken = true;\n return statements;\n } catch (error) {\n planned = undefined;\n throw error;\n }\n },\n });\n Object.freeze(command);\n return command;\n}\n\nexport function mysqlUnboundProgramPreamble(): Promise<readonly string[]> {\n return Promise.reject(\n new MigrationError(\n \"MySQL sequential program is not bound to a locked command's recovery scope.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: \"mysql\", type: \"unbound-migration-command\" } }\n )\n );\n}\n\nexport class MySQLRuntimeMigrationDriver\n extends RuntimeMigrationDriver\n implements CommandNamespaceResolver\n{\n readonly dialect = \"mysql\" as const;\n readonly driverName = \"mysql\";\n readonly capabilities: MigrationCapabilities = MYSQL_CAPABILITIES;\n override readonly controlDialect = mysqlControlDialect;\n override readonly runSequentialProgram = runSequentialProgram;\n\n escapeIdentifier(name: string): string {\n if (name == null) {\n throw new MigrationError(\n \"Cannot escape null or undefined identifier\",\n VibORMErrorCode.INVALID_INPUT\n );\n }\n return `\\`${String(name).replace(/`/g, \"``\")}\\``;\n }\n\n introspect(executeRaw: CatalogReader): Promise<SchemaSnapshot> {\n return introspectMySQL(executeRaw, this.namespace, this.target?.tables);\n }\n\n override preflightSchemaRequirements(\n snapshots: readonly SchemaSnapshot[],\n executeRaw: CatalogReader\n ): Promise<boolean> {\n return mysqlPreflightSchemaRequirements(this, snapshots, executeRaw);\n }\n\n override adoptionHazards(\n tables: readonly string[],\n executeRaw: CatalogReader\n ): Promise<readonly AdoptionHazard[]> {\n return mysqlAdoptionHazards(this, tables, executeRaw);\n }\n\n override async proveNamespaceExists(\n executeRaw: CatalogReader\n ): Promise<void> {\n await this.resolveCommandNamespace(executeRaw);\n }\n\n async resolveCommandNamespace(read: CatalogRead): Promise<string> {\n return await resolveCatalogNamespace(read, this.namespace);\n }\n\n generateAcquireLock(_lockId: number): string | null {\n return mysqlAcquireLockStatement(\n mysqlRequireLockScope(this),\n MYSQL_LOCK_TIMEOUT_SECONDS,\n (value) => mysqlStringLiteral(value)\n );\n }\n\n generateReleaseLock(_lockId: number): string | null {\n return mysqlReleaseLockStatement(mysqlRequireLockScope(this), (value) =>\n mysqlStringLiteral(value)\n );\n }\n\n override provesLockAcquired(rows: readonly unknown[]): boolean {\n return mysqlLockAnswer(rows, \"acquired\");\n }\n\n override provesLockReleased(rows: readonly unknown[]): boolean {\n return mysqlLockAnswer(rows, \"released\");\n }\n\n override generateSelectTarget(): string | null {\n if (this.namespace === undefined) {\n return null;\n }\n return mysqlSelectTargetStatement(this.namespace, (name) =>\n this.escapeIdentifier(name)\n );\n }\n\n override proveSession(read: CatalogRead): Promise<this> {\n return mysqlProveSession(this, read);\n }\n\n override programPreamble(): Promise<readonly string[]> {\n return mysqlUnboundProgramPreamble();\n }\n}\n\nexport const mysqlRuntimeMigrationDriver = new MySQLRuntimeMigrationDriver();\n"],"mappings":"8lBAgBA,MAAM,EAAiB,IAAuB,CAC5C,QAAS,QACT,YACD,EAsED,eAAsB,EACpB,EACA,EACiB,CACjB,GAAI,IAAc,IAAA,GAChB,MAAM,IAAI,EACR,uEACA,SACA,CAAE,KAAM,CAAE,QAAS,QAAS,KAAM,mBAAoB,CAAC,CACxD,CAGH,GAAM,CAAE,QAAS,MAAM,EAAwB;;;;;EAAgB,CAAC,EAAU,CAAC,CACrE,EAAa,EAChB,IAAK,GAAQ,EAAI,YAAW,CAC5B,OAAQ,GAAyB,OAAO,GAAS,SAAS,CAE7D,GAAI,EAAW,SAAW,EACxB,MAAM,IAAI,EACR,mBAAmB,EAAU,qCAC7B,SACA,CAAE,KAAM,CAAE,GAAG,EAAc,EAAU,CAAE,KAAM,mBAAoB,CAAC,CACnE,CAGH,IAAM,EAAQ,EAAW,KAAM,GAAc,IAAc,EAAU,CACrE,GAAI,IAAU,IAAA,GAAW,OAAO,EAEhC,GAAM,CAAC,GAAU,EACjB,GAAI,EAAW,SAAW,GAAK,IAAW,IAAA,GAAW,OAAO,EAE5D,MAAM,IAAI,EACR,mBAAmB,EAAU,YAAY,EAAW,OAAO,2BAA2B,EAAW,KAAK,KAAK,CAAC,0BAC5G,SACA,CACE,KAAM,CACJ,GAAG,EAAc,EAAU,CAC3B,KAAM,qBACN,aACD,CACH,CACD,CCjHH,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C,CAGH,oBAAoB,EAAgC,CAClD,OAAO,EAA0B,EAAsB,KAAK,CAAG,GAC7D,EAAmB,EAAK,CACzB,CAGH,mBAA4B,EAAmC,CAC7D,OAAO,EAAgB,EAAM,WAAW,CAG1C,mBAA4B,EAAmC,CAC7D,OAAO,EAAgB,EAAM,WAAW,CAG1C,sBAA+C,CAI7C,OAHI,KAAK,YAAc,IAAA,GACd,KAEF,EAA2B,KAAK,UAAY,GACjD,KAAK,iBAAiB,EAAI,CAC3B,CAGH,aAAsB,EAAkC,CACtD,OAAO,GAAkB,KAAM,EAAK,CAGtC,iBAAuD,CACrD,OAAO,IAA6B"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { s as MigrationLimits, t as MigrationClient } from "./client-driver-DuQy6lsN.mjs";
|
|
2
|
+
import { t as MigrationStorageReader } from "./contract-CAoFgKSO.mjs";
|
|
3
|
+
import { a as ApplyV1Options, f as LedgerEventV1, n as StatusV1Result, r as ApplyV1Result, t as VerifyV1Result } from "./verify-v1-CJFrJ4lx.mjs";
|
|
4
|
+
|
|
5
|
+
//#region src/migrations/runtime-client.d.ts
|
|
6
|
+
|
|
7
|
+
interface RuntimeMigrationClientOptions {
|
|
8
|
+
readonly storage: MigrationStorageReader;
|
|
9
|
+
readonly tables?: readonly string[];
|
|
10
|
+
readonly limits?: MigrationLimits;
|
|
11
|
+
}
|
|
12
|
+
interface RuntimeMigrationLogOptions {
|
|
13
|
+
readonly tables?: readonly string[];
|
|
14
|
+
readonly limits?: MigrationLimits;
|
|
15
|
+
}
|
|
16
|
+
interface RuntimeMigrations {
|
|
17
|
+
status(): Promise<StatusV1Result>;
|
|
18
|
+
verify(): Promise<VerifyV1Result>;
|
|
19
|
+
log(): Promise<readonly LedgerEventV1[]>;
|
|
20
|
+
apply(options?: ApplyV1Options): Promise<ApplyV1Result>;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Creates a lightweight runtime-only migration client (`status`, `apply`,
|
|
24
|
+
* `verify`, `log`) for production Workers and application servers.
|
|
25
|
+
*/
|
|
26
|
+
declare function createRuntimeMigrationClient(client: MigrationClient, options: RuntimeMigrationClientOptions): RuntimeMigrations;
|
|
27
|
+
/** Tree-shakable standalone `status()` for minimal runtime bundles. */
|
|
28
|
+
declare function getMigrationStatus(client: MigrationClient, options: RuntimeMigrationClientOptions): Promise<StatusV1Result>;
|
|
29
|
+
/** Tree-shakable standalone `apply()` for minimal runtime bundles. */
|
|
30
|
+
declare function applyMigrations(client: MigrationClient, options: RuntimeMigrationClientOptions & {
|
|
31
|
+
readonly apply?: ApplyV1Options;
|
|
32
|
+
}): Promise<ApplyV1Result>;
|
|
33
|
+
/** Tree-shakable standalone `verify()` for minimal runtime bundles. */
|
|
34
|
+
declare function verifyMigrations(client: MigrationClient, options: RuntimeMigrationClientOptions): Promise<VerifyV1Result>;
|
|
35
|
+
/** Tree-shakable standalone `log()` for minimal runtime bundles. */
|
|
36
|
+
declare function getMigrationLog(client: MigrationClient, options?: RuntimeMigrationLogOptions): Promise<readonly LedgerEventV1[]>;
|
|
37
|
+
//#endregion
|
|
38
|
+
export { createRuntimeMigrationClient as a, verifyMigrations as c, applyMigrations as i, RuntimeMigrationLogOptions as n, getMigrationLog as o, RuntimeMigrations as r, getMigrationStatus as s, RuntimeMigrationClientOptions as t };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{M as e}from"./error-mapping-B9rSvgG9.mjs";import{b as t}from"./base-17NSFtrA.mjs";import{t as n}from"./migrations-DIUltjr3.mjs";import{H as r,L as i,R as a,_t as o,gn as s,vn as c}from"./push-fingerprint-CegYVFFp.mjs";import{a as l,i as u,o as d,r as f,t as p}from"./contract-BBone8RD.mjs";function m(e,t){throw new n(e,`V4002`,{cause:t})}function h(e){if(e.$driver.dialect===`snowflake`)throw new n(`Snowflake has no migrations: VibORM only reads it (introspectSchema() reads its schema).`,`V8001`,{meta:{dialect:`snowflake`}})}function g(e){let n;try{n=p(e)}catch(e){return m(`migration client storage could not be inspected`,t(e))}return n?e:m(`migration client storage must implement MigrationStorageReader`)}function _(t,n){let o=r(n?.tables),c=n?.limits===void 0?void 0:s(n.limits);return o===void 0&&c===void 0?t:{$driver:t.$driver,$schema:t.$schema,[i]:o,[a]:c,[e]:t[e]}}function v(e,t){return t.catch(t=>{throw o(t,{step:e})})}function y(e,t,n=[`storage`,`tables`,`limits`]){h(e);let r=c(t,n,`migration client options`,m);return{bound:_(e,r),storage:g(r.storage),record:r}}function b(e,t){let{bound:n,storage:r}=y(e,t);return Object.freeze({status:()=>u(n,r),verify:()=>f(n,r),log:()=>l(n),apply:e=>v(`apply`,d(n,r,e))})}function x(e,t){let{bound:n,storage:r}=y(e,t);return u(n,r)}function S(e,t){let{bound:n,storage:r,record:i}=y(e,t,[`storage`,`tables`,`limits`,`apply`]);return v(`apply`,d(n,r,i.apply))}function C(e,t){let{bound:n,storage:r}=y(e,t);return f(n,r)}function w(e,t){return h(e),l(_(e,t===void 0?void 0:c(t,[`tables`,`limits`],`migration client options`,m)))}export{C as a,x as i,b as n,w as r,S as t};
|
|
2
|
+
//# sourceMappingURL=runtime-client-xeiXA_1m.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime-client-xeiXA_1m.mjs","names":[],"sources":["../src/migrations/runtime-client.ts"],"sourcesContent":["/**\n * Runtime-only Migration V1 client and tree-shakable operation entrypoints.\n *\n * Exposes only live production runtime operations (`status`, `apply`, `verify`,\n * `log`) without importing authoring, diffing, serialization, DDL compilation,\n * push, reset, rollback, prune, or cross-dialect drivers.\n */\n\nimport { CLIENT_DIAGNOSTICS } from \"../drivers/execution-context\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport { type ApplyV1Result, applyV1 } from \"./apply-v1\";\nimport type { MigrationClient } from \"./client-driver\";\nimport { annotateMigrationFailure } from \"./execute-dispatch\";\nimport { snapshotExactRecord } from \"./input-boundary\";\nimport { type MigrationLimits, resolveMigrationLimits } from \"./limits\";\nimport { logV1 } from \"./log-v1\";\nimport { type StatusV1Result, statusV1 } from \"./status-v1\";\nimport {\n isMigrationStorageReader,\n type MigrationStorageReader,\n} from \"./storage/contract\";\nimport {\n MANAGED_TABLES,\n MIGRATION_LIMITS,\n normalizeManagedTables,\n} from \"./target\";\nimport type { ApplyV1Options, LedgerEventV1 } from \"./v1-types\";\nimport { type VerifyV1Result, verifyV1 } from \"./verify-v1\";\n\nexport interface RuntimeMigrationClientOptions {\n readonly storage: MigrationStorageReader;\n readonly tables?: readonly string[];\n readonly limits?: MigrationLimits;\n}\n\nexport interface RuntimeMigrationLogOptions {\n readonly tables?: readonly string[];\n readonly limits?: MigrationLimits;\n}\n\nexport interface RuntimeMigrations {\n status(): Promise<StatusV1Result>;\n verify(): Promise<VerifyV1Result>;\n log(): Promise<readonly LedgerEventV1[]>;\n apply(options?: ApplyV1Options): Promise<ApplyV1Result>;\n}\n\nfunction refuseRuntimeOptions(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n\nfunction refuseSnowflake(client: MigrationClient): void {\n if (client.$driver.dialect === \"snowflake\") {\n throw new MigrationError(\n \"Snowflake has no migrations: VibORM only reads it (introspectSchema() reads its schema).\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { dialect: \"snowflake\" } }\n );\n }\n}\n\nfunction readStorage(storage: unknown): MigrationStorageReader {\n let valid: boolean;\n try {\n valid = isMigrationStorageReader(storage);\n } catch (failure) {\n return refuseRuntimeOptions(\n \"migration client storage could not be inspected\",\n errorCause(failure)\n );\n }\n if (!valid) {\n return refuseRuntimeOptions(\n \"migration client storage must implement MigrationStorageReader\"\n );\n }\n return storage as MigrationStorageReader;\n}\n\nfunction bindClient(\n client: MigrationClient,\n record: Readonly<Record<string, unknown>> | undefined\n): MigrationClient {\n const tables = normalizeManagedTables(\n record?.tables as readonly string[] | undefined\n );\n const limits =\n record?.limits === undefined\n ? undefined\n : resolveMigrationLimits(record.limits as MigrationLimits);\n if (tables === undefined && limits === undefined) return client;\n return {\n $driver: client.$driver,\n $schema: client.$schema,\n [MANAGED_TABLES]: tables,\n [MIGRATION_LIMITS]: limits,\n [CLIENT_DIAGNOSTICS]: client[CLIENT_DIAGNOSTICS],\n };\n}\n\nfunction named<T>(step: string, promise: Promise<T>): Promise<T> {\n return promise.catch((failure: unknown) => {\n throw annotateMigrationFailure(failure, { step });\n });\n}\n\nfunction parseRuntimeOptions(\n client: MigrationClient,\n options: RuntimeMigrationClientOptions,\n allowed: readonly string[] = [\"storage\", \"tables\", \"limits\"]\n): {\n readonly bound: MigrationClient;\n readonly storage: MigrationStorageReader;\n readonly record: Readonly<Record<string, unknown>>;\n} {\n refuseSnowflake(client);\n const record = snapshotExactRecord(\n options,\n allowed,\n \"migration client options\",\n refuseRuntimeOptions\n );\n return {\n bound: bindClient(client, record),\n storage: readStorage(record.storage),\n record,\n };\n}\n\n/**\n * Creates a lightweight runtime-only migration client (`status`, `apply`,\n * `verify`, `log`) for production Workers and application servers.\n */\nexport function createRuntimeMigrationClient(\n client: MigrationClient,\n options: RuntimeMigrationClientOptions\n): RuntimeMigrations {\n const { bound, storage } = parseRuntimeOptions(client, options);\n return Object.freeze({\n status: () => statusV1(bound, storage),\n verify: () => verifyV1(bound, storage),\n log: () => logV1(bound),\n apply: (applyOptions) =>\n named(\"apply\", applyV1(bound, storage, applyOptions)),\n });\n}\n\n/** Tree-shakable standalone `status()` for minimal runtime bundles. */\nexport function getMigrationStatus(\n client: MigrationClient,\n options: RuntimeMigrationClientOptions\n): Promise<StatusV1Result> {\n const { bound, storage } = parseRuntimeOptions(client, options);\n return statusV1(bound, storage);\n}\n\n/** Tree-shakable standalone `apply()` for minimal runtime bundles. */\nexport function applyMigrations(\n client: MigrationClient,\n options: RuntimeMigrationClientOptions & {\n readonly apply?: ApplyV1Options;\n }\n): Promise<ApplyV1Result> {\n const { bound, storage, record } = parseRuntimeOptions(client, options, [\n \"storage\",\n \"tables\",\n \"limits\",\n \"apply\",\n ]);\n return named(\n \"apply\",\n applyV1(bound, storage, record.apply as ApplyV1Options | undefined)\n );\n}\n\n/** Tree-shakable standalone `verify()` for minimal runtime bundles. */\nexport function verifyMigrations(\n client: MigrationClient,\n options: RuntimeMigrationClientOptions\n): Promise<VerifyV1Result> {\n const { bound, storage } = parseRuntimeOptions(client, options);\n return verifyV1(bound, storage);\n}\n\n/** Tree-shakable standalone `log()` for minimal runtime bundles. */\nexport function getMigrationLog(\n client: MigrationClient,\n options?: RuntimeMigrationLogOptions\n): Promise<readonly LedgerEventV1[]> {\n refuseSnowflake(client);\n const record =\n options === undefined\n ? undefined\n : snapshotExactRecord(\n options,\n [\"tables\", \"limits\"],\n \"migration client options\",\n refuseRuntimeOptions\n );\n return logV1(bindClient(client, record));\n}\n"],"mappings":"ySAgDA,SAAS,EAAqB,EAAiB,EAAsB,CACnE,MAAM,IAAI,EAAe,EAAS,QAAA,CAAA,QAAgB,CAAA,CAGpD,SAAS,EAAgB,EAA+B,CACtD,GAAI,EAAO,QAAQ,UAAY,YAC7B,MAAM,IAAI,EACR,2FACA,QACA,CAAE,KAAM,CAAE,QAAS,YAAa,CAAC,CAClC,CAIL,SAAS,EAAY,EAA0C,CAC7D,IAAI,EACJ,GAAI,CACF,EAAQ,EAAyB,EAAQ,OAClC,EAAS,CAChB,OAAO,EACL,kDACA,EAAW,EAAO,CACnB,CAOH,OALK,EAKE,EAJE,EACL,iEACD,CAKL,SAAS,EACP,EACA,EACiB,CACjB,IAAM,EAAS,EACb,GAAQ,OACT,CACK,EACJ,GAAQ,SAAW,IAAA,GACf,IAAA,GACA,EAAuB,EAAO,OAA0B,CAE9D,OADI,IAAW,IAAA,IAAa,IAAW,IAAA,GAAkB,EAClD,CACL,QAAS,EAAO,QAChB,QAAS,EAAO,SACf,GAAiB,GACjB,GAAmB,GACnB,GAAqB,EAAO,GAC9B,CAGH,SAAS,EAAS,EAAc,EAAiC,CAC/D,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,E as r,It as i,N as a,S as o,T as s,b as c,j as l,v as u,x as d}from"./model-ByktcCGW.mjs";import{$ as f,G as ee,H as p,J as m,K as h,Q as g,U as te,V as ne,W as re,X as ie,Y as ae,Z as _,et as v,it as oe,nt as se,q as ce,rt as le,tt as y}from"./identifier-BdLx66pi.mjs";import{a as b,i as x,n as S,r as ue,t as de}from"./native-types-BUkcVedc.mjs";function C(e,t,n){if(typeof t!=`object`||!t||!t[`~`]?.names||!t[`~`]?.state?.scalars)return{code:`M008`,message:`Schema entry '${e}' is not an s.model()`,severity:`error`,model:e};let r=t[`~`].names.ts??n.get(t);if(r!==void 0&&r!==e)return{code:`M003`,message:`Model '${r}' cannot also register as '${e}'`,severity:`error`,model:e};n.set(t,e)}function fe(e){let t=new Map;for(let[n,r]of e){let e=C(n,r,t);if(e!==void 0)return e}}function w(e){let t=new Map;for(let n in e){if(!Object.hasOwn(e,n))continue;let r=C(n,e[n],t);if(r!==void 0)return r}}var T=class extends e{static get name(){return`SchemaValidationError`}static diagnosticName=`SchemaValidationError`;issues;constructor(e,t){let n=Object.freeze(e.map(e=>Object.freeze(e.candidates?{...e,candidates:Object.freeze([...e.candidates])}:{...e}))),r=n.map(e=>[`[${e.code}] ${e.message}`,e.candidates?.length?`Candidates: ${e.candidates.join(`, `)}`:``,e.repair??``].filter(Boolean).join(`
|
|
2
|
+
`));super(`Schema validation failed:\n${r.join(`
|
|
3
|
+
`)}`,`V4002`,t?.cause?{cause:t.cause}:void 0),this.issues=n}toJSON(){return{...super.toJSON(),issues:this.issues}}};function E(e){return e instanceof T}function D(e,t,n){return{code:e,message:t,severity:`error`,...n}}function O(e,t,n){return{code:e,message:t,severity:`warning`,...n}}function k(e,t,n,r,i,a){return{code:e,message:r,severity:`error`,model:t,relation:n,repair:i,...a}}function A(e){return e instanceof Error?e:Error(String(e))}const j=[[],[1],[1,2]],M=/^\d+$/,N=/^[A-Za-z_][A-Za-z0-9_]*(\(\d+(,\d+)*\))?$/,P={pg:`PG`,mysql:`MYSQL`,sqlite:`SQLITE`};let F;function I(e,t){F??=pe();let n=F[e];if(n.exact.has(t))return!0;if(!N.test(t))return!1;let r=t.indexOf(`(`);if(r===-1)return n.templates.get(t)?.has(0)===!0;let i=t.slice(0,r),a=t.slice(r+1,-1).split(`,`).length;return n.templates.get(i)?.has(a)===!0}function L(e){return`Native type must belong to '${e}' (${P[e]}) catalog`}function R(e,t){return t===void 0?void 0:z(e,t)}function z(e,n){if(t(n)||r(e,`nativeType`,`Invalid native type`),b(n)){let{db:t,type:i}=n;(!S.includes(t)||typeof i!=`string`)&&r(e,`nativeType`,`Tagged native type needs \`db\` (${S.join(`/`)}) and string \`type\``);let a=S.find(e=>Object.hasOwn(n,e));return a!==void 0&&r(e,`nativeType.${a}`,`Tagged native type ('${t}') cannot also have '${a}' entry`),n}return B(e,n)}function B(e,t){let n={},i=Object.keys(t);i.length===0&&r(e,`nativeType`,`Native-type map is empty`);for(let a of i)a===`pg`?n.pg=V(e,a,t.pg):a===`mysql`?n.mysql=V(e,a,t.mysql):a===`sqlite`?n.sqlite=V(e,a,t.sqlite):r(e,`nativeType.${a}`,`Unknown dialect '${a}' (expected ${S.join(`/`)})`);return Object.freeze(n)}function V(e,n,i){let a=t(i)?i:void 0,o=a?.db,s=a?.type;return(o!==n||typeof s!=`string`)&&r(e,`nativeType.${n}`,`'${n}' entry must be { db: "${n}", type: string }`),Object.freeze({db:n,type:s})}function pe(){let e=e=>{let t={exact:new Set,templates:new Map};return H(e,t),t};return{pg:e(ue),mysql:e(de),sqlite:e(x)}}function H(e,t){if(typeof e==`function`){me(e,t);return}if(typeof e.type==`string`){t.exact.add(e.type);return}for(let n of Object.values(e))H(n,t)}function me(e,t){for(let n of j){let r=e(...n).type,a=r.indexOf(`(`);if(a===-1){i(t.templates,r,()=>new Set).add(0);continue}let o=r.slice(a+1,-1).split(`,`);o.every(e=>M.test(e))&&i(t.templates,r.slice(0,a),()=>new Set).add(o.length)}}const U=new Uint8Array(200),W=new DataView(U.buffer),G=new DataView(new ArrayBuffer(200)),K=new DataView(new ArrayBuffer(40)),q=(e,t)=>e.getInt32(t,!0),J=(e,t,n)=>e.setInt32(t,n,!0);function he(){for(let e=0,t=1;e<24;e++){for(let e=0;e<5;e++){let t=0,n=0;for(let r=0;r<25;r+=5)t^=q(W,(e+r)*8),n^=q(W,(e+r)*8+4);J(K,e*8,t),J(K,e*8+4,n)}for(let e=0;e<5;e++){let t=q(K,(e+1)%5*8),n=q(K,(e+1)%5*8+4),r=q(K,(e+4)%5*8)^(t<<1|n>>>31),i=q(K,(e+4)%5*8+4)^(n<<1|t>>>31);for(let t=0;t<25;t+=5){let n=(e+t)*8;J(W,n,q(W,n)^r),J(W,n+4,q(W,n+4)^i)}}J(G,0,q(W,0)),J(G,4,q(W,4));for(let e=0,t=1,n=0;e<24;e++){let r=(t+5*n)*8,i=(e+1)*(e+2)/2%64,a=n,o=(2*t+3*n)%5,s=(a+5*o)*8,c=q(W,r),l=q(W,r+4),u=i<32?c:l,d=i<32?l:c,f=i&31;J(G,s,u<<f|d>>>32-f),J(G,s+4,d<<f|u>>>32-f),t=a,n=o}for(let e=0;e<25;e+=5)for(let t=0;t<5;t++){let n=(e+t)*8,r=(e+(t+1)%5)*8,i=(e+(t+2)%5)*8;J(W,n,q(G,n)^~q(G,r)&q(G,i)),J(W,n+4,q(G,n+4)^~q(G,r+4)&q(G,i+4))}for(let e=0;e<7;e++){let n=(1<<e)-1;if(t&1){let e=n<32?0:4;J(W,e,q(W,e)^1<<(n&31))}t=(t<<1^(t&128?113:0))&255}}}function Y(e,t){for(let n=0;n<72;n+=4)J(W,n,q(W,n)^q(e,t+n));he()}function ge(e){U.fill(0);let t=e.length,n=new DataView(e.buffer,e.byteOffset,t),r=Math.floor(t/72);for(let e=0;e<r;e++)Y(n,e*72);let i=new Uint8Array(72),a=t-r*72;return i.set(e.subarray(r*72)),i[a]=6,i[71]=a===71?134:128,Y(new DataView(i.buffer),0),Uint8Array.from(U.subarray(0,64))}const X=(e,t)=>()=>m(e,t());function _e(){let e=globalThis.crypto;return typeof e?.randomUUID==`function`?e.randomUUID():_(le(v(ce,`uuid`)))}const ve=e=>X(e,_e),ye=e=>X(e,()=>_(oe(Date.now(),v(h,`uuidv7`))));function be(e){let t=Uint8Array.from(e);for(let e=t.length-1;e>=0;e--){let n=t[e]+1;if(t[e]=n,n<=255)return t}return y(`s.string().ulid`,`generate`,`ULID millisecond sequence exhausted (2^80)`)}function xe(e={}){let t=e.now??Date.now,n=e.random??(e=>v(e,`ulid`)),r,i;return()=>{let e=t();return r!==void 0&&e<=r?i=be(i):(r=e,i=n(ee)),ie(se(r,i))}}const Se=xe(),Ce=e=>X(e,Se),we=e=>X(e,()=>ae(f(Math.floor(Date.now()/1e3),v(ne,`ksuid`)))),Te=(e,t)=>{let n=e??re;return(!Number.isInteger(n)||n<1||n>p)&&y(`s.string().nanoid`,`length`,`nanoid length must be an integer 1..${p}; got ${n}`),()=>{let e=``;for(let t of v(n,`nanoid`))e+=te.charAt(t&63);return m(t,e)}};let Ee;function De(){let e=v(4,`cuid`);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(0,!0)/4294967296}function Z(e,t){let n=``;for(;n.length<e;)n+=Math.floor(t()*36).toString(36);return n}function Q(e){let t=0n;for(let n of ge((Ee??=new TextEncoder).encode(e)))t=t<<8n|BigInt(n);return t.toString(36).slice(1)}function Oe(e){return Q(Object.keys(globalThis).toString()+Z(32,e)).substring(0,32)}function ke(e={}){let t=e.random??De,n=e.counter??(()=>{let e=Math.floor(t()*476782367);return()=>e++})(),r=e.length??24,i=e.fingerprint??Oe(t);return()=>`abcdefghijklmnopqrstuvwxyz`.charAt(Math.floor(t()*26))+Q(Date.now().toString(36)+Z(r,t)+n().toString(36)+i).substring(1,r)}let Ae;const je=e=>X(e,()=>(Ae??=ke())());function $(e){let{kind:t,prefix:n,length:r}=e;switch(t){case`uuid`:return ve(n);case`uuidv7`:return ye(n);case`ulid`:return Ce(n);case`ksuid`:return we(n);case`nanoid`:return Te(r,n);case`cuid`:return je(n);default:return y(`s.string`,`generate`,`Not a string identifier format`)}}const Me=a.string();var Ne=class e extends o{rebase(e){return a.string(s(e))}array(){return d(this.state.default)&&n(`s.string`),new e(l(this,{array:!0,base:a.string({...s(this.state),array:!0})}),this._nativeType)}id(e){let t=typeof e==`object`?e.generate:void 0,n=typeof e==`string`?e:e?.prefix,r=this.state.autoGenerate;r&&g(n)&&Fe(r);let i=r?{...r,generate:t??r.generate}:{kind:`ulid`,prefix:n,implicit:!0,generate:t};return this.ww(i,!0)}uuid(e){return this.hs(`uuid`,e)}uuidv7(e){return this.hs(`uuidv7`,e)}ksuid(e){return this.hs(`ksuid`,e)}ulid(e){return this.hs(`ulid`,e)}cuid(e){return this.hs(`cuid`,e)}nanoid(e,t){return this.hs(`nanoid`,typeof e==`number`?{length:e,prefix:t}:e??{prefix:t})}hs(e,t){let n=typeof t==`string`?{prefix:t}:t;return this.ww({kind:e,prefix:n?.prefix,length:e===`nanoid`?n?.length:void 0,generate:n?.generate??this.state.autoGenerate?.generate},this.state.isId)}ww(t,r){let i=$(t),a=this.state.hasDefault&&!d(this.state.default),o=(t.generate===!0||r&&t.generate!==!1)&&!a;this.state.array&&o&&n(`s.string`);let s=a||o;return new e(l(this,{isId:r,isUnique:r||this.state.isUnique,autoGenerate:t,hasDefault:s,optional:s,default:o?c(i):a?this.state.default:void 0}),this._nativeType)}};const Pe=e=>new Ne(u(`string`,Me),R(`s.string`,e));function Fe(e){return y(`s.string().id`,`prefix`,`Already declares '${e.kind}'${e.prefix?` (prefix '${e.prefix}')`:``}; spell prefix once on the format`)}export{T as a,k as c,fe as d,w as f,L as i,A as l,R as n,D as o,I as r,E as s,Pe as t,O as u};
|
|
4
|
+
//# sourceMappingURL=scalar-BTYxpiP_.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scalar-BTYxpiP_.mjs","names":["v","state"],"sources":["../src/schema/registration-preflight.ts","../src/schema/validation/error.ts","../src/schema/scalars/native-catalog.ts","../src/validation/primitives/sha3.ts","../src/schema/scalars/string/autogenerate.ts","../src/schema/scalars/string/scalar.ts"],"sourcesContent":["import type { Model } from \"./model\";\nimport type { SchemaValidationIssue } from \"./validation/types\";\n\nfunction checkModelRegistrationEntry(\n modelKey: string,\n model: Model<any>,\n claimedInThisPass: Map<Model<any>, string>\n): SchemaValidationIssue | undefined {\n if (\n model === null ||\n typeof model !== \"object\" ||\n !model[\"~\"]?.names ||\n !model[\"~\"]?.state?.scalars\n )\n return {\n code: \"M008\",\n message: `Schema entry '${modelKey}' is not an s.model()`,\n severity: \"error\",\n model: modelKey,\n };\n const claimed = model[\"~\"].names.ts ?? claimedInThisPass.get(model);\n if (claimed !== undefined && claimed !== modelKey)\n return {\n code: \"M003\",\n message: `Model '${claimed}' cannot also register as '${modelKey}'`,\n severity: \"error\",\n model: modelKey,\n };\n claimedInThisPass.set(model, modelKey);\n return;\n}\n\n/**\n * Prove that every model object in one registration batch has one schema key.\n *\n * The model's hydrated name is the lifetime claim. The local map covers the\n * still-unhydrated batch, so `{ alpha: shared, beta: shared }` is refused before\n * hydration writes either name. Repeating the same object under the same key is\n * deliberately idempotent.\n */\nexport function preflightModelRegistrationIdentity(\n registrations: Iterable<readonly [string, Model<any>]>\n): SchemaValidationIssue | undefined {\n const claimedInThisPass = new Map<Model<any>, string>();\n for (const [modelKey, model] of registrations) {\n const issue = checkModelRegistrationEntry(\n modelKey,\n model,\n claimedInThisPass\n );\n if (issue !== undefined) return issue;\n }\n return;\n}\n\n/** Same identity preflight directly over a schema record, avoiding `Object.entries`. */\nexport function preflightModelRegistrationIdentityRecord(\n schema: Record<string, Model<any>>\n): SchemaValidationIssue | undefined {\n const claimedInThisPass = new Map<Model<any>, string>();\n for (const modelKey in schema) {\n if (!Object.hasOwn(schema, modelKey)) continue;\n const issue = checkModelRegistrationEntry(\n modelKey,\n schema[modelKey]!,\n claimedInThisPass\n );\n if (issue !== undefined) return issue;\n }\n return;\n}\n","import { VibORMError, VibORMErrorCode } from \"../../errors/base\";\nimport type { SchemaValidationIssue } from \"./types\";\n\nexport class SchemaValidationError extends VibORMError {\n static override readonly diagnosticName = \"SchemaValidationError\";\n\n declare readonly code: typeof VibORMErrorCode.INVALID_INPUT;\n readonly issues: readonly SchemaValidationIssue[];\n\n constructor(\n issues: readonly SchemaValidationIssue[],\n options?: { cause?: Error | undefined }\n ) {\n // `candidates` is the one array-valued field, so the snapshot freezes it\n // too: a shallow freeze would publish an immutable issue wrapping a\n // caller-mutable list.\n const snapshot = Object.freeze(\n issues.map((issue) =>\n Object.freeze(\n issue.candidates\n ? { ...issue, candidates: Object.freeze([...issue.candidates]) }\n : { ...issue }\n )\n )\n );\n const messages = snapshot.map((issue) =>\n [\n `[${issue.code}] ${issue.message}`,\n issue.candidates?.length\n ? `Candidates: ${issue.candidates.join(\", \")}`\n : \"\",\n issue.repair ?? \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\")\n );\n super(\n `Schema validation failed:\\n${messages.join(\"\\n\")}`,\n VibORMErrorCode.INVALID_INPUT,\n options?.cause ? { cause: options.cause } : undefined\n );\n this.issues = snapshot;\n }\n\n override toJSON(): Record<string, unknown> {\n return { ...super.toJSON(), issues: this.issues };\n }\n}\n\nexport function isSchemaValidationError(\n error: unknown\n): error is SchemaValidationError {\n return error instanceof SchemaValidationError;\n}\n\nexport function err(\n code: string,\n message: string,\n extra?: Omit<SchemaValidationIssue, \"code\" | \"message\" | \"severity\">\n): SchemaValidationIssue {\n return { code, message, severity: \"error\", ...extra };\n}\n\nexport function warn(\n code: string,\n message: string,\n extra?: Omit<SchemaValidationIssue, \"code\" | \"message\" | \"severity\">\n): SchemaValidationIssue {\n return { code, message, severity: \"warning\", ...extra };\n}\n\nexport function relErr(\n code: string,\n model: string,\n relation: string,\n message: string,\n repair: string,\n extra?: Pick<SchemaValidationIssue, \"field\" | \"candidates\">\n): SchemaValidationIssue {\n return {\n code,\n message,\n severity: \"error\",\n model,\n relation,\n repair,\n ...extra,\n };\n}\n\n/**\n * ONE reading of a value pulled out of a `catch`, shared by every gate boundary\n * that turns a throw into a diagnostic.\n *\n * The throwers this gate catches are all in-repo and all throw `Error`s — the\n * target once-cell normalizes before the resolver ever sees a getter's throw,\n * and the physical-name owner throws its own error type. Each catch site\n * spelling this narrowing itself made three owners for one rule and three arms\n * that no schema can reach; the narrowing lives here instead, where it is\n * witnessed directly.\n */\nexport function thrownAsError(thrown: unknown): Error {\n return thrown instanceof Error ? thrown : new Error(String(thrown));\n}\n","// The closed per-dialect native-type catalog, and the scalar factories' one\n// native-type admission.\n//\n// A native type's `type` is the ONE declaration string a migration driver emits\n// into DDL verbatim — the three drivers write it as a column's type with no\n// escaping, because a coded schema takes it from a typed constant. A schema\n// document is written by whoever hands you one, so it decides what may occupy\n// that position here. Coded maps and tagged declarations share the historical\n// trusted schema-author escape hatch for custom type spellings. The round-1 answer was a word grammar; the reviewer proved it cannot\n// work: `TEXT REFERENCES victims(id)`, `TEXT UNIQUE` and `TEXT CHECK(0)` are\n// letters and spaces with an optional parenthesized group, indistinguishable\n// from a multi-word type name, yet each appends a CONSTRAINT to a column in DDL.\n// No regex over arbitrary SQL words separates a type from a clause.\n//\n// So the admissible set is CLOSED and derived, per dialect, from the one owner\n// that already enumerates native types: the shipped `PG`/`MYSQL`/`SQLITE`\n// constant trees. Derivation, not duplication —\n//\n// - a string leaf (`{ db, type: \"text\" }`) contributes its EXACT value;\n// - a function leaf (a parameterized type) is probe-called at zero, one and\n// two integer arguments to learn its base name and which argument arities it\n// publishes; the catalog then admits that base bare, or with one or two\n// INTEGER arguments, at exactly those arities.\n//\n// The trees produce no word-argument type THROUGH A FUNCTION — `geometry(Point)`\n// is a string leaf, matched exactly — so there is no word-argument rule, which\n// is the narrowest rule the trees justify. A coded schema's constants are\n// catalog members by construction. The schema-document reader and serializer\n// consult this owner for the tagged `native` form; `admitNativeType` validates coded maps structurally. A TAGGED declaration written in code keeps its historical\n// open contract (a custom `{ db, type }` still reaches DDL as written) — only a\n// document refuses one outside the catalog. Nothing downstream sanitizes native\n// types, and nothing can.\n//\n// This lives beside `native-types.ts` rather than in the document module because\n// the scalar factories need it; it imports the constant trees, so the trees'\n// module cannot import it back.\n\nimport { isRecord } from \"@validation/value-guards\";\nimport { mapGet } from \"../record\";\nimport { refuseBuilder } from \"./common\";\nimport {\n type DialectNativeType,\n isTaggedNativeType,\n MYSQL,\n NATIVE_DIALECTS,\n type NativeDialect,\n type NativeTypeDeclaration,\n type NativeTypeMap,\n PG,\n SQLITE,\n} from \"./native-types\";\n\ntype Dialect = NativeDialect;\n\ntype DialectCatalog = {\n /** The exact type strings every string leaf produces. */\n readonly exact: Set<string>;\n /** A parameterized base name → the argument arities it publishes (0 = bare). */\n readonly templates: Map<string, Set<number>>;\n};\n\n/** Distinct non-zero probe arguments, so a produced form is unambiguous. */\nconst PROBE_ARGUMENTS: readonly number[][] = [[], [1], [1, 2]];\n\n/** A parameterized-type argument the trees produce: a non-negative integer. */\nconst INTEGER_ARGUMENT = /^\\d+$/;\n\nconst TYPE_EXPRESSION = /^[A-Za-z_][A-Za-z0-9_]*(\\(\\d+(,\\d+)*\\))?$/;\n\nconst CONSTANT_NAMES: Record<Dialect, string> = {\n pg: \"PG\",\n mysql: \"MYSQL\",\n sqlite: \"SQLITE\",\n};\n\nlet catalogs: Record<Dialect, DialectCatalog> | undefined;\n\nexport function isNativeTypeInCatalog(db: Dialect, type: string): boolean {\n catalogs ??= buildCatalogs();\n const catalog = catalogs[db];\n if (catalog.exact.has(type)) return true;\n if (!TYPE_EXPRESSION.test(type)) return false;\n const open = type.indexOf(\"(\");\n if (open === -1) return catalog.templates.get(type)?.has(0) === true;\n const base = type.slice(0, open);\n const arity = type.slice(open + 1, -1).split(\",\").length;\n return catalog.templates.get(base)?.has(arity) === true;\n}\n\nexport function nativeTypeRefusal(db: Dialect): string {\n return `Native type must belong to '${db}' (${CONSTANT_NAMES[db]}) catalog`;\n}\n\n// =============================================================================\n// SCALAR FACTORY ADMISSION\n// =============================================================================\n\nexport function admitNativeType(\n builder: string,\n declaration: NativeTypeDeclaration | undefined\n): NativeTypeDeclaration | undefined {\n return declaration === undefined\n ? undefined\n : admitDeclaredNativeType(builder, declaration);\n}\n\n/** A declared native type, out of line: most scalars declare none. */\nfunction admitDeclaredNativeType(\n builder: string,\n declaration: NativeTypeDeclaration\n): NativeTypeDeclaration {\n if (!isRecord(declaration)) {\n refuseBuilder(builder, \"nativeType\", \"Invalid native type\");\n }\n if (isTaggedNativeType(declaration)) {\n const { db, type } = declaration;\n if (!NATIVE_DIALECTS.includes(db) || typeof type !== \"string\") {\n refuseBuilder(\n builder,\n \"nativeType\",\n `Tagged native type needs \\`db\\` (${NATIVE_DIALECTS.join(\"/\")}) and string \\`type\\``\n );\n }\n const beside = NATIVE_DIALECTS.find((dialect) =>\n Object.hasOwn(declaration, dialect)\n );\n if (beside !== undefined) {\n refuseBuilder(\n builder,\n `nativeType.${beside}`,\n `Tagged native type ('${db}') cannot also have '${beside}' entry`\n );\n }\n return declaration;\n }\n return admitNativeTypeMap(builder, declaration);\n}\n\nfunction admitNativeTypeMap(\n builder: string,\n map: NativeTypeMap\n): NativeTypeMap {\n const snapshot: {\n pg?: DialectNativeType<\"pg\">;\n mysql?: DialectNativeType<\"mysql\">;\n sqlite?: DialectNativeType<\"sqlite\">;\n } = {};\n const keys = Object.keys(map);\n if (keys.length === 0) {\n refuseBuilder(builder, \"nativeType\", \"Native-type map is empty\");\n }\n for (const key of keys) {\n if (key === \"pg\") snapshot.pg = admitEntry(builder, key, map.pg);\n else if (key === \"mysql\")\n snapshot.mysql = admitEntry(builder, key, map.mysql);\n else if (key === \"sqlite\")\n snapshot.sqlite = admitEntry(builder, key, map.sqlite);\n else\n refuseBuilder(\n builder,\n `nativeType.${key}`,\n `Unknown dialect '${key}' (expected ${NATIVE_DIALECTS.join(\"/\")})`\n );\n }\n return Object.freeze(snapshot);\n}\n\n/** One map entry: a native type of exactly its key's dialect, in its catalog. */\nfunction admitEntry<Entry extends Dialect>(\n builder: string,\n dialect: Entry,\n entry: unknown\n): DialectNativeType<Entry> {\n const rec = isRecord(entry) ? entry : undefined;\n const db = rec?.db;\n const type = rec?.type;\n if (db !== dialect || typeof type !== \"string\") {\n refuseBuilder(\n builder,\n `nativeType.${dialect}`,\n `'${dialect}' entry must be { db: \"${dialect}\", type: string }`\n );\n }\n return Object.freeze({ db: dialect, type });\n}\n\n// =============================================================================\n// CATALOG CONSTRUCTION\n// =============================================================================\n\nfunction buildCatalogs(): Record<Dialect, DialectCatalog> {\n const build = (tree: unknown): DialectCatalog => {\n const catalog: DialectCatalog = { exact: new Set(), templates: new Map() };\n walk(tree, catalog);\n return catalog;\n };\n return { pg: build(PG), mysql: build(MYSQL), sqlite: build(SQLITE) };\n}\n\nfunction walk(node: any, catalog: DialectCatalog): void {\n if (typeof node === \"function\") {\n deriveFunction(node, catalog);\n return;\n }\n if (typeof node.type === \"string\") {\n catalog.exact.add(node.type);\n return;\n }\n for (const value of Object.values(node)) walk(value, catalog);\n}\n\n/** A parameterized-type leaf, called generically — hence the erased type. */\nfunction deriveFunction(factory: any, catalog: DialectCatalog): void {\n for (const args of PROBE_ARGUMENTS) {\n const type: string = factory(...args).type;\n const open = type.indexOf(\"(\");\n if (open === -1) {\n mapGet(catalog.templates, type, () => new Set()).add(0);\n continue;\n }\n const parts = type.slice(open + 1, -1).split(\",\");\n if (parts.every((part) => INTEGER_ARGUMENT.test(part))) {\n mapGet(catalog.templates, type.slice(0, open), () => new Set()).add(\n parts.length\n );\n }\n }\n}\n","// biome-ignore-all lint/suspicious/noBitwiseOperators: Keccak-f[1600] is a bit\n// permutation. Every operator below is part of the published specification's\n// arithmetic, carried on 32-bit halves because JavaScript has no 64-bit word.\n\n/**\n * SHA3-512, the one hash VibORM computes.\n *\n * FIPS 202's Keccak-f[1600] over 25 lanes of 64 bits, rate 72 bytes, domain\n * padding `0x06 ... 0x80`. One exported function, no streaming, no options, no\n * configuration: the caller hands over the complete message and receives the\n * 64-byte digest.\n *\n * Each 64-bit lane is carried as TWO 32-bit halves rather than a `BigInt`.\n * JavaScript's bitwise operators are 32-bit, so a BigInt lane would allocate a\n * new arbitrary-precision value for every one of the roughly 1,200 operations a\n * single digest performs.\n *\n * Every read goes through a `DataView`, which is the one indexed read this\n * codebase has that is not `T | undefined`: a Keccak round has no in-range\n * check to make and no branch to take, so a fallback on a typed-array read\n * would be a guard whose coverage cannot be named. The halves are stored\n * little-endian at `lane * 8` and `lane * 8 + 4`, which is exactly the lane's\n * own little-endian byte layout — so absorbing a block is a word-wise XOR of\n * the message and squeezing is a copy of the first 64 bytes.\n *\n * The one caller is CUID2 (`@schema/scalars/string/autogenerate`). Nothing else\n * in VibORM may import this module without its own differential proof against a\n * reference implementation.\n */\n\n/** SHA3-512's rate: 1600 - 2*512 bits, as bytes. */\nconst RATE_BYTES = 72;\n/** 512 bits of output. */\nconst DIGEST_BYTES = 64;\nconst LANES = 25;\nconst STATE_BYTES = LANES * 8;\nconst ROUNDS = 24;\n/** SHA-3's domain separation: `01` then the pad10*1 rule's leading bit. */\nconst DOMAIN_PAD = 0x06;\n/** pad10*1's trailing bit, at the top of the block's last byte. */\nconst FINAL_PAD = 0x80;\n\n/**\n * The iota round constants, low half then high half of each round.\n *\n * Filled through the same little-endian writes every other buffer in this\n * module is filled with. A typed array would lay its bytes out in the HOST's\n * order, which is not what the read at the iota step asks for: the two would\n * agree on a little-endian machine and disagree on every other one.\n */\nconst stateBytes = new Uint8Array(STATE_BYTES);\nconst state = new DataView(stateBytes.buffer);\nconst plane = new DataView(new ArrayBuffer(STATE_BYTES));\nconst column = new DataView(new ArrayBuffer(5 * 8));\n\nconst get32 = (view: DataView, offset: number): number =>\n view.getInt32(offset, true);\nconst set32 = (view: DataView, offset: number, value: number): void =>\n view.setInt32(offset, value, true);\n\n/** Keccak-f[1600]: 24 rounds of theta, rho + pi, chi and iota. */\nfunction permute(): void {\n for (let round = 0, lfsr = 1; round < ROUNDS; round++) {\n // Theta: each column's parity, folded back into every lane of the column.\n for (let x = 0; x < 5; x++) {\n let low = 0;\n let high = 0;\n for (let y = 0; y < LANES; y += 5) {\n low ^= get32(state, (x + y) * 8);\n high ^= get32(state, (x + y) * 8 + 4);\n }\n set32(column, x * 8, low);\n set32(column, x * 8 + 4, high);\n }\n for (let x = 0; x < 5; x++) {\n const nextLow = get32(column, ((x + 1) % 5) * 8);\n const nextHigh = get32(column, ((x + 1) % 5) * 8 + 4);\n const deltaLow =\n get32(column, ((x + 4) % 5) * 8) ^ ((nextLow << 1) | (nextHigh >>> 31));\n const deltaHigh =\n get32(column, ((x + 4) % 5) * 8 + 4) ^\n ((nextHigh << 1) | (nextLow >>> 31));\n for (let y = 0; y < LANES; y += 5) {\n const at = (x + y) * 8;\n set32(state, at, get32(state, at) ^ deltaLow);\n set32(state, at + 4, get32(state, at + 4) ^ deltaHigh);\n }\n }\n\n // Rho and pi: rotate every lane and move it to its permuted position.\n set32(plane, 0, get32(state, 0));\n set32(plane, 4, get32(state, 4));\n for (let t = 0, x = 1, y = 0; t < ROUNDS; t++) {\n const lane = (x + 5 * y) * 8;\n const shift = (((t + 1) * (t + 2)) / 2) % 64;\n const nextX = y;\n const nextY = (2 * x + 3 * y) % 5;\n const target = (nextX + 5 * nextY) * 8;\n const low = get32(state, lane);\n const high = get32(state, lane + 4);\n const a = shift < 32 ? low : high;\n const b = shift < 32 ? high : low;\n const s = shift & 31;\n set32(plane, target, (a << s) | (b >>> (32 - s)));\n set32(plane, target + 4, (b << s) | (a >>> (32 - s)));\n x = nextX;\n y = nextY;\n }\n\n // Chi: each lane against the next two in its row.\n for (let y = 0; y < LANES; y += 5) {\n for (let x = 0; x < 5; x++) {\n const at = (y + x) * 8;\n const next = (y + ((x + 1) % 5)) * 8;\n const after = (y + ((x + 2) % 5)) * 8;\n set32(\n state,\n at,\n get32(plane, at) ^ (~get32(plane, next) & get32(plane, after))\n );\n set32(\n state,\n at + 4,\n get32(plane, at + 4) ^\n (~get32(plane, next + 4) & get32(plane, after + 4))\n );\n }\n }\n\n // Iota: round constant LFSR on lane 0.\n for (let bitIndex = 0; bitIndex < 7; bitIndex++) {\n const bit = (1 << bitIndex) - 1;\n if (lfsr & 1) {\n const offset = bit < 32 ? 0 : 4;\n set32(state, offset, get32(state, offset) ^ (1 << (bit & 31)));\n }\n lfsr = ((lfsr << 1) ^ (lfsr & 0x80 ? 0x71 : 0)) & 0xff;\n }\n }\n}\n\n/** Absorb one complete rate-sized block and run the permutation. */\nfunction absorb(block: DataView, offset: number): void {\n for (let at = 0; at < RATE_BYTES; at += 4) {\n set32(state, at, get32(state, at) ^ get32(block, offset + at));\n }\n permute();\n}\n\n/**\n * The SHA3-512 digest of one complete message.\n *\n * Byte-identical to the reference implementation for every input, which a\n * differential test pins against the NIST known-answer vectors and 10,000\n * random messages crossing every rate boundary.\n */\nexport function sha3_512(bytes: Uint8Array): Uint8Array {\n stateBytes.fill(0);\n\n const length = bytes.length;\n const message = new DataView(bytes.buffer, bytes.byteOffset, length);\n const wholeBlocks = Math.floor(length / RATE_BYTES);\n for (let block = 0; block < wholeBlocks; block++) {\n absorb(message, block * RATE_BYTES);\n }\n\n // The final block is the message tail plus pad10*1. A tail of exactly\n // `RATE_BYTES - 1` puts both pad bits in the same byte, which is the rule\n // rather than a special case.\n const tail = new Uint8Array(RATE_BYTES);\n const tailLength = length - wholeBlocks * RATE_BYTES;\n tail.set(bytes.subarray(wholeBlocks * RATE_BYTES));\n tail[tailLength] = DOMAIN_PAD;\n tail[RATE_BYTES - 1] =\n tailLength === RATE_BYTES - 1 ? DOMAIN_PAD | FINAL_PAD : FINAL_PAD;\n absorb(new DataView(tail.buffer), 0);\n\n // 512 bits is narrower than the rate, so one squeeze with no further\n // permutation is the whole digest — and the halves are already stored in the\n // little-endian order the digest is written in.\n return Uint8Array.from(stateBytes.subarray(0, DIGEST_BYTES));\n}\n","// biome-ignore-all lint/suspicious/noBitwiseOperators: NanoID selects a\n// character with `byte & 63`, the ULID counter carries a byte at a time, and\n// CUID2's digest is read as one big-endian integer. All three are bit layouts.\n\n/**\n * The six identifier generators a string scalar can declare.\n *\n * Each `default*` function is the DECLARATION: it validates what the modifier\n * was spelled with and returns the closure the scalar stores as its default.\n * The closure is what runs per row, synchronously, inside the field's own\n * create schema — so nothing here may be asynchronous, and nothing here may\n * draw entropy before it is called.\n *\n * The byte layouts, alphabets, widths and the one entropy source live in\n * `@validation/primitives/id-formats`, where the storage codec can read them\n * without pulling a scalar class. This module owns only what a GENERATOR adds\n * to a format: the clock it reads, the state it keeps between calls, and the\n * prefix it puts in front of the payload.\n */\n\nimport {\n applyIdPrefix,\n bytesToKsuid,\n bytesToUlid,\n bytesToUuid,\n KSUID_PAYLOAD_LENGTH,\n ksuidBytes,\n MAX_RANDOM_BYTES,\n NANOID_ALPHABET,\n NANOID_DEFAULT_LENGTH,\n randomBytes,\n refuseId,\n ULID_RANDOM_LENGTH,\n UUID_BYTE_LENGTH,\n UUIDV7_RANDOM_LENGTH,\n ulidBytes,\n uuidV4Bytes,\n uuidV7Bytes,\n} from \"@validation/primitives/id-formats\";\nimport { sha3_512 } from \"@validation/primitives/sha3\";\n\nconst MILLISECONDS_PER_SECOND = 1000;\n\n// =============================================================================\n// UUID\n// =============================================================================\n\n/**\n * A UUIDv4.\n *\n * `crypto.randomUUID()` when the runtime has it — it is the platform's own\n * implementation of exactly this format, and it is measurably faster than\n * drawing bytes and tagging them. The manual path is not a fallback to a weaker\n * value: it is the same 122 random bits with the same version and variant, from\n * the same entropy source, for runtimes that expose `getRandomValues` without\n * `randomUUID`.\n */\nconst prefixed = (prefix: string | undefined, make: () => string) => () =>\n applyIdPrefix(prefix, make());\n\nfunction uuidV4(): string {\n const source = globalThis.crypto;\n if (typeof source?.randomUUID === \"function\") return source.randomUUID();\n return bytesToUuid(uuidV4Bytes(randomBytes(UUID_BYTE_LENGTH, \"uuid\")));\n}\n\nexport const defaultUuid = (prefix?: string) => prefixed(prefix, uuidV4);\n\nexport const defaultUuidV7 = (prefix?: string) =>\n prefixed(prefix, () =>\n bytesToUuid(\n uuidV7Bytes(Date.now(), randomBytes(UUIDV7_RANDOM_LENGTH, \"uuidv7\"))\n )\n );\n\n// =============================================================================\n// ULID\n// =============================================================================\n\nfunction incrementUlidRandom(random: Uint8Array): Uint8Array {\n const next = Uint8Array.from(random);\n for (let i = next.length - 1; i >= 0; i--) {\n const inc = next[i]! + 1;\n next[i] = inc;\n if (inc <= 255) return next;\n }\n return refuseId(\n \"s.string().ulid\",\n \"generate\",\n \"ULID millisecond sequence exhausted (2^80)\"\n );\n}\n\nexport function createUlidGenerator(\n options: { now?: () => number; random?: (length: number) => Uint8Array } = {}\n): () => string {\n const now = options.now ?? Date.now;\n const draw = options.random ?? ((length) => randomBytes(length, \"ulid\"));\n let lastTime: number | undefined;\n let lastRandom: Uint8Array;\n return () => {\n const time = now();\n if (lastTime !== undefined && time <= lastTime) {\n lastRandom = incrementUlidRandom(lastRandom);\n } else {\n lastTime = time;\n lastRandom = draw(ULID_RANDOM_LENGTH);\n }\n return bytesToUlid(ulidBytes(lastTime, lastRandom));\n };\n}\n\nconst nextUlid = /*#__PURE__*/ createUlidGenerator();\n\nexport const defaultUlid = (prefix?: string) => prefixed(prefix, nextUlid);\n\n// =============================================================================\n// KSUID\n// =============================================================================\n\nexport const defaultKsuid = (prefix?: string) =>\n prefixed(prefix, () =>\n bytesToKsuid(\n ksuidBytes(\n Math.floor(Date.now() / MILLISECONDS_PER_SECOND),\n randomBytes(KSUID_PAYLOAD_LENGTH, \"ksuid\")\n )\n )\n );\n\n// =============================================================================\n// NANOID\n// =============================================================================\n\n/**\n * The lengths a nanoid can have, refused where the length is spelled.\n *\n * One character costs one byte of entropy, so the upper bound is the entropy\n * source's own per-call quota: asking for more used to declare cleanly and then\n * throw a raw `QuotaExceededError` from inside the closure, at row-create time,\n * for every row.\n */\nexport const defaultNanoid = (length?: number, prefix?: string) => {\n const size = length ?? NANOID_DEFAULT_LENGTH;\n if (!Number.isInteger(size) || size < 1 || size > MAX_RANDOM_BYTES) {\n refuseId(\n \"s.string().nanoid\",\n \"length\",\n `nanoid length must be an integer 1..${MAX_RANDOM_BYTES}; got ${size}`\n );\n }\n return () => {\n let id = \"\";\n for (const byte of randomBytes(size, \"nanoid\")) {\n id += NANOID_ALPHABET.charAt(byte & 63);\n }\n return applyIdPrefix(prefix, id);\n };\n};\n\n// =============================================================================\n// CUID2\n// =============================================================================\n\n/*\n * The CUID2 construction below is a port of @paralleldrive/cuid2 3.3.0, kept\n * byte-identical to it so that identifiers minted by VibORM and identifiers\n * minted by the upstream package belong to the same space. What changed is the\n * arithmetic (native `BigInt` in place of bignumber.js), the entropy source\n * (secure bytes only, never `Math.random()`), and the fingerprint's global\n * object (`globalThis`, which every supported runtime has). A differential test\n * pins the rest against the upstream package.\n *\n * MIT License\n *\n * Copyright (c) 2022 Eric Elliott\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nconst CUID_DEFAULT_LENGTH = 24;\nconst CUID_BIG_LENGTH = 32;\nconst CUID_ALPHABET_SIZE = 26;\nconst BASE36 = 36;\n/** ~22k hosts before a 50% chance of an initial counter collision (upstream). */\nconst CUID_INITIAL_COUNT_MAX = 476_782_367;\n\nlet textEncoder: TextEncoder | undefined;\nconst LOWERCASE_LETTERS = \"abcdefghijklmnopqrstuvwxyz\";\n\n/** A float in `[0, 1)` from four secure bytes, read as one 32-bit word. */\nfunction secureFloat(): number {\n const bytes = randomBytes(4, \"cuid\");\n const word = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n return word.getUint32(0, true) / 0x1_00_00_00_00;\n}\n\nfunction createEntropy(length: number, random: () => number): string {\n let entropy = \"\";\n while (entropy.length < length) {\n entropy += Math.floor(random() * BASE36).toString(BASE36);\n }\n return entropy;\n}\n\nfunction hashBase36(input: string): string {\n let value = 0n;\n for (const byte of sha3_512(\n (textEncoder ??= new TextEncoder()).encode(input)\n )) {\n value = (value << 8n) | BigInt(byte);\n }\n return value.toString(BASE36).slice(1);\n}\n\n/**\n * A fingerprint of the host environment, mixed into every id so that two\n * processes minting ids at the same millisecond with the same counter still\n * disagree.\n */\nfunction createFingerprint(random: () => number): string {\n const globals = Object.keys(globalThis).toString();\n const entropy = createEntropy(CUID_BIG_LENGTH, random);\n // Upstream writes `globals.length > 0 ? globals + entropy : entropy`. The two\n // arms are the same string — concatenating an empty `globals` IS `entropy` —\n // so the condition names no case, and a branch whose unique coverage cannot\n // be stated is one this codebase does not keep. The digest is unchanged,\n // which the differential test against the pinned upstream package proves.\n return hashBase36(globals + entropy).substring(0, CUID_BIG_LENGTH);\n}\n\n/**\n * One CUID2 sequence.\n *\n * Everything upstream lets a caller replace is replaceable here for the same\n * reason: the fingerprint, counter and random source are the parts that make\n * two processes differ, and a test that cannot fix them cannot compare two\n * implementations at all. `length` is replaceable for the same reason — the\n * salt is as long as the id, so a differential test that only ever saw 24\n * characters would compare one input shape.\n *\n * No length is spellable in a schema: `.cuid(prefix?)` takes none and always\n * mints the published 24, and a schema document that declares one is refused by\n * the reader (J007). The construction therefore states no bound of its own.\n */\nexport function createCuid2(\n options: {\n random?: () => number;\n counter?: () => number;\n length?: number;\n fingerprint?: string;\n } = {}\n): () => string {\n const random = options.random ?? secureFloat;\n const counter =\n options.counter ??\n (() => {\n let count = Math.floor(random() * CUID_INITIAL_COUNT_MAX);\n return () => count++;\n })();\n const length = options.length ?? CUID_DEFAULT_LENGTH;\n const fingerprint = options.fingerprint ?? createFingerprint(random);\n return () => {\n const firstLetter = LOWERCASE_LETTERS.charAt(\n Math.floor(random() * CUID_ALPHABET_SIZE)\n );\n const time = Date.now().toString(BASE36);\n const salt = createEntropy(length, random);\n return (\n firstLetter +\n hashBase36(\n time + salt + counter().toString(BASE36) + fingerprint\n ).substring(1, length)\n );\n };\n}\n\nlet processCuid: (() => string) | undefined;\n\nexport const defaultCuid = (prefix?: string) =>\n prefixed(prefix, () => (processCuid ??= createCuid2())());\n","// String Scalar\n// The modifiers every scalar shares are implemented once, in the chain this\n// class extends; the class types them for this scalar's own state\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { hasIdPrefix, refuseId } from \"@validation/primitives/id-formats\";\nimport type { StringSchema } from \"@validation/primitives/string\";\nimport v from \"@validation/primitives/v\";\nimport type { ComputeInput, ComputeOutput } from \"@validation/types\";\nimport {\n type AutoGenerate,\n createDefaultState,\n type DefaultValueInput,\n type GeneratorDefaultBrand,\n generatorDefault,\n isGeneratorDefault,\n keyedScalarChain,\n rebaseOpts,\n refuseListGenerator,\n type ScalarState,\n type UpdateState,\n updateState,\n} from \"../common\";\nimport { admitNativeType } from \"../native-catalog\";\nimport type {\n ExactNativeTypeMap,\n NativeDialect,\n NativeTypeArgument,\n NativeTypeDeclaration,\n} from \"../native-types\";\nimport {\n defaultCuid,\n defaultKsuid,\n defaultNanoid,\n defaultUlid,\n defaultUuid,\n defaultUuidV7,\n} from \"./autogenerate\";\n\ninterface FormatOptions {\n prefix?: string;\n generate?: true;\n}\ninterface NanoidOptions extends FormatOptions {\n length?: number;\n}\ninterface KeyOptions {\n generate: false;\n prefix?: string;\n}\ntype IdentifierKind = \"uuid\" | \"uuidv7\" | \"ulid\" | \"ksuid\" | \"nanoid\" | \"cuid\";\ntype ExactOptions<Given, Allowed> = Given extends string | number | undefined\n ? unknown\n : Record<Exclude<keyof Given, keyof Allowed>, never>;\ntype GenerationRequested<\n State extends ScalarState<\"string\">,\n Given,\n> = Given extends { generate: true }\n ? true\n : Given extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends { generate: true }\n ? true\n : State[\"isId\"];\ntype GenerationChoice<\n State extends ScalarState<\"string\">,\n Given,\n> = Given extends { generate: true }\n ? true\n : Given extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends {\n generate: infer Choice extends boolean | undefined;\n }\n ? Choice\n : undefined;\ntype HasCustomDefault<State extends ScalarState<\"string\">> =\n State[\"default\"] extends GeneratorDefaultBrand ? false : State[\"hasDefault\"];\ntype FormatState<\n State extends ScalarState<\"string\">,\n Given,\n Kind extends IdentifierKind = IdentifierKind,\n> = {\n autoGenerate: AutoGenerate & {\n kind: Kind;\n implicit?: undefined;\n generate: GenerationChoice<State, Given>;\n };\n hasDefault: HasCustomDefault<State> extends true\n ? true\n : GenerationRequested<State, Given>;\n optional: HasCustomDefault<State> extends true\n ? true\n : GenerationRequested<State, Given>;\n default: HasCustomDefault<State> extends true\n ? State[\"default\"]\n : GenerationRequested<State, Given> extends true\n ? (() => string) & GeneratorDefaultBrand\n : undefined;\n};\ntype KeyState<State extends ScalarState<\"string\">, Given> = Omit<\n FormatState<UpdateState<State, { isId: true }>, Given>,\n \"autoGenerate\"\n> & {\n isId: true;\n isUnique: true;\n autoGenerate: State[\"autoGenerate\"] extends AutoGenerate\n ? Omit<State[\"autoGenerate\"], \"generate\"> & {\n generate: GenerationChoice<State, Given>;\n }\n : {\n kind: \"ulid\";\n implicit: true;\n prefix?: string;\n generate: GenerationChoice<State, Given>;\n };\n};\n\nfunction identifierGenerator(declaration: AutoGenerate): () => string {\n const { kind, prefix, length } = declaration;\n switch (kind) {\n case \"uuid\":\n return defaultUuid(prefix);\n case \"uuidv7\":\n return defaultUuidV7(prefix);\n case \"ulid\":\n return defaultUlid(prefix);\n case \"ksuid\":\n return defaultKsuid(prefix);\n case \"nanoid\":\n return defaultNanoid(length, prefix);\n case \"cuid\":\n return defaultCuid(prefix);\n default:\n return refuseId(\"s.string\", \"generate\", \"Not a string identifier format\");\n }\n}\n\nconst stringBase = /*#__PURE__*/ v.string();\n\nexport class StringScalar<\n State extends ScalarState<\"string\">,\n> extends keyedScalarChain<State> {\n private declare readonly state: State;\n private declare readonly _nativeType: NativeTypeDeclaration | undefined;\n declare readonly nullable: () => StringScalar<\n UpdateState<\n State,\n {\n readonly nullable: true;\n readonly hasDefault: true;\n readonly default: State[\"hasDefault\"] extends true\n ? State[\"default\"]\n : null;\n readonly optional: true;\n readonly base: StringSchema<\n ComputeInput<\n string,\n {\n nullable: true;\n array: State[\"array\"];\n schema: State[\"schema\"];\n }\n >,\n ComputeOutput<\n string,\n {\n nullable: true;\n array: State[\"array\"];\n schema: State[\"schema\"];\n }\n >\n >;\n }\n >\n >;\n declare readonly unique: () => StringScalar<\n UpdateState<\n State,\n {\n readonly isUnique: true;\n }\n >\n >;\n declare readonly default: <V extends DefaultValueInput<State>>(\n value: V\n ) => StringScalar<\n UpdateState<\n State,\n {\n readonly hasDefault: true;\n readonly default: V;\n readonly optional: true;\n }\n >\n >;\n declare readonly schema: <S extends StandardSchemaV1<string>>(\n schema: S\n ) => StringScalar<\n UpdateState<\n State,\n {\n readonly schema: S;\n readonly base: StringSchema<\n ComputeInput<\n string,\n {\n nullable: State[\"nullable\"];\n array: State[\"array\"];\n schema: S;\n }\n >,\n ComputeOutput<\n string,\n {\n nullable: State[\"nullable\"];\n array: State[\"array\"];\n schema: S;\n }\n >\n >;\n }\n >\n >;\n /**\n * Maps this scalar to a custom column name in the database\n */\n declare readonly map: (columnName: string) => StringScalar<\n UpdateState<\n State,\n {\n readonly columnName: string;\n }\n >\n >;\n declare readonly [\"~\"]: {\n state: State;\n nativeType: NativeTypeDeclaration | undefined;\n };\n\n protected rebase(state: State) {\n return v.string(rebaseOpts(state));\n }\n\n array() {\n if (isGeneratorDefault(this.state.default)) refuseListGenerator(\"s.string\");\n return new StringScalar(\n updateState(this, {\n array: true,\n base: v.string<{\n nullable: State[\"nullable\"];\n array: true;\n schema: State[\"schema\"];\n }>({\n ...rebaseOpts(this.state),\n array: true,\n }),\n }),\n this._nativeType\n );\n }\n\n id<const Given extends string | KeyOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, KeyOptions>\n ): StringScalar<UpdateState<State, KeyState<State, Given>>>;\n id(options?: string | KeyOptions): StringScalar<ScalarState<\"string\">> {\n const generate = typeof options === \"object\" ? options.generate : undefined;\n const prefix = typeof options === \"string\" ? options : options?.prefix;\n const declared = this.state.autoGenerate;\n if (declared && hasIdPrefix(prefix)) refuseSecondIdPrefix(declared);\n const declaration: AutoGenerate = declared\n ? { ...declared, generate: generate ?? declared.generate }\n : { kind: \"ulid\", prefix, implicit: true, generate };\n return this.withIdentifier(declaration, true);\n }\n\n uuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"uuid\">>>;\n uuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"uuid\", options);\n }\n\n uuidv7<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"uuidv7\">>>;\n uuidv7(\n options?: string | FormatOptions\n ): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"uuidv7\", options);\n }\n\n ksuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"ksuid\">>>;\n ksuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"ksuid\", options);\n }\n\n ulid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"ulid\">>>;\n ulid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"ulid\", options);\n }\n\n cuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"cuid\">>>;\n cuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"cuid\", options);\n }\n\n nanoid<const Given extends number | NanoidOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, NanoidOptions>,\n prefix?: string\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"nanoid\">>>;\n nanoid(\n options?: number | NanoidOptions,\n prefix?: string\n ): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\n \"nanoid\",\n typeof options === \"number\"\n ? { length: options, prefix }\n : (options ?? { prefix })\n );\n }\n\n private withFormat(kind: IdentifierKind, options?: string | NanoidOptions) {\n const configuration: NanoidOptions | undefined =\n typeof options === \"string\" ? { prefix: options } : options;\n return this.withIdentifier(\n {\n kind,\n prefix: configuration?.prefix,\n length: kind === \"nanoid\" ? configuration?.length : undefined,\n generate: configuration?.generate ?? this.state.autoGenerate?.generate,\n },\n this.state.isId\n );\n }\n\n private withIdentifier(declaration: AutoGenerate, isId: boolean) {\n const generator = identifierGenerator(declaration);\n const customDefault =\n this.state.hasDefault && !isGeneratorDefault(this.state.default);\n const generate =\n declaration.generate === true || (isId && declaration.generate !== false);\n const installed = generate && !customDefault;\n if (this.state.array && installed) refuseListGenerator(\"s.string\");\n const hasDefault = customDefault || installed;\n return new StringScalar(\n updateState(this, {\n isId,\n isUnique: isId || this.state.isUnique,\n autoGenerate: declaration,\n hasDefault,\n optional: hasDefault,\n default: installed\n ? generatorDefault(generator)\n : customDefault\n ? this.state.default\n : undefined,\n }),\n this._nativeType\n );\n }\n}\n\nexport const string = <\n Db extends NativeDialect = never,\n const Given extends ExactNativeTypeMap<Given> = never,\n>(\n nativeType?: NativeTypeArgument<Db, Given>\n) => {\n return new StringScalar(\n createDefaultState(\"string\", stringBase),\n admitNativeType(\"s.string\", nativeType)\n );\n};\n\nfunction refuseSecondIdPrefix(declared: {\n readonly kind: string;\n readonly prefix?: string | undefined;\n}): never {\n return refuseId(\n \"s.string().id\",\n \"prefix\",\n `Already declares '${declared.kind}'${declared.prefix ? ` (prefix '${declared.prefix}')` : \"\"}; spell prefix once on the format`\n );\n}\n"],"mappings":"mcAGA,SAAS,EACP,EACA,EACA,EACmC,CACnC,GAEE,OAAO,GAAU,WADjB,GAEA,CAAC,EAAM,MAAM,OACb,CAAC,EAAM,MAAM,OAAO,QAEpB,MAAO,CACL,KAAM,OACN,QAAS,iBAAiB,EAAS,uBACnC,SAAU,QACV,MAAO,EACR,CACH,IAAM,EAAU,EAAM,KAAK,MAAM,IAAM,EAAkB,IAAI,EAAM,CACnE,GAAI,IAAY,IAAA,IAAa,IAAY,EACvC,MAAO,CACL,KAAM,OACN,QAAS,UAAU,EAAQ,6BAA6B,EAAS,GACjE,SAAU,QACV,MAAO,EACR,CACH,EAAkB,IAAI,EAAO,EAAS,CAYxC,SAAgB,GACd,EACmC,CACnC,IAAM,EAAoB,IAAI,IAC9B,IAAK,GAAM,CAAC,EAAU,KAAU,EAAe,CAC7C,IAAM,EAAQ,EACZ,EACA,EACA,EACD,CACD,GAAI,IAAU,IAAA,GAAW,OAAO,GAMpC,SAAgB,EACd,EACmC,CACnC,IAAM,EAAoB,IAAI,IAC9B,IAAK,IAAM,KAAY,EAAQ,CAC7B,GAAI,CAAC,OAAO,OAAO,EAAQ,EAAS,CAAE,SACtC,IAAM,EAAQ,EACZ,EACA,EAAO,GACP,EACD,CACD,GAAI,IAAU,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A,EACqC,CACrC,OAAO,KAAK,WACV,SACA,OAAO,GAAY,SACf,CAAE,OAAQ,EAAS,SAAQ,CAC1B,GAAW,CAAE,SAAQ,CAC3B,CAGH,WAAmB,EAAsB,EAAkC,CACzE,IAAM,EACJ,OAAO,GAAY,SAAW,CAAE,OAAQ,EAAS,CAAG,EACtD,OAAO,KAAK,eACV,CACE,OACA,OAAQ,GAAe,OACvB,OAAQ,IAAS,SAAW,GAAe,OAAS,IAAA,GACpD,SAAU,GAAe,UAAY,KAAK,MAAM,cAAc,SAC/D,CACD,KAAK,MAAM,KACZ,CAGH,eAAuB,EAA2B,EAAe,CAC/D,IAAM,EAAY,EAAoB,EAAY,CAC5C,EACJ,KAAK,MAAM,YAAc,CAAC,EAAmB,KAAK,MAAM,QAAQ,CAG5D,GADJ,EAAY,WAAa,IAAS,GAAQ,EAAY,WAAa,KACvC,CAAC,EAC3B,KAAK,MAAM,OAAS,GAAW,EAAoB,WAAW,CAClE,IAAM,EAAa,GAAiB,EACpC,OAAO,IAAI,EACT,EAAY,KAAM,CAChB,OACA,SAAU,GAAQ,KAAK,MAAM,SAC7B,aAAc,EACd,aACA,SAAU,EACV,QAAS,EACL,EAAiB,EAAU,CAC3B,EACE,KAAK,MAAM,QACX,IAAA,GACP,CAAC,CACF,KAAK,YACN,GAIL,MAAa,GAIX,GAEO,IAAI,GACT,EAAmB,SAAU,GAAW,CACxC,EAAgB,WAAY,EAAW,CACxC,CAGH,SAAS,GAAqB,EAGpB,CACR,OAAO,EACL,gBACA,SACA,qBAAqB,EAAS,KAAK,GAAG,EAAS,OAAS,aAAa,EAAS,OAAO,IAAM,GAAG,mCAC/F"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { p as AnyDriver } from "../database-adapter-
|
|
2
|
-
import { d as SchemaDocument } from "../document-
|
|
1
|
+
import { p as AnyDriver } from "../database-adapter-cW0nmWM6.mjs";
|
|
2
|
+
import { d as SchemaDocument } from "../document-B8ClXlb7.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/migrations/introspect/types.d.ts
|
|
5
5
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"../introspect-
|
|
1
|
+
import{t as e}from"../introspect-dyBpdr2L.mjs";export{e as introspectSchema};
|
package/dist/schema/json.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { mi as Schema, mt as VibORMConfig, pt as VibORMClient } from "../database-adapter-
|
|
2
|
-
import { a as IndexDocument, c as RelationFieldDocument, d as SchemaDocument, f as VariantJunctionDocument, i as GenerateDocument, l as SCHEMA_DOCUMENT_VERSION, n as EnumDocument, o as JunctionDocument, p as ViewDocument, r as FieldDocument, s as ModelDocument, t as CompoundKeyDocument, u as ScalarFieldDocument } from "../document-
|
|
1
|
+
import { mi as Schema, mt as VibORMConfig, pt as VibORMClient } from "../database-adapter-cW0nmWM6.mjs";
|
|
2
|
+
import { a as IndexDocument, c as RelationFieldDocument, d as SchemaDocument, f as VariantJunctionDocument, i as GenerateDocument, l as SCHEMA_DOCUMENT_VERSION, n as EnumDocument, o as JunctionDocument, p as ViewDocument, r as FieldDocument, s as ModelDocument, t as CompoundKeyDocument, u as ScalarFieldDocument } from "../document-B8ClXlb7.mjs";
|
|
3
3
|
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
4
4
|
|
|
5
5
|
//#region src/schema/json/interpret.d.ts
|
package/dist/schema/json.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e,n as t,r as n,t as r}from"../json-
|
|
1
|
+
import{i as e,n as t,r as n,t as r}from"../json-DvvrTWUw.mjs";export{e as SCHEMA_DOCUMENT_VERSION,r as attachFieldSchemas,t as parseSchema,n as serializeSchema};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{f as e,m as t,t as n}from"./validation-ATmgN5RE.mjs";import{o as r}from"./sql-tegqTqGq.mjs";import{o as i}from"./value-guards-CBVIJXlI.mjs";import{k as a}from"./identifier-BdLx66pi.mjs";import{n as o}from"./facts-Bjnzv3j-.mjs";import{i as s}from"./keys-o4Pl6Vsg.mjs";import{c}from"./time-step-BIdl2Iy7.mjs";import{c as l,r as u,t as d}from"./validation-CEnhYqhl.mjs";import{l as f,n as p,u as m}from"./validator-CISkL46K.mjs";var h=class{},g=class extends h{compute(){throw Error(`Stored has no value`)}},_=class extends h{};const v=new WeakMap,y=Object.keys,b=Object.entries,x=Object.values,S=Object.fromEntries,C=Object.hasOwn,w=Array.isArray,T=e=>typeof e==`object`&&!!e,E=e=>{if(!T(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},D=(e,t,n)=>{let r=e.get(t);r?r.push(n):e.set(t,[n])},O=e=>e[`~`].names.ts,k=e=>e[`~`].names.sql,A=e=>e[`~`].state.scalars,j=e=>r.join(e,`, `),M=(e,t)=>e instanceof Date||t instanceof Date?e!=null&&t!=null&&+new Date(e)==+new Date(t):String(e)===String(t);function N(e){throw new t(e)}function P(t){throw new e(t)}function F(e,t,r,i,o){let s=d(e,t);if(s.issues){let e=i?[i]:[];throw new n(r,s.issues.map(t=>({path:[...e,...t.path?.map(String)??[]].join(`.`)||`root`,message:t.message})),{cause:a(s),meta:{model:O(o)}})}return s.value}function I(e){let t=new Set,n=[];for(let r of[e.ev,e.eb])for(let e of r.members)t.has(e.ef)||(t.add(e.ef),n.push({xl:r,pair:e}));return n}function L(e){if(e.kind===`reference`&&e.owner===`source`)return;let t=e.scope.edge,n=e.kind===`reference`&&t.kind===`foreignKey`?e.pairs.map(e=>e.target):[],r=t=>t.source===e.source&&t.field===e.name,i=t.kind===`foreignKey`||t.kind===`junction`?t.endpoints.find(e=>!r(e)):r(t.carrier)?e.scope.member?.inverse:t.carrier;return i&&n.push(i.field),{kind:`update`,writes:n}}function R(e,t,n,r){return e.membership(t,n,r)}function z(e,t,n,r){let i=e.index.get(t).get(n),a=i.edge,o=e.mu(i),s=t[`~`].state.relations[n][`~`].state.cardinality===`many`,c=e=>{let c=i.member??e.find(e=>e.variant===r),l=i.member===void 0;return[c,l,{scope:{edge:a,member:c},mu:o,name:l?`${n}.${c.variant}`:n,source:t,many:s}]};if(a.kind===`variantRowCarrier`){let[e,t,n]=c(a.members);return{...n,target:t?e.targetModel:a.carrier.source,kind:`reference`,owner:t?`source`:`target`,pairs:[{source:t?a.storage.idColumn.name:e.ee,target:t?e.ee:a.storage.idColumn.name}],discriminator:{xl:t?`source`:`target`,field:a.storage.typeColumn.name,value:e.entry.storedValue}}}if(a.kind===`variantJunctionCarrier`){let[e,t,n]=c(a.members);return{...n,target:t?e.tj.target.model:e.tj.source.model,kind:`junction`,table:e.tj.table,ev:t?e.tj.source:e.tj.target,eb:t?e.tj.target:e.tj.source,pb:e.mw?t?`target`:`source`:void 0}}let l=i.slot.source,u=a.endpoints[0],d=u.source===l&&u.field===n?a.endpoints[1]:u,f={scope:i,mu:o,name:n,source:t,target:d.source,many:s};if(a.kind===`foreignKey`){let e=a.owner.source===l&&a.owner.field===n;return{...f,kind:`reference`,owner:e?`source`:`target`,reference:a.reference,pairs:a.reference.members.map(t=>({source:e?t.tw:t.ee,target:e?t.ee:t.tw}))}}let p=a.tj,m=d===a.endpoints[1];return{...f,kind:`junction`,table:p.table,ev:m?p.source:p.target,eb:m?p.target:p.source,declared:p.declared}}function B(e){return e.kind===`reference`?V(e,`source`):e.ev.members.map(e=>e.ee)}const V=(e,t)=>[...e.discriminator?.xl===t?[e.discriminator.field]:[],...e.pairs.map(e=>e[t])];function H(e,t,n){return e.pd(t,n)}function U(e,t){let n=[];for(let{edge:r,member:i}of e.index.get(t).values())r.kind===`variantRowCarrier`&&!i&&n.push(r.storage.typeColumn,r.storage.idColumn);return n}function W(e,t,n){let r=A(t)[n],i=r?{name:t[`~`].getFieldName(n).sql,scalar:r,nullable:r[`~`].state.nullable===!0}:U(e,t).find(e=>e.name===n),{state:a,nativeType:o}=i.scalar[`~`];return{...i,state:a,nativeType:o}}function G(e,t){return[...t[`~`].scalarFieldNames,...U(e,t).map(e=>e.name)]}const K=new Set([`findMany`,`findUnique`,`findFirst`,`count`,`exist`,`aggregate`,`groupBy`]);function q(e){return K.has(e)}function J(e,n){let r=O(e),i=q(n)?n===`findUnique`&&s(e).addressableKeys.length===0?`View '${r}' has no key for ${n}.`:void 0:`View '${r}' is read-only (${n}).`;if(i)throw new t(i,{meta:{model:r,operation:n}})}const Y=[`multiply`,`divide`],X=[`set`,`increment`,`decrement`,`multiply`,`divide`];function Z(e){return e}function Q(e){return w(e)?e:[Z(e)]}function $(e,t,n){let r=e.get(t);return r===void 0&&(r=n(),e.set(t,r)),r}const ee=()=>({leaves:new WeakMap,kw:new WeakMap,jf:new WeakMap,documents:new WeakMap}),te=[];var ne=class{index;registry;#e=new WeakMap;#t=new WeakMap;#n=new WeakMap;#r=new WeakMap;#i=new WeakMap;#a=new WeakMap;schema;constructor(e,t){if(this.schema=e,t){this.index=t.index,this.registry=t.registry;return}c(e),this.index=p(e),this.registry=u(e,this.index)}lf(e,t,n){o(e)!==void 0&&J(e,t);let r=this.#o(e,t,n);if(t===`update`||t===`updateMany`){let t=this.fe(e,r.data);if(t)throw t}return r}#o(e,t,n){let r=this.registry.getModelSchemas(e).args[t],a={},o=[],s=F(r,(t===`update`||t===`updateMany`)&&i(n)&&i(n.data)?{...n,data:S(b(n.data).filter(([e,t])=>t instanceof h?(t instanceof g?o.push(e):a[e]=t,!1):!0).sort(([t],[n])=>{let r=t=>e[`~`].state.relations[t]?.[`~`].state.target.kind===`variants`;return Number(r(t))-Number(r(n))}))}:n,t,``,e);if(y(a).length===0&&o.length===0)return s;let c={...s.data,...a};for(let e of o)delete c[e];return{...s,data:c}}fe(e,n){if(i(n))for(let r of this.keys(e)){let a=n[r];if(!i(a))continue;let o=X.filter(e=>a[e]!==void 0),s;if(o.length!==1)s=`PK '${r}' requires one update op; got ${o.join(`, `)||`none`}.`;else if(o[0]!==`set`){let t=A(e)[r]?.[`~`].state.type;t===`number`||t===`decimal`&&Y.includes(o[0])?s=`Arithmetic updates unsupported on ${t} PK '${r}'; use set.`:(a.divide===0||a.divide===0n)&&(s=`Cannot divide PK '${r}' by zero.`)}if(s)return new t(s)}}a9(e,t){let n=this.registry.getModelSchemas(e).scalars,r={};for(let[i,a]of b(t))r[i]=F(n[i].create,a,`create`,i,e);return r}ys(e,t){return $(this.#e,e,()=>{let n=A(e),r=y(n).filter(n=>!t.includes(this.pd(e,n).name));return{required:r.filter(e=>n[e][`~`].state.optional!==!0),defaults:r.filter(t=>n[t][`~`].state.hasDefault===!0&&this.a9(e,{[t]:void 0})[t]!==void 0)}})}update(e,t){return Z(F(this.registry.getModelSchemas(e).core.update,t,`updateMany`,`data`,e))}keys(e){return s(e).pl?.fields??te}identity(e,t){let n={};for(let r of this.keys(e))n[r]=t[r];return n}membership(e,t,n){return $($($(this.#t,e,()=>new Map),t,()=>new Map),n,()=>z(this,e,t,n))}uh(e){return $(this.#a,e,()=>{let t=[];for(let[n,r]of this.index.get(e)??[]){let i=r.edge;if(i.kind!==`foreignKey`&&i.kind!==`junction`)continue;let a=this.membership(e,n),o=a.kind===`junction`?m(a.ev):i.kind===`foreignKey`&&a.owner===`target`?f(i):void 0;(o===`restrict`||o===`noAction`)&&t.push(n)}return t})}mu(e){return $(this.#i,e,()=>l(e))}pd(e,t){return $($(this.#n,e,()=>new Map),t,()=>W(this,e,t))}#s=new WeakMap;h0(e){return $(this.#s,e,ee)}rj(e){return $(this.#r,e,()=>G(this,e))}scalars(e,t){let n={};for(let r of e[`~`].scalarFieldNames){let e=t[r];e!==void 0&&(n[r]=e)}return n}};export{g as A,D as C,N as D,k as E,h as O,x as S,A as T,E as _,Z as a,b,L as c,V as d,P as f,T as g,w as h,$ as i,v as j,_ as k,I as l,C as m,Q as n,R as o,S as p,q as r,B as s,ne as t,H as u,j as v,M as w,y as x,O as y};
|
|
2
|
+
//# sourceMappingURL=schema-BzkBJTF-.mjs.map
|