viborm 1.2.3 → 1.3.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/README.md +6 -1
- package/dist/{adapter-internals-n3Mf3css.mjs → adapter-internals-AGgQRu5t.mjs} +1 -1
- package/dist/{adapter-internals-n3Mf3css.mjs.map → adapter-internals-AGgQRu5t.mjs.map} +1 -1
- package/dist/adapter-namespace-BpMbLKpL.mjs +2 -0
- package/dist/{adapter-namespace-DqkJQdrD.mjs.map → adapter-namespace-BpMbLKpL.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-BsbbSLw3.mjs → array-literal-BKdLfNzM.mjs} +1 -1
- package/dist/{array-literal-BsbbSLw3.mjs.map → array-literal-BKdLfNzM.mjs.map} +1 -1
- package/dist/{base-AdXAoy6l.mjs → base-D3m1S7Uc.mjs} +2 -2
- package/dist/{base-AdXAoy6l.mjs.map → base-D3m1S7Uc.mjs.map} +1 -1
- package/dist/{batch-refs-4L8ECdPU.mjs → batch-refs-B4zn-FAu.mjs} +2 -2
- package/dist/{batch-refs-4L8ECdPU.mjs.map → batch-refs-B4zn-FAu.mjs.map} +1 -1
- package/dist/{bind-parameter-capacity-CjPgqnmx.mjs → bind-parameter-capacity-qfEejeOX.mjs} +2 -2
- package/dist/{bind-parameter-capacity-CjPgqnmx.mjs.map → bind-parameter-capacity-qfEejeOX.mjs.map} +1 -1
- package/dist/builder-Df24l2Bd.mjs +2 -0
- package/dist/builder-Df24l2Bd.mjs.map +1 -0
- package/dist/bun-sql.d.mts +3 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +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-BO57X0TT.mjs → cache-CIPRF-pz.mjs} +2 -2
- package/dist/{cache-BO57X0TT.mjs.map → cache-CIPRF-pz.mjs.map} +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/{canonical-json-rfC2Dg0X.mjs → canonical-json-BReb5nFO.mjs} +2 -2
- package/dist/{canonical-json-rfC2Dg0X.mjs.map → canonical-json-BReb5nFO.mjs.map} +1 -1
- package/dist/chain-C7c1YTXD.mjs +2 -0
- package/dist/chain-C7c1YTXD.mjs.map +1 -0
- package/dist/cli.mjs +2 -2
- package/dist/cli.mjs.map +1 -1
- package/dist/{client-GoDZgqdq.d.mts → client-70MrTq1E.d.mts} +3 -3
- package/dist/client-DM1UHfYG.mjs +49 -0
- package/dist/client-DM1UHfYG.mjs.map +1 -0
- package/dist/client-_WKrPNmm.mjs +2 -0
- package/dist/client-_WKrPNmm.mjs.map +1 -0
- package/dist/client.d.mts +2 -2
- package/dist/client.mjs +1 -1
- package/dist/{clock-CK41KO7t.mjs → clock-C24RcpwO.mjs} +1 -1
- package/dist/{clock-CK41KO7t.mjs.map → clock-C24RcpwO.mjs.map} +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/controls-Da-efekX.mjs +2 -0
- package/dist/controls-Da-efekX.mjs.map +1 -0
- package/dist/{current-DyzK6OCh.mjs → current-oXcxSCBQ.mjs} +1 -1
- package/dist/{current-DyzK6OCh.mjs.map → current-oXcxSCBQ.mjs.map} +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/{datetime-physical-codec-oIhiYZEP.mjs → datetime-physical-codec-BEqQbIP_.mjs} +2 -2
- package/dist/{datetime-physical-codec-oIhiYZEP.mjs.map → datetime-physical-codec-BEqQbIP_.mjs.map} +1 -1
- package/dist/driver-B9fIori_.mjs +2 -0
- package/dist/driver-B9fIori_.mjs.map +1 -0
- package/dist/{driver-B19QlFqn.mjs → driver-CPD0Xxw2.mjs} +2 -2
- package/dist/{driver-B19QlFqn.mjs.map → driver-CPD0Xxw2.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/error-mapping-C9WgitPi.mjs +2 -0
- package/dist/error-mapping-C9WgitPi.mjs.map +1 -0
- package/dist/every-1pKZteeB.mjs +2 -0
- package/dist/{every-DCY4HV0X.mjs.map → every-1pKZteeB.mjs.map} +1 -1
- package/dist/{execution-context-BKR3bgES.mjs → execution-context-rJXTRVrJ.mjs} +1 -1
- package/dist/{execution-context-BKR3bgES.mjs.map → execution-context-rJXTRVrJ.mjs.map} +1 -1
- package/dist/{fs-estate-CAhDg7nY.mjs → fs-estate-i8Zlr1OQ.mjs} +2 -2
- package/dist/{fs-estate-CAhDg7nY.mjs.map → fs-estate-i8Zlr1OQ.mjs.map} +1 -1
- package/dist/{geo-area-codec-1SY9im7O.mjs → geo-area-codec-CbkmFArQ.mjs} +2 -2
- package/dist/{geo-area-codec-1SY9im7O.mjs.map → geo-area-codec-CbkmFArQ.mjs.map} +1 -1
- package/dist/geo-point-codec-DyEHMdJg.mjs +2 -0
- package/dist/geo-point-codec-DyEHMdJg.mjs.map +1 -0
- package/dist/hydration-DsyHNSDS.mjs +2 -0
- package/dist/{hydration-CAxOL4aI.mjs.map → hydration-DsyHNSDS.mjs.map} +1 -1
- package/dist/identifier-conversion-DaZ9yNpv.mjs +2 -0
- package/dist/{identifier-conversion-GgbwHc2G.mjs.map → identifier-conversion-DaZ9yNpv.mjs.map} +1 -1
- package/dist/{identity-CLFhCTZx.mjs → identity-oQvIe7u8.mjs} +2 -2
- package/dist/{identity-CLFhCTZx.mjs.map → identity-oQvIe7u8.mjs.map} +1 -1
- package/dist/{index-BaK35ze2.d.mts → index-VsM29vYN.d.mts} +5269 -4918
- package/dist/index.d.mts +3 -3
- 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/{invariant-BnLYqsHO.mjs → invariant-D57gi_yW.mjs} +1 -1
- package/dist/{invariant-BnLYqsHO.mjs.map → invariant-D57gi_yW.mjs.map} +1 -1
- package/dist/{json-number-CGXpPu4D.mjs → json-number-DvmiNx0n.mjs} +1 -1
- package/dist/{json-number-CGXpPu4D.mjs.map → json-number-DvmiNx0n.mjs.map} +1 -1
- package/dist/key-D_kagnFv.mjs +2 -0
- package/dist/{key-BeoOwGr3.mjs.map → key-D_kagnFv.mjs.map} +1 -1
- package/dist/{libsql-x0RPVRDS.mjs → libsql-DFAoHXrI.mjs} +3 -3
- package/dist/{libsql-x0RPVRDS.mjs.map → libsql-DFAoHXrI.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-gv5jLGYm.mjs → memory-GTWgeDNY.mjs} +2 -2
- package/dist/{memory-gv5jLGYm.mjs.map → memory-GTWgeDNY.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +5 -5
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +5 -5
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +5 -5
- package/dist/migrations/sqlite.mjs +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/tenant.d.mts +3 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/{migrations-DTObIjAm.mjs → migrations-Bn1SatyB.mjs} +2 -2
- package/dist/{migrations-DTObIjAm.mjs.map → migrations-Bn1SatyB.mjs.map} +1 -1
- package/dist/migrations.d.mts +5 -5
- package/dist/migrations.mjs +1 -1
- package/dist/mysql-adapter-C6c5govr.mjs +2 -0
- package/dist/{mysql-adapter-DkJPfoGf.mjs.map → mysql-adapter-C6c5govr.mjs.map} +1 -1
- package/dist/{mysql-B5cqxG99.mjs → mysql-xChEivOe.mjs} +6 -6
- package/dist/{mysql-B5cqxG99.mjs.map → mysql-xChEivOe.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/{native-types-veeTk36s.mjs → native-types-asNCr26n.mjs} +1 -1
- package/dist/{native-types-veeTk36s.mjs.map → native-types-asNCr26n.mjs.map} +1 -1
- package/dist/neon-http.d.mts +3 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/{object-store-DQR6bTBY.mjs → object-store-ChYHlOMD.mjs} +2 -2
- package/dist/{object-store-DQR6bTBY.mjs.map → object-store-ChYHlOMD.mjs.map} +1 -1
- package/dist/{object-store-Cj8Cnnba.d.mts → object-store-D9mvOHP4.d.mts} +4 -4
- package/dist/{observation-DUSm7oXK.mjs → observation-Co72iCd1.mjs} +2 -2
- package/dist/{observation-DUSm7oXK.mjs.map → observation-Co72iCd1.mjs.map} +1 -1
- package/dist/permissions.d.mts +424 -0
- package/dist/permissions.mjs +2 -0
- package/dist/permissions.mjs.map +1 -0
- package/dist/pg.d.mts +9 -1
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +3 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/{physical-6V_LNU3L.mjs → physical-CAOaNM4R.mjs} +2 -2
- package/dist/{physical-6V_LNU3L.mjs.map → physical-CAOaNM4R.mjs.map} +1 -1
- package/dist/{pinned-session-CLxj5M5e.mjs → pinned-session-BTplL3iZ.mjs} +2 -2
- package/dist/{pinned-session-CLxj5M5e.mjs.map → pinned-session-BTplL3iZ.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-DH-K2gSq.d.mts → planner-C1NzLBge.d.mts} +1 -1
- package/dist/{postgres-DrXDok0O.mjs → postgres-BqAxDWTQ.mjs} +4 -4
- package/dist/{postgres-DrXDok0O.mjs.map → postgres-BqAxDWTQ.mjs.map} +1 -1
- package/dist/postgres-adapter-CGthb5yh.mjs +2 -0
- package/dist/postgres-adapter-CGthb5yh.mjs.map +1 -0
- package/dist/postgres-adapter-CxEit2-v.mjs +2 -0
- package/dist/postgres-adapter-CxEit2-v.mjs.map +1 -0
- package/dist/{postgres-result-7F0DllQe.mjs → postgres-result-KyBKBNJr.mjs} +2 -2
- package/dist/{postgres-result-7F0DllQe.mjs.map → postgres-result-KyBKBNJr.mjs.map} +1 -1
- package/dist/postgres.d.mts +3 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-BHATED_m.mjs → provider-limits-Da00ilvv.mjs} +2 -2
- package/dist/{provider-limits-BHATED_m.mjs.map → provider-limits-Da00ilvv.mjs.map} +1 -1
- package/dist/{result-parsing-DRXC89ek.mjs → result-parsing-8wEK3GY1.mjs} +1 -1
- package/dist/{result-parsing-DRXC89ek.mjs.map → result-parsing-8wEK3GY1.mjs.map} +1 -1
- package/dist/result-shape-CDgX_vzn.mjs +2 -0
- package/dist/result-shape-CDgX_vzn.mjs.map +1 -0
- package/dist/scalar-S8yMvdmx.mjs +4 -0
- package/dist/scalar-S8yMvdmx.mjs.map +1 -0
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/schema/json.mjs.map +1 -1
- package/dist/schema-9N9jQlVL.mjs +2 -0
- package/dist/{schema-Cjem1-0f.mjs.map → schema-9N9jQlVL.mjs.map} +1 -1
- package/dist/{schema-introspection-DEYGC2qg.mjs → schema-introspection-CyXKReK1.mjs} +4 -4
- package/dist/{schema-introspection-DEYGC2qg.mjs.map → schema-introspection-CyXKReK1.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-f1UGoblh.mjs → select-assembly-CkGe2ABs.mjs} +2 -2
- package/dist/{select-assembly-f1UGoblh.mjs.map → select-assembly-CkGe2ABs.mjs.map} +1 -1
- package/dist/{settle-B9Vg1FnP.mjs → settle-CS_k6Ztm.mjs} +2 -2
- package/dist/{settle-B9Vg1FnP.mjs.map → settle-CS_k6Ztm.mjs.map} +1 -1
- package/dist/soft-delete.d.mts +27 -96
- package/dist/soft-delete.mjs +1 -1
- package/dist/soft-delete.mjs.map +1 -1
- package/dist/sql-Bhxq9arK.mjs +2 -0
- package/dist/sql-Bhxq9arK.mjs.map +1 -0
- package/dist/{sql-BvfwUKIh.d.mts → sql-EsoN_7Et.d.mts} +24 -0
- package/dist/{sql-statement-tokens-BBcoGmJb.mjs → sql-statement-tokens-CFi1y3bK.mjs} +1 -1
- package/dist/{sql-statement-tokens-BBcoGmJb.mjs.map → sql-statement-tokens-CFi1y3bK.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-BXAJy3mI.mjs +2 -0
- package/dist/sqlite-adapter-BXAJy3mI.mjs.map +1 -0
- package/dist/{sqlite-utils-DlgokMJN.mjs → sqlite-utils-D_cypcyW.mjs} +2 -2
- package/dist/{sqlite-utils-DlgokMJN.mjs.map → sqlite-utils-D_cypcyW.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +3 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/{standard-sql-Bk4RZPqJ.mjs → standard-sql-CoGqv-iX.mjs} +3 -3
- package/dist/standard-sql-CoGqv-iX.mjs.map +1 -0
- package/dist/{suppressed-failure-BwULh-8h.mjs → suppressed-failure-Bdo2aK81.mjs} +1 -1
- package/dist/{suppressed-failure-BwULh-8h.mjs.map → suppressed-failure-Bdo2aK81.mjs.map} +1 -1
- package/dist/to-many-C1PuFIpf.mjs +2 -0
- package/dist/to-many-C1PuFIpf.mjs.map +1 -0
- package/dist/{transaction-Bnl6ULTw.mjs → transaction-4dfqals6.mjs} +2 -2
- package/dist/{transaction-Bnl6ULTw.mjs.map → transaction-4dfqals6.mjs.map} +1 -1
- package/dist/{transaction-operation-CKK3l_9x.mjs → transaction-operation-CU1zlxiG.mjs} +2 -2
- package/dist/{transaction-operation-CKK3l_9x.mjs.map → transaction-operation-CU1zlxiG.mjs.map} +1 -1
- package/dist/{types-C4v6iAmY.mjs → types-C5Oxz9yp.mjs} +1 -1
- package/dist/{types-C4v6iAmY.mjs.map → types-C5Oxz9yp.mjs.map} +1 -1
- package/dist/{utils-CZNaOZR7.mjs → utils-CtFUE8UN.mjs} +4 -4
- package/dist/{utils-CZNaOZR7.mjs.map → utils-CtFUE8UN.mjs.map} +1 -1
- package/dist/v-CYTUI0H5.mjs +2 -0
- package/dist/v-CYTUI0H5.mjs.map +1 -0
- package/dist/validation-BQtO6srU.mjs +2 -0
- package/dist/{validation-PF9-_nKd.mjs.map → validation-BQtO6srU.mjs.map} +1 -1
- package/dist/validation-BamBwne9.mjs +2 -0
- package/dist/validation-BamBwne9.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-DgffZq9C.mjs +2 -0
- package/dist/validator-DgffZq9C.mjs.map +1 -0
- package/dist/version-CXuJzC-q.mjs +2 -0
- package/dist/{version-Bemp-64P.mjs.map → version-CXuJzC-q.mjs.map} +1 -1
- package/package.json +35 -9
- package/dist/adapter-namespace-DqkJQdrD.mjs +0 -2
- package/dist/builder-Ycvq3ETg.mjs +0 -2
- package/dist/builder-Ycvq3ETg.mjs.map +0 -1
- package/dist/chain-Dh0FV72b.mjs +0 -2
- package/dist/chain-Dh0FV72b.mjs.map +0 -1
- package/dist/client-B1p6Le_h.mjs +0 -49
- package/dist/client-B1p6Le_h.mjs.map +0 -1
- package/dist/client-BLiBmykn.mjs +0 -2
- package/dist/client-BLiBmykn.mjs.map +0 -1
- package/dist/controls-DXgIn4zh.mjs +0 -2
- package/dist/controls-DXgIn4zh.mjs.map +0 -1
- package/dist/driver-BlnKXPFF.mjs +0 -2
- package/dist/driver-BlnKXPFF.mjs.map +0 -1
- package/dist/error-mapping-CnPCv1dm.mjs +0 -2
- package/dist/error-mapping-CnPCv1dm.mjs.map +0 -1
- package/dist/every-DCY4HV0X.mjs +0 -2
- package/dist/geo-point-codec-lhxH42SK.mjs +0 -2
- package/dist/geo-point-codec-lhxH42SK.mjs.map +0 -1
- package/dist/hydration-CAxOL4aI.mjs +0 -2
- package/dist/identifier-conversion-GgbwHc2G.mjs +0 -2
- package/dist/identifier-hQCs8M1n.mjs +0 -2
- package/dist/identifier-hQCs8M1n.mjs.map +0 -1
- package/dist/key-BeoOwGr3.mjs +0 -2
- package/dist/mysql-adapter-DkJPfoGf.mjs +0 -2
- package/dist/postgres-adapter-B3SQvcV1.mjs +0 -2
- package/dist/postgres-adapter-B3SQvcV1.mjs.map +0 -1
- package/dist/postgres-adapter-CQD2oGuD.mjs +0 -2
- package/dist/postgres-adapter-CQD2oGuD.mjs.map +0 -1
- package/dist/registration-preflight-DEjv050M.mjs +0 -4
- package/dist/registration-preflight-DEjv050M.mjs.map +0 -1
- package/dist/result-shape-CTNdNSW3.mjs +0 -2
- package/dist/result-shape-CTNdNSW3.mjs.map +0 -1
- package/dist/scalar-U0wD5bKy.mjs +0 -2
- package/dist/scalar-U0wD5bKy.mjs.map +0 -1
- package/dist/schema-Cjem1-0f.mjs +0 -2
- package/dist/sql-Bp7jicEX.mjs +0 -2
- package/dist/sql-Bp7jicEX.mjs.map +0 -1
- package/dist/sqlite-adapter-CW_3l6ea.mjs +0 -2
- package/dist/sqlite-adapter-CW_3l6ea.mjs.map +0 -1
- package/dist/standard-sql-Bk4RZPqJ.mjs.map +0 -1
- package/dist/terminal-C8cq1WWX.mjs +0 -2
- package/dist/terminal-C8cq1WWX.mjs.map +0 -1
- package/dist/v-D5Z06FKN.mjs +0 -2
- package/dist/v-D5Z06FKN.mjs.map +0 -1
- package/dist/validation-Dk9Q_-C7.mjs +0 -2
- package/dist/validation-Dk9Q_-C7.mjs.map +0 -1
- package/dist/validation-PF9-_nKd.mjs +0 -2
- package/dist/validator-X9-bwtRo.mjs +0 -2
- package/dist/validator-X9-bwtRo.mjs.map +0 -1
- package/dist/version-Bemp-64P.mjs +0 -2
- /package/dist/{contract-CIIqgFyb.d.mts → contract-Dw0FR78e.d.mts} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scalar-S8yMvdmx.mjs","names":["model","#state","#internal","state","#state","#internal","state","#withForeignKeyAction","#localFields","state","state","v","#state","#internal","model","#names","#nameRegistry","#scalarFieldNames","#relationNames","state","catalogs","v","state"],"sources":["../src/schema/registration-preflight.ts","../src/schema/validation/error.ts","../src/schema/record.ts","../src/schema/relation/polymorphic.ts","../src/schema/relation/to-one.ts","../src/schema/model/helper.ts","../src/schema/model/model.ts","../src/schema/scalars/common.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\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 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 a model; pass an explicit object containing only s.model() definitions`,\n severity: \"error\",\n model: modelKey,\n };\n const claimed = model[\"~\"].names.ts ?? claimedInThisPass.get(model);\n if (claimed !== undefined && claimed !== modelKey)\n return doubleRegistrationIssue(claimed, modelKey);\n claimedInThisPass.set(model, modelKey);\n }\n return undefined;\n}\n\nfunction doubleRegistrationIssue(\n claimed: string,\n modelKey: string\n): SchemaValidationIssue {\n return {\n code: \"M003\",\n message: `Model registered as '${claimed}' cannot also be registered as '${modelKey}'; one model object binds one schema key`,\n severity: \"error\",\n model: modelKey,\n };\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\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","// Records keyed by DATA.\n//\n// A schema is built from maps whose keys come from somewhere else: a model\n// shape's field key, a document's model/field/variant key, an enum reference, a\n// default's own object keys. `record[key] = value` is not a safe way to build\n// such a map, because `__proto__` is an accessor on `Object.prototype`:\n// assigning through it sets a prototype and creates NO own key. The entry\n// disappears, and what is left is a well-formed object, so nothing downstream\n// can notice the loss.\n//\n// Reading has the mirror problem: `record[key]` resolves inherited members, so\n// a data key of `__proto__`, `constructor` or `toString` answers something the\n// map never held.\n//\n// One owner for both, used everywhere a key comes from data — the JSON\n// document's maps and `s.model(...)`'s classified member maps alike. It carries\n// no refusal: whether a key is a legal identifier is `isValidSchemaIdentifier`'s\n// question, asked at hydration and by the document reader, and the answer is the\n// same whichever way the key was written. The document READER needs neither\n// helper, because it asks that question before anything is written.\n\n/** A map with no inherited members, so a data key can only find what was put. */\nexport function emptyRecord<T>(): Record<string, T> {\n return Object.create(null);\n}\n\n/** Write one own key, whatever it is called. */\nexport function put<T>(target: Record<string, T>, key: string, value: T): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/** Read one own key, or nothing. */\nexport function own<T>(\n source: Record<string, T> | undefined,\n key: string\n): T | undefined {\n if (source === undefined || !Object.hasOwn(source, key)) return;\n return source[key];\n}\n","// Variant target domains: the normalization owner and the two variant terminals.\n//\n// \"Polymorphic\" is not a relation family. It is the derived observation that a\n// declaration's TARGET DOMAIN holds named variants instead of one model, which\n// is why the two variant terminals are reached through the same `s.toOne` /\n// `s.toMany` factories as the model-target ones. What is irreducibly different\n// is the legal local configuration: a row-held variant to-one may be\n// `.optional()` and owns no public foreign key, and a member-junction variant\n// to-many names one junction per variant through an exact `.through(...)` map.\n\nimport type { Model } from \"@schema/model\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport { isValidSchemaIdentifier } from \"../identifier\";\nimport {\n createTargetSettlement,\n declaredKeys,\n hasExactKeys,\n isPlainRecord,\n normalizeRelationName,\n type RelationBuilder,\n readCallerProperty,\n refuseRelationInput,\n} from \"./terminal\";\nimport type {\n AnyRelation,\n Getter,\n RelationInternal,\n Replace,\n VariantEntry,\n VariantJunctionOverride,\n VariantManyEntry,\n VariantToManyState,\n VariantToOneState,\n} from \"./types\";\n\n/**\n * The stored-discriminator grammar. A stored value is written to a physical\n * column and read back by migrations and predicates, so it admits namespaced\n * and versioned spellings the public variant key does not.\n */\nconst STORED_VALUE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,190}$/;\n\nconst THROUGH_ENTRY_KEYS = [\"table\", \"source\", \"target\"] as const;\n\n// =============================================================================\n// FACTORY-LEVEL TYPES\n// =============================================================================\n\nexport type VariantGetterMap = Readonly<Record<string, Getter>>;\n\n/**\n * The map overload's phantom refusal.\n *\n * It is NOT redundant with {@link GetterOnly}. With the map overload first and\n * an unconstrained getter overload second, a structurally-map argument that\n * fails this guard would otherwise fall through to the getter overload, whose\n * conditional return answers `never` — and `never` is assignable to a model\n * shape, so the refusal would disappear entirely. This guard uniquely owns\n * \"structurally a map, but not a legal variant map\"; `GetterOnly` uniquely owns\n * \"not a map at all and not a getter\".\n */\nexport type VariantMapGuard<Entries> = string extends keyof Entries\n ? {\n readonly \"a variant map needs literal keys, not a string index signature\": never;\n }\n : [keyof Entries] extends [never]\n ? { readonly \"a variant map needs at least one variant\": never }\n : unknown;\n\nexport type VariantOptions<Entries> = {\n readonly values: { readonly [Key in keyof Entries]: string };\n};\n\n/**\n * The whole options bag is exact, not only `values`: a NON-FRESH bag with a\n * sibling key beside `values` sails through excess-property checking, so the\n * unknown keys are refused structurally.\n */\nexport type ExactVariantOptions<Options, Entries> = Options extends undefined\n ? unknown\n : Record<Exclude<keyof Options, \"values\">, never> & {\n readonly values: Record<\n Exclude<\n keyof (Options extends { readonly values: infer Values }\n ? Values\n : never),\n keyof Entries\n >,\n never\n >;\n };\n\n/**\n * Normalized entries carry the getter's exact type and a plain `string` stored\n * value: the stored discriminator is runtime storage, never a public result\n * discriminator, so carrying its literal would be a public type parameter no\n * consumer reads.\n */\nexport type NormalizedOneEntries<Entries> = {\n readonly [Key in keyof Entries]: {\n readonly getter: Entries[Key];\n readonly storedValue: string;\n };\n};\n\nexport type NormalizedManyEntries<Entries> = {\n readonly [Key in keyof Entries]: {\n readonly getter: Entries[Key];\n readonly storedValue: string;\n readonly junction?: VariantJunctionOverride;\n };\n};\n\ntype VariantEntriesOfState<State> = State extends {\n readonly target: { readonly entries: infer Entries };\n}\n ? Entries\n : never;\n\ntype VariantThroughMap<Entries> = {\n readonly [Key in keyof Entries]: VariantJunctionOverride;\n};\n\ntype ExactVariantThroughMap<Given, Entries> = Record<\n Exclude<keyof Given, keyof Entries>,\n never\n> & {\n readonly [Key in keyof Given]: Record<\n Exclude<keyof Given[Key], keyof VariantJunctionOverride>,\n never\n >;\n};\n\n// =============================================================================\n// TERMINAL CAPABILITY SURFACES\n// =============================================================================\n\n/** A slot that holds at most one membership across its variants. */\nexport type VariantToOneRelation<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): VariantToOneRelation<Replace<State, { readonly name: Name }>>;\n optional(): VariantToOneRelation<Replace<State, { readonly optional: true }>>;\n};\n\n/**\n * A slot that holds a collection across its variants. No `.optional()`: an\n * empty collection is already the empty case.\n */\nexport type VariantToManyRelation<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): VariantToManyRelation<Replace<State, { readonly name: Name }>>;\n through<\n const ThroughMap extends VariantThroughMap<VariantEntriesOfState<State>>,\n >(\n map: ThroughMap &\n ExactVariantThroughMap<ThroughMap, VariantEntriesOfState<State>>\n ): VariantToManyRelation<State>;\n};\n\n// =============================================================================\n// NORMALIZATION\n// =============================================================================\n\n/**\n * Read the target map and its options ONCE, judge every structurally knowable\n * fact, and build the single normalized entry map. There is no separately\n * stored `targets`, `values` or `through` map to keep in sync.\n *\n * Every own property at both map levels is read exactly once here and pinned as\n * a plain value: a live accessor could otherwise answer validation with one\n * value and the storage builder with another. Reading a property's value does\n * not invoke a target thunk; getters are stored as functions and stay lazy.\n */\nexport function normalizeVariantEntries(\n builder: RelationBuilder,\n variants: unknown,\n options: unknown\n): Readonly<Record<string, VariantEntry>> {\n if (!isPlainRecord(variants)) {\n refuseRelationInput(\n builder,\n \"target\",\n \"A relation target is either `() => model` or a plain map of named `() => model` getters\"\n );\n }\n const variantKeys = declaredKeys(variants);\n if (variantKeys.length === 0) {\n refuseRelationInput(\n builder,\n \"target\",\n \"A variant map needs at least one variant\"\n );\n }\n const storedValues = readStoredValues(builder, variantKeys, options);\n const entries: Record<string, VariantEntry> = {};\n for (const variantKey of variantKeys) {\n if (!isValidSchemaIdentifier(variantKey)) {\n refuseRelationInput(\n builder,\n `target.${variantKey}`,\n `Variant key '${variantKey}' is not a valid schema identifier`\n );\n }\n const getter = readCallerProperty(\n builder,\n variants,\n variantKey,\n `target.${variantKey}`\n );\n if (typeof getter !== \"function\") {\n refuseRelationInput(\n builder,\n `target.${variantKey}`,\n `Variant '${variantKey}' must be a lazy getter; write \\`() => model\\` rather than the model itself`\n );\n }\n entries[variantKey] = Object.freeze({\n getter,\n storedValue: storedValues[variantKey] ?? variantKey,\n });\n }\n return Object.freeze(entries);\n}\n\n/**\n * The stored discriminator per variant: each public key by default, or the\n * exact `values` bag when one is supplied. An explicit `undefined` is\n * equivalent to omission; `{}` is not, because it declares an options bag\n * without the one option it may carry.\n */\nfunction readStoredValues(\n builder: RelationBuilder,\n variantKeys: readonly string[],\n options: unknown\n): Record<string, string> {\n if (options === undefined) return {};\n if (!isPlainRecord(options)) {\n refuseRelationInput(\n builder,\n \"options\",\n \"Relation options must be a plain `{ values }` record; omit the argument to use each variant key as its stored value\"\n );\n }\n if (!hasExactKeys(declaredKeys(options), [\"values\"])) {\n refuseRelationInput(\n builder,\n \"options\",\n \"Relation options carry exactly one key, `values`; omit the argument to use each variant key as its stored value\"\n );\n }\n const values = readCallerProperty(\n builder,\n options,\n \"values\",\n \"options.values\"\n );\n if (!isPlainRecord(values)) {\n refuseRelationInput(\n builder,\n \"options.values\",\n \"`values` must be a plain record keyed by every variant\"\n );\n }\n const valueKeys = declaredKeys(values);\n if (!hasExactKeys(valueKeys, variantKeys)) {\n refuseRelationInput(\n builder,\n \"options.values\",\n `\\`values\\` must be exact over the variant keys ${renderKeys(variantKeys)}; it declares ${renderKeys(valueKeys)}`\n );\n }\n const storedValues: Record<string, string> = {};\n const claimed = new Set<string>();\n for (const variantKey of variantKeys) {\n const storedValue = readCallerProperty(\n builder,\n values,\n variantKey,\n `options.values.${variantKey}`\n );\n if (typeof storedValue !== \"string\" || !STORED_VALUE.test(storedValue)) {\n refuseRelationInput(\n builder,\n `options.values.${variantKey}`,\n `Stored value for variant '${variantKey}' must match the stored-discriminator grammar`\n );\n }\n if (claimed.has(storedValue)) {\n refuseRelationInput(\n builder,\n `options.values.${variantKey}`,\n `Stored value '${storedValue}' is declared for more than one variant`\n );\n }\n claimed.add(storedValue);\n storedValues[variantKey] = storedValue;\n }\n return storedValues;\n}\n\nfunction renderKeys(keys: readonly string[]): string {\n return `[${keys.map((key) => `'${key}'`).join(\", \")}]`;\n}\n\n/**\n * Fold one member-junction override into each normalized entry. The outer map\n * is exact over the variants and every inner value is exact — the runtime\n * mirror of the `.through()` type contract, and the reason there is no second\n * `through` map to keep in sync with the entries.\n */\nfunction foldMemberJunctions(\n entries: Readonly<Record<string, VariantEntry>>,\n through: unknown\n): Readonly<Record<string, VariantManyEntry>> {\n const variantKeys = Object.keys(entries);\n if (!isPlainRecord(through)) {\n refuseRelationInput(\n \"s.toMany\",\n \"through\",\n \"`.through()` takes a plain map keyed by every variant\"\n );\n }\n if (!hasExactKeys(declaredKeys(through), variantKeys)) {\n refuseRelationInput(\n \"s.toMany\",\n \"through\",\n `\\`.through()\\` must be exact over the variant keys ${renderKeys(variantKeys)}`\n );\n }\n const folded: Record<string, VariantManyEntry> = {};\n for (const [variantKey, entry] of Object.entries(entries)) {\n const override = readCallerProperty(\n \"s.toMany\",\n through,\n variantKey,\n `through.${variantKey}`\n );\n folded[variantKey] = Object.freeze({\n ...entry,\n junction: readJunctionOverride(variantKey, override),\n });\n }\n return Object.freeze(folded);\n}\n\nfunction readJunctionOverride(\n variantKey: string,\n override: unknown\n): VariantJunctionOverride {\n const path = `through.${variantKey}`;\n if (!isPlainRecord(override)) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `Member junction '${variantKey}' must be a plain \\`{ table, source, target }\\` record`\n );\n }\n const table = readCallerProperty(\n \"s.toMany\",\n override,\n \"table\",\n `${path}.table`\n );\n const source = readCallerProperty(\n \"s.toMany\",\n override,\n \"source\",\n `${path}.source`\n );\n const target = readCallerProperty(\n \"s.toMany\",\n override,\n \"target\",\n `${path}.target`\n );\n if (\n !hasExactKeys(declaredKeys(override), THROUGH_ENTRY_KEYS) ||\n typeof table !== \"string\" ||\n typeof source !== \"string\" ||\n typeof target !== \"string\"\n ) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `Member junction '${variantKey}' declares exactly \\`table\\`, \\`source\\` and \\`target\\`, all strings`\n );\n }\n return Object.freeze({ table, source, target });\n}\n\n// =============================================================================\n// TERMINALS\n// =============================================================================\n\n/**\n * Private terminal machinery. None of the four terminal classes is exported\n * from its module, let alone from the package: callers see only the\n * capabilities the two factories return. The two constructor helpers below are\n * the whole cross-module surface.\n */\nclass VariantToOne {\n readonly #state: VariantToOneState;\n readonly #internal: RelationInternal<VariantToOneState>;\n\n constructor(state: VariantToOneState) {\n this.#state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.#state,\n settleTarget: createTargetSettlement((variantKey) =>\n readVariantGetter(this.#state, variantKey)\n ),\n });\n }\n\n name(name: string): VariantToOne {\n return new VariantToOne({\n ...this.#state,\n name: normalizeRelationName(\"s.toOne\", name),\n });\n }\n\n optional(): VariantToOne {\n return new VariantToOne({ ...this.#state, optional: true });\n }\n\n get \"~\"(): RelationInternal<VariantToOneState> {\n return this.#internal;\n }\n}\n\nclass VariantToMany {\n readonly #state: VariantToManyState;\n readonly #internal: RelationInternal<VariantToManyState>;\n\n constructor(state: VariantToManyState) {\n this.#state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.#state,\n settleTarget: createTargetSettlement((variantKey) =>\n readVariantGetter(this.#state, variantKey)\n ),\n });\n }\n\n name(name: string): VariantToMany {\n return new VariantToMany({\n ...this.#state,\n name: normalizeRelationName(\"s.toMany\", name),\n });\n }\n\n through(map: unknown): VariantToMany {\n return new VariantToMany({\n ...this.#state,\n target: {\n kind: \"variants\",\n entries: foldMemberJunctions(this.#state.target.entries, map),\n },\n });\n }\n\n get \"~\"(): RelationInternal<VariantToManyState> {\n return this.#internal;\n }\n}\n\n/** Construct the row-held variant terminal for `s.toOne`. */\nexport function variantToOneTerminal(state: VariantToOneState): AnyRelation {\n return new VariantToOne(state);\n}\n\n/** Construct the member-junction variant terminal for `s.toMany`. */\nexport function variantToManyTerminal(state: VariantToManyState): AnyRelation {\n return new VariantToMany(state);\n}\n\nfunction readVariantGetter(\n state: VariantToOneState | VariantToManyState,\n variantKey: string | undefined\n): unknown {\n if (variantKey === undefined) return undefined;\n const entry = state.target.entries[variantKey];\n return entry === undefined ? undefined : entry.getter;\n}\n\n// =============================================================================\n// RESOLVED VARIANT STORAGE COLUMN\n// =============================================================================\n// Resolution OUTPUT, not declaration state: one private column the variant\n// row-storage owner derives, carried on the resolved edge and read by the\n// serializer and the engine. The descriptors that used to sit beside it are\n// gone — the resolved edge IS the topology, and a second copy of it on the\n// model was a second answer to every question the edge already answers.\n\nexport interface PolymorphicStorageColumn {\n readonly name: string;\n readonly scalar: Scalar;\n readonly nullable: boolean;\n /**\n * The KEY this private column stands in for, when it stands in for one.\n *\n * A row carrier's id column holds every variant's primary key, and what\n * those keys hold — an identifier domain above all — may be DERIVED rather\n * than declared: the ordinary one-to-one child whose primary key IS its\n * parent foreign key declares nothing and still holds uuids. The scalar\n * alone cannot answer that (derivation is keyed by model and field, never by\n * a scalar instance two models may share), so the column carries the pair\n * the one lookup takes. Every variant's key agrees on the answer or the\n * carrier does not exist — that agreement is what the identifier-domain\n * derivation refuses when it fails — so the FIRST member's key is the\n * carrier's key.\n *\n * The type discriminator column stands in for no key and carries none.\n */\n readonly reference?: {\n readonly model: Model<any>;\n readonly field: string;\n };\n}\n","// `s.toOne` — one of the two relation factories.\n//\n// The factory states the SLOT CARDINALITY (one) and its argument states the\n// TARGET DOMAIN (one model, or named variants). Which endpoint owns a foreign\n// key, whether the pair is one-to-one or many-to-one, and whether a model-target\n// slot may be empty are DERIVED later by the full-schema topology owner.\n\nimport {\n type ExactVariantOptions,\n type NormalizedOneEntries,\n normalizeVariantEntries,\n type VariantGetterMap,\n type VariantMapGuard,\n type VariantOptions,\n type VariantToOneRelation,\n variantToOneTerminal,\n} from \"./polymorphic\";\nimport {\n createTargetSettlement,\n normalizeFieldTuple,\n normalizeReferentialAction,\n normalizeRelationName,\n refuseRelationInput,\n} from \"./terminal\";\nimport type {\n AnyRelation,\n ForeignKeyDeclaration,\n Getter,\n GetterOnly,\n ModelToOneState,\n NonEmptyFieldTuple,\n ReferentialAction,\n RelationInternal,\n Replace,\n} from \"./types\";\n\n// =============================================================================\n// TERMINAL CAPABILITY SURFACE\n// =============================================================================\n\n/**\n * Referential actions exist only once a complete reference exists — they act on\n * a foreign key, and there is no foreign key to act on before\n * `.references(...)` completes the pair.\n */\ntype ForeignKeyActions<State> = {\n onDelete<const Action extends ReferentialAction>(\n action: Action\n ): ModelToOneRelation<\n State extends { readonly foreignKey: infer FK }\n ? Replace<\n State,\n { readonly foreignKey: Replace<FK, { onDelete: Action }> }\n >\n : State\n >;\n onUpdate<const Action extends ReferentialAction>(\n action: Action\n ): ModelToOneRelation<\n State extends { readonly foreignKey: infer FK }\n ? Replace<\n State,\n { readonly foreignKey: Replace<FK, { onUpdate: Action }> }\n >\n : State\n >;\n};\n\ntype ModelToOneCapabilities<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): ModelToOneRelation<Replace<State, { readonly name: Name }>>;\n fields<const Fields extends NonEmptyFieldTuple>(\n ...fields: Fields\n ): ReferencesStage<State, Fields>;\n};\n\n/**\n * A model-target singular slot. It exposes no `.optional()`: emptiness follows\n * from the nullability of a complete local foreign-key tuple, and a non-owning\n * singular view is derived nullable.\n */\nexport type ModelToOneRelation<State> = ModelToOneCapabilities<State> &\n (State extends { readonly foreignKey: ForeignKeyDeclaration }\n ? ForeignKeyActions<State>\n : unknown);\n\n/**\n * The transient value `.fields(...)` returns.\n *\n * It carries NO relation brand, so neither `ModelShape` nor any downstream\n * relation consumer can mistake an incomplete foreign key for trusted schema\n * state, and `s.model(...)` refuses it outright. It exposes only\n * `.references(...)` and `.name(...)`: a name must not be able to turn an\n * incomplete pair into schema truth.\n */\nexport type ReferencesStage<State, Fields extends NonEmptyFieldTuple> = {\n references<\n const References extends NonEmptyFieldTuple & {\n readonly length: Fields[\"length\"];\n },\n >(\n ...references: References\n ): ModelToOneRelation<\n Replace<\n State,\n {\n readonly foreignKey: Replace<\n State extends { readonly foreignKey: infer FK } ? FK : unknown,\n { readonly fields: Fields; readonly references: References }\n >;\n }\n >\n >;\n name<const Name extends string>(\n name: Name\n ): ReferencesStage<Replace<State, { readonly name: Name }>, Fields>;\n};\n\n// =============================================================================\n// PRIVATE TERMINALS\n// =============================================================================\n\nclass ModelToOne {\n readonly #state: ModelToOneState;\n readonly #internal: RelationInternal<ModelToOneState>;\n\n constructor(state: ModelToOneState) {\n this.#state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.#state,\n settleTarget: createTargetSettlement(() => this.#state.target.getter),\n });\n }\n\n name(name: string): ModelToOne {\n return new ModelToOne({\n ...this.#state,\n name: normalizeRelationName(\"s.toOne\", name),\n });\n }\n\n fields(...fields: string[]): PendingReferences {\n return new PendingReferences(\n this.#state,\n normalizeFieldTuple(\"s.toOne\", \"fields\", fields)\n );\n }\n\n onDelete(action: ReferentialAction): ModelToOne {\n return this.#withForeignKeyAction(\"onDelete\", action);\n }\n\n onUpdate(action: ReferentialAction): ModelToOne {\n return this.#withForeignKeyAction(\"onUpdate\", action);\n }\n\n /**\n * The type surface hides both action setters until `.references(...)` has\n * completed a foreign key. This refusal covers the route a type pin cannot:\n * a JavaScript caller placing a referential action on a slot that owns no\n * foreign key, where the action would otherwise have nowhere to be stored and\n * would be silently dropped.\n */\n #withForeignKeyAction(\n action: \"onDelete\" | \"onUpdate\",\n value: ReferentialAction\n ): ModelToOne {\n const foreignKey = this.#state.foreignKey;\n if (foreignKey === undefined) {\n refuseRelationInput(\n \"s.toOne\",\n action,\n `'${action}' is available only after \\`.fields(...).references(...)\\` declares a foreign key`\n );\n }\n return new ModelToOne({\n ...this.#state,\n foreignKey: Object.freeze({\n ...foreignKey,\n [action]: normalizeReferentialAction(action, value),\n }),\n });\n }\n\n get \"~\"(): RelationInternal<ModelToOneState> {\n return this.#internal;\n }\n}\n\n/**\n * The transient references stage. It has no `\"~\"` accessor by design: that\n * absence is what makes an incomplete chain unusable as a model member.\n */\nclass PendingReferences {\n readonly #state: ModelToOneState;\n readonly #localFields: NonEmptyFieldTuple;\n\n constructor(state: ModelToOneState, localFields: NonEmptyFieldTuple) {\n this.#state = state;\n this.#localFields = localFields;\n }\n\n name(name: string): PendingReferences {\n return new PendingReferences(\n { ...this.#state, name: normalizeRelationName(\"s.toOne\", name) },\n this.#localFields\n );\n }\n\n references(...references: string[]): ModelToOne {\n const referenced = normalizeFieldTuple(\"s.toOne\", \"references\", references);\n if (referenced.length !== this.#localFields.length)\n refuseReferenceArity(referenced.length, this.#localFields.length);\n // Completing a second stage replaces the pair atomically and preserves the\n // endpoint's name and referential actions; the prior terminal is untouched.\n const prior = this.#state.foreignKey;\n const foreignKey: ForeignKeyDeclaration = {\n fields: this.#localFields,\n references: referenced,\n ...(prior?.onDelete === undefined ? {} : { onDelete: prior.onDelete }),\n ...(prior?.onUpdate === undefined ? {} : { onUpdate: prior.onUpdate }),\n };\n return new ModelToOne({\n ...this.#state,\n foreignKey: Object.freeze(foreignKey),\n });\n }\n}\n\n/**\n * Is this model member a transient references stage?\n *\n * Deliberately nominal: a stage is only ever produced by `.fields(...)`, so an\n * `instanceof` test cannot be spoofed by a look-alike record, and the\n * `s.model(...)` boundary can refuse the one member shape that would otherwise\n * be silently dropped.\n */\nexport function isReferencesStage(value: unknown): boolean {\n return value instanceof PendingReferences;\n}\n\n// =============================================================================\n// FACTORY\n// =============================================================================\n\n/**\n * Declare a slot that holds AT MOST ONE membership.\n *\n * The map overload is declared first so a variant map is never swallowed by the\n * broad getter overload. Dispatch examines only the argument representation and\n * never invokes a getter.\n */\nexport function toOne<\n const Entries extends VariantGetterMap,\n const Options extends VariantOptions<Entries> | undefined = undefined,\n>(\n variants: Entries & VariantMapGuard<Entries>,\n options?: Options & ExactVariantOptions<Options, Entries>\n): VariantToOneRelation<{\n readonly kind: \"relation\";\n readonly cardinality: \"one\";\n readonly target: {\n readonly kind: \"variants\";\n readonly entries: NormalizedOneEntries<Entries>;\n };\n}>;\nexport function toOne<const G>(getter: G & GetterOnly<G>): G extends Getter\n ? ModelToOneRelation<{\n readonly kind: \"relation\";\n readonly cardinality: \"one\";\n readonly target: { readonly kind: \"model\"; readonly getter: G };\n }>\n : never;\nexport function toOne(target: unknown, options?: unknown): AnyRelation {\n if (typeof target === \"function\") {\n // biome-ignore lint/complexity/noArguments: distinguishes omission from explicit undefined without changing the factory's public arity\n if (arguments.length > 1) {\n refuseRelationInput(\n \"s.toOne\",\n \"options\",\n \"A model-target relation takes exactly one argument\"\n );\n }\n return new ModelToOne({\n kind: \"relation\",\n cardinality: \"one\",\n target: { kind: \"model\", getter: target },\n });\n }\n return variantToOneTerminal({\n kind: \"relation\",\n cardinality: \"one\",\n target: {\n kind: \"variants\",\n entries: normalizeVariantEntries(\"s.toOne\", target, options),\n },\n });\n}\n\nfunction refuseReferenceArity(referenced: number, local: number): never {\n return refuseRelationInput(\n \"s.toOne\",\n \"references\",\n `\\`.references(...)\\` declares ${referenced} field(s) against ${local} local field(s); a foreign key pairs them positionally`\n );\n}\n","import { emptyRecord } from \"@schema/record\";\nimport type { AnyRelation } from \"@schema/relation\";\nimport { refuseRelationInput } from \"@schema/relation/terminal\";\n// Deep import: the references-stage predicate is the `s.model(...)` boundary's\n// own instrument and is deliberately not part of the relation package surface.\nimport { isReferencesStage } from \"@schema/relation/to-one\";\nimport type { Scalar } from \"@schema/scalars/base\";\n\n/**\n * Record of model fields - the canonical type for scalar and relation definitions.\n * A model field is either a scalar or a relation; ONE relation map holds both\n * target domains.\n */\nexport type AnyModelField = Scalar | AnyRelation;\nexport type ModelShape = Record<string, AnyModelField>;\n\n/**\n * The shape `s.model(...)` and `.extends(...)` accept: a model shape with no\n * member named `_count` or `_distance`, the names a selection's own outputs\n * reserve (relation counts, a distance). This is the compile-time spelling of\n * rule F010 for TypeScript callers; F010 (`memberNamesAreNotReserved`) stays\n * the contract for every caller. It constrains keys only and never reads a\n * member's type, so it cannot change what a shape infers. Each key's type is\n * its reason spelled as a string literal, so the diagnostic a caller reads\n * names it: no model member is a string, so nothing a shape can hold\n * satisfies it.\n */\nexport type DeclaredModelShape = ModelShape & {\n readonly _count?: \"`_count` is reserved for relation counts (F010)\";\n readonly _distance?: \"`_distance` is reserved for distance results (F010)\";\n};\n\nexport type NameFromKeys<\n TFields extends string[],\n TName extends string = \"\",\n> = TFields extends readonly [\n infer F extends string,\n ...infer R extends string[],\n]\n ? R extends []\n ? `${TName}_${F}`\n : NameFromKeys<R, TName extends \"\" ? F : `${TName}_${F}`>\n : never;\n\nexport interface CompoundConstraint<\n TFields extends string[],\n TName extends string | undefined = undefined,\n> {\n fields: TFields;\n name: TName extends undefined ? NameFromKeys<TFields> : TName;\n}\n\n/** Any compound constraint (for loose typing) */\nexport type AnyCompoundConstraint = CompoundConstraint<string[]>;\n\nexport type ToString<T> = T extends\n | string\n | number\n | bigint\n | boolean\n | null\n | undefined\n ? `${T}`\n : never;\n\nexport type StringKeyOf<T extends Record<string, any>> = {\n [K in keyof T]: K extends string ? K : never;\n}[keyof T];\n\nexport type ScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar ? ToString<K> : never;\n}[keyof T];\n\n/** Fixed-decimal list keys, which have value semantics but no key semantics. */\nexport type DecimalListScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"] extends { type: \"decimal\"; array: true }\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\n/** GeoPoint keys have value semantics but no portable key/order semantics. */\nexport type PointScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"type\"] extends \"point\"\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type NonNullablePointScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"type\"] extends \"point\"\n ? T[K][\"~\"][\"state\"][\"nullable\"] extends true\n ? never\n : ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type NonPointScalarKeys<T extends ModelShape> = Exclude<\n ScalarKeys<T>,\n string extends keyof T ? never : PointScalarKeys<T>\n>;\n\n/** Scalar keys except fixed-decimal lists, which cannot be physical keys. */\nexport type NonDecimalListScalarKeys<T extends ModelShape> = Exclude<\n ScalarKeys<T>,\n string extends keyof T ? never : DecimalListScalarKeys<T>\n>;\n\n/** Scalar keys admitted in IDs, unique constraints, and foreign-key identity. */\nexport type PortableKeyScalarKeys<T extends ModelShape> = Exclude<\n NonDecimalListScalarKeys<T>,\n string extends keyof T ? never : PointScalarKeys<T>\n>;\n\n/** Extract relation keys from ModelState */\nexport type RelationKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends AnyRelation ? ToString<K> : never;\n}[keyof T];\n\nexport type RequiredScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"optional\"] extends true\n ? never\n : ToString<K>\n : never;\n}[keyof T];\n\nexport type UniqueScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"isId\"] extends true\n ? ToString<K>\n : T[K][\"~\"][\"state\"][\"isUnique\"] extends true\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\n/** Numeric scalar types for aggregations (avg, sum) */\nexport type NumericScalarType = \"int\" | \"number\" | \"decimal\" | \"bigint\";\n\n/** Extract keys of numeric scalars from a ModelShape */\nexport type NumericScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"array\"] extends true\n ? never\n : T[K][\"~\"][\"state\"][\"type\"] extends NumericScalarType\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type ScalarMap<T extends ModelShape> = {\n [K in ScalarKeys<T>]: T[K] extends Scalar ? T[K] : never;\n};\n\nexport type RelationMap<T extends ModelShape> = {\n [K in RelationKeys<T>]: T[K] extends AnyRelation ? T[K] : never;\n};\n\nexport type UniqueScalarMap<T extends ModelShape> = {\n [K in UniqueScalarKeys<T>]: T[K] extends Scalar ? T[K] : never;\n};\n\n/**\n * ONE relation boundary, keyed on the internal brand.\n *\n * Trusted relation state originates only in `s.toOne` / `s.toMany`, and both\n * target domains carry `kind: \"relation\"` — so a model has one relation map and\n * no consumer has to ask which family a member belongs to. Scalars keep\n * `state.type`, so the two brands cannot collide.\n */\nfunction isRelation(value: unknown): value is AnyRelation {\n if (\n (typeof value !== \"object\" || value === null) &&\n typeof value !== \"function\"\n ) {\n return false;\n }\n const internal = Reflect.get(value, \"~\");\n if (typeof internal !== \"object\" || internal === null) return false;\n const state = Reflect.get(internal, \"state\");\n return (\n typeof state === \"object\" &&\n state !== null &&\n Reflect.get(state, \"kind\") === \"relation\"\n );\n}\n\nconst SCALAR_TYPES = new Set<string>([\n \"string\",\n \"int\",\n \"number\",\n \"decimal\",\n \"boolean\",\n \"datetime\",\n \"date\",\n \"time\",\n \"bigint\",\n \"json\",\n \"blob\",\n \"vector\",\n \"point\",\n \"enum\",\n]);\n\nfunction isScalar(value: unknown): value is Scalar {\n if (\n (typeof value !== \"object\" || value === null) &&\n typeof value !== \"function\"\n ) {\n return false;\n }\n const internal = Reflect.get(value, \"~\");\n if (typeof internal !== \"object\" || internal === null) return false;\n const state = Reflect.get(internal, \"state\");\n if (typeof state !== \"object\" || state === null) return false;\n const type = Reflect.get(state, \"type\");\n return typeof type === \"string\" && SCALAR_TYPES.has(type);\n}\n\n/**\n * The classified member maps are a PROJECTION of the shape: every member an\n * extractor recognizes appears in the map that claims it, under the key the\n * shape gave it. A shape key comes from the caller — a hand-written literal, a\n * generated schema, a JSON document's field name — so it can be any string, and\n * assigning into an ordinary object would lose a `__proto__` member to\n * `Object.prototype`'s setter. These maps come from `emptyRecord` and stay\n * private until complete: their null prototype makes every assignment an own\n * data entry, including `__proto__`, without defining a descriptor per member.\n *\n * Whether such a key is a LEGAL identifier is a separate question with a\n * separate owner (`isValidSchemaIdentifier`, enforced at hydration and by the\n * document reader). Keeping the member is what lets that owner name it.\n */\nexport const extractScalarMap = <T extends ModelShape>(fields: T) => {\n const scalars = emptyRecord<Scalar>();\n for (const [key, value] of Object.entries(fields)) {\n if (isScalar(value)) {\n scalars[key] = value;\n }\n }\n return scalars as ScalarMap<T>;\n};\n\n/**\n * The `s.model(...)` member-classification boundary for relations.\n *\n * It gains exactly ONE refusal: a transient references stage — a chain that\n * started `.fields(...)` and never received `.references(...)` — is rejected\n * loudly rather than silently dropped, because that member declares a foreign\n * key the schema would then never have. Every other unrecognized member keeps\n * its existing silent-drop behavior; widening that is a separate decision.\n */\nexport const extractRelationMap = <T extends ModelShape>(fields: T) => {\n const relations = emptyRecord<AnyRelation>();\n for (const [key, value] of Object.entries(fields)) {\n if (isRelation(value)) {\n relations[key] = value;\n } else if (isReferencesStage(value)) {\n refuseRelationInput(\n \"s.model\",\n key,\n `Relation '${key}' started \\`.fields(...)\\` without \\`.references(...)\\`; complete the foreign key before using it as a model field`\n );\n }\n }\n return relations as RelationMap<T>;\n};\n\nexport const extractUniqueScalarMap = <T extends ModelShape>(fields: T) => {\n const uniques = emptyRecord<Scalar>();\n for (const [key, value] of Object.entries(fields)) {\n if (\n isScalar(value) &&\n (value[\"~\"].state.isUnique || value[\"~\"].state.isId)\n ) {\n uniques[key] = value;\n }\n }\n return uniques as UniqueScalarMap<T>;\n};\n\nexport const getNameFromKeys = <\n Name extends string | undefined,\n TFields extends any[],\n>(\n name: Name,\n fields: TFields\n) => {\n return (\n name ??\n (fields.join(\"_\") as Name extends undefined ? NameFromKeys<TFields> : Name)\n );\n};\n","// Model Class Implementation\n// Defines database models with scalars and relations\n\nimport type { ObjectSchema, VibSchema } from \"@validation\";\nimport v from \"@validation/primitives/v\";\nimport { emptyRecord, put } from \"../record\";\nimport type { AnyRelation } from \"../relation\";\nimport type { Scalar } from \"../scalars/base\";\nimport type { HydratedSchemaNames, SchemaNames } from \"../scalars/common\";\nimport {\n type DeclaredModelShape,\n extractRelationMap,\n extractScalarMap,\n extractUniqueScalarMap,\n getNameFromKeys,\n type ModelShape,\n type NameFromKeys,\n type NonNullablePointScalarKeys,\n type PortableKeyScalarKeys,\n type RelationMap,\n type ScalarMap,\n type StringKeyOf,\n type UniqueScalarMap,\n} from \"./helper\";\n// Re-export types from helpers for external use\n\n// =============================================================================\n// TYPE INFERENCE HELPER\n// =============================================================================\n\nexport interface ModelState {\n shape: ModelShape;\n compoundId:\n | Record<string, ObjectSchema<Record<string, VibSchema>>>\n | undefined;\n compoundUniques:\n | Record<string, ObjectSchema<Record<string, VibSchema>>>\n | undefined;\n tableName: string | undefined;\n indexes: IndexDefinition[];\n omit: Record<string, true> | undefined;\n scalars: Record<string, Scalar>;\n /** ONE canonical relation map, holding both target domains in shape order. */\n relations: Record<string, AnyRelation>;\n uniques: Record<string, Scalar>;\n}\n\n/** Initial model projections stay named when a consumer emits recursive graphs. */\nexport interface InitialModelState<Shape extends ModelShape>\n extends ModelState {\n shape: Shape;\n scalars: ScalarMap<Shape>;\n relations: RelationMap<Shape>;\n uniques: UniqueScalarMap<Shape>;\n omit: undefined;\n}\n\n/**\n * Internal accessor return type for Model[\"~\"]\n * Explicit type annotation to avoid TS7056 (type too complex to serialize)\n */\nexport interface ModelInternal<T extends ModelState> {\n state: T;\n names: SchemaNames;\n nameRegistry: {\n fields: Map<string, SchemaNames>;\n };\n getFieldName: (key: string) => HydratedSchemaNames;\n /** Cached scalar field names (computed once on first access) */\n scalarFieldNames: string[];\n /** Cached relation names (computed once on first access) */\n relationNames: string[];\n}\n\n/**\n * The index kinds a schema may declare. The union is the whole of what any\n * dialect accepts, not what all of them accept — `validateIndexType` in\n * `migrations/drivers/base.ts` refuses each one on the dialects whose\n * `supportsIndexTypes` does not list it, by name, at push time.\n *\n * `fulltext` and `spatial` are here because MySQL's whole round trip already\n * exists and only this union could not spell it: the emitter writes the\n * `FULLTEXT`/`SPATIAL` prefix and refuses to combine either with `UNIQUE`\n * (`mysql/index.ts`), the introspection reads them back and normalizes MySQL's\n * `RTREE` to `spatial` (`mysql/introspect.ts`), the migration snapshot's\n * `IndexDef` already carries both (`migrations/types.ts`), and the capability\n * list already declares them. See Phase 10 item 6 in\n * `docs/architecture/query-performance-plan.md`.\n */\nexport type IndexType =\n | \"btree\"\n | \"hash\"\n | \"gin\"\n | \"gist\"\n | \"fulltext\"\n | \"spatial\";\n\nexport interface IndexOptions {\n name?: string;\n unique?: boolean;\n type?: IndexType;\n where?: string; // For partial indexes (PostgreSQL)\n}\n\ntype OrdinaryIndexOptions = Omit<IndexOptions, \"type\"> & {\n type?: Exclude<IndexType, \"spatial\">;\n};\n\ntype GeoPointSpatialIndexOptions = {\n name?: string;\n type: \"spatial\";\n unique?: never;\n where?: never;\n};\n\nexport interface IndexDefinition<\n Keys extends string[] = string[],\n O extends IndexOptions = IndexOptions,\n> {\n fields: Keys;\n options: O;\n}\n\n/** A partial index cannot constrain rows excluded by its predicate. */\nexport function isTotalIndex(options: Pick<IndexOptions, \"where\">): boolean {\n return !options.where;\n}\n\nexport type UpdateIndexDefinition<\n State extends ModelState,\n Index extends IndexDefinition,\n> = [...State[\"indexes\"], Index];\n\n/** The name a compound `.id()` / `.unique()` constraint may be given. */\nexport interface CompoundKeyOptions {\n name?: string;\n}\n\n/**\n * An options bag that carries the surface's own keys and NOTHING else.\n *\n * A generic `O extends Options` is no guard on its own: when inference produces\n * a bag the constraint would reject, TypeScript CLAMPS `O` to the constraint and\n * only excess-property checking is left to catch the stray key — and that needs\n * a fresh object literal, so `.index([\"a\"], sharedIndexOptions)` sails through\n * with `uniqu: true` recorded as nothing at all. Demanding `never` for the\n * unknown keys refuses structurally instead, whatever the argument's freshness.\n * Same instrument as `UnknownOmitKeys` below.\n */\ntype ExactOptions<Given, Allowed> = Given &\n Record<Exclude<keyof Given, keyof Allowed>, never>;\n\n/**\n * The constraint name: the caller's `name` when they gave one, otherwise the\n * underscore-joined field names. Read off the options bag rather than a separate\n * inferred parameter so that ONE type parameter carries the whole literal — the\n * parameter `ExactOptions` needs in order to see the unknown keys.\n */\ntype CompoundKeyName<\n Keys extends string[],\n O extends CompoundKeyOptions,\n> = O extends { name: infer N extends string } ? N : NameFromKeys<Keys>;\n\nexport const mergeIndexDefinitions = <\n State extends ModelState,\n Index extends IndexDefinition,\n>(\n state: State,\n index: Index\n): UpdateIndexDefinition<State, Index> => {\n return [...state.indexes, index] as UpdateIndexDefinition<State, Index>;\n};\n\n// Publish the same completed state as fluent returns so a legacy explicit\n// Model<UpdateState<...>> annotation retains exact relation-link identity.\nexport type UpdateState<\n State extends ModelState,\n Update extends Partial<ModelState>,\n> = {\n [P in keyof (Omit<State, keyof Update> & Update)]: (Omit<\n State,\n keyof Update\n > &\n Update)[P];\n};\n\n/**\n * The keys a proposed `.omit()` names that this model does NOT have as a\n * scalar: the typos and the relation names.\n *\n * `Hidden` is inferred from the argument's own keys and is deliberately NOT\n * constrained to the scalar names. A constrained type parameter is no guard\n * here: when inference produces something the constraint rejects, TypeScript\n * silently CLAMPS the parameter to the constraint and only excess-property\n * checking — which needs a fresh object literal — is left to catch the bad\n * key. Anything non-fresh (`as const`, a spread, an annotated variable, a\n * widened `Record<string, true>`) then sails through and records a\n * hidden-column claim nobody wrote. Excluding the unknown keys and demanding\n * `never` for them refuses structurally instead, whatever the argument's\n * freshness, and a `never` the caller cannot produce is a compile error at the\n * offending key.\n *\n * Relations are absent from the accepted set because `State[\"scalars\"]` is the\n * scalar half of the shape (`ScalarMap`), the same source `.index()` /\n * `.id()` / `.unique()` key off. Reading it never touches a relation's\n * `getter`, the member that must not be resolved while two model consts still\n * refer to each other (see `RelationState.getter`).\n */\ntype UnknownOmitKeys<Hidden extends string, State extends ModelState> = Exclude<\n Hidden,\n StringKeyOf<State[\"scalars\"]>\n>;\n\n/**\n * This model's scalar names, each optionally flagged `true`.\n *\n * It carries NO refusal — `UnknownOmitKeys` does that — and it adds no\n * requirement, every key being optional. It is in the parameter for one\n * reason: an editor offers the keys of a CONCRETE contextual type, and\n * `Record<Hidden, true>` is not concrete until `Hidden` has been inferred from\n * the very literal being typed. Without this member `.omit({ ` autocompletes\n * the global scope; with it, the model's scalars.\n */\nexport type ModelOmitInput<State extends ModelState> = Partial<\n Record<StringKeyOf<State[\"scalars\"]>, true>\n>;\n\n/**\n * Merge a new compound constraint into the existing record so repeated\n * .id()/.unique() calls accumulate instead of replacing each other.\n * Resolves to just `Added` when nothing was set yet.\n */\ntype MergeCompound<Existing, Added> = Added &\n (Existing extends Record<string, ObjectSchema<Record<string, VibSchema>>>\n ? Existing\n : unknown);\n\n/**\n * Resolve compound-key members to their base schemas, refusing any name that\n * is not a scalar of the model AT THE DECLARING SITE. The typed surface\n * already refuses these names; this throw is the runtime backstop for\n * untyped callers and JSON documents (the document interpreter relocates it\n * onto the `ids[]`/`uniques[]` node that wrote it), and it must fire on the\n * rule-free paths (`serializeModels`, `generate`,\n * `push({ skipValidation: true })`) that never run the advisory rules. I003\n * keeps its own coverage: post-construction shape drift (`.extends()`\n * shadowing a key member) is invisible to this constructor.\n *\n * A module function rather than a `Model` method: adding members to the class\n * perturbs how TS compares mutually-recursive model instantiations.\n */\nfunction compoundMembers(\n state: ModelState,\n fields: readonly string[],\n label: string\n): Record<string, VibSchema> {\n refuseDuplicateModelKeyMembers(fields, label);\n const members = emptyRecord<VibSchema>();\n for (const fieldName of fields) {\n // `in` is exact here: both maps come from the extractors, which build\n // prototype-free records, so no key can resolve an inherited member.\n const scalar =\n fieldName in state.scalars ? state.scalars[fieldName] : undefined;\n if (!scalar) {\n throw new Error(\n fieldName in state.relations\n ? `${label} field '${fieldName}' is a relation and cannot be a key member`\n : `${label} field '${fieldName}' does not exist`\n );\n }\n put(members, fieldName, scalar[\"~\"].state.base);\n }\n return members;\n}\n\n/**\n * One compound ID or unique, written into its own slot. The first tuple of a\n * name is preserved before Record storage could overwrite it.\n */\nfunction withCompound(\n state: ModelState,\n slot: \"compoundId\" | \"compoundUniques\",\n label: \"Compound ID\" | \"Compound unique\",\n fields: readonly string[],\n options: CompoundKeyOptions | undefined\n): Model<any> {\n const storedFields = snapshotModelKeyMembers(fields, label);\n const name = getNameFromKeys(options?.name, storedFields);\n if (Object.hasOwn(state[slot] ?? {}, name)) {\n throw new Error(\n `${label} name '${name}' is already used by another compound key; give this tuple a distinct name`\n );\n }\n const fieldsRecord = compoundMembers(state, storedFields, label);\n return new Model({\n ...state,\n [slot]: {\n ...state[slot],\n [name]: v.object(fieldsRecord, { partial: false }),\n },\n });\n}\n\n/** Snapshot one declaration tuple without consulting caller iteration hooks. */\nfunction snapshotModelKeyMembers(fields: unknown, label: string): string[] {\n if (!Array.isArray(fields)) {\n throw new Error(`${label} fields must be a dense array of strings`);\n }\n const memberCount = fields.length;\n const members = new Array<string>(memberCount);\n for (let position = 0; position < memberCount; position++) {\n if (!Object.hasOwn(fields, position)) {\n throw new Error(`${label} fields must be a dense array of strings`);\n }\n const member: unknown = fields[position];\n if (typeof member !== \"string\") {\n throw new Error(`${label} fields must be a dense array of strings`);\n }\n members[position] = member;\n }\n return members;\n}\n\n/** Snapshot the four public index options, including inherited accessors. */\nfunction snapshotIndexOptions(options: IndexOptions): IndexOptions {\n const name = options.name;\n const unique = options.unique;\n const type = options.type;\n const where = options.where;\n return {\n ...(name === undefined ? {} : { name }),\n ...(unique === undefined ? {} : { unique }),\n ...(type === undefined ? {} : { type }),\n ...(where === undefined ? {} : { where }),\n };\n}\n\n/** One physical key/index tuple cannot name the same column twice. */\nfunction refuseDuplicateModelKeyMembers(\n fields: readonly string[],\n label: string\n): void {\n if (new Set(fields).size !== fields.length) {\n throw new Error(`${label} cannot repeat a field in one tuple`);\n }\n}\n\n/**\n * Name registry for scalars and relations.\n * Maps scalar/relation keys to their resolved names (ts and sql).\n * This is populated during hydration.\n */\nexport interface NameRegistry {\n /** Scalar names: key -> {ts, sql} */\n fields: Map<string, SchemaNames>;\n}\n\nexport class Model<State extends ModelState> {\n // biome-ignore lint/style/useReadonlyClassProperties: <it is reassigned when hydrating schemas>\n #names: SchemaNames = {};\n // biome-ignore lint/style/useReadonlyClassProperties: <it is reassigned when hydrating schemas>\n #nameRegistry: NameRegistry = {\n fields: new Map(),\n };\n readonly #state: State;\n\n // Cached field metadata (lazily computed on first access)\n #scalarFieldNames: string[] | undefined;\n #relationNames: string[] | undefined;\n #internal: ModelInternal<State> | undefined;\n\n constructor(state: State) {\n this.#state = state;\n }\n\n // Materialize each completed modifier state inline before a recursive getter\n // captures it. A helper alias retains the whole prior modifier chain.\n /**\n * Maps the model to a specific database table name\n */\n map<Name extends string>(tableName: Name) {\n return new Model({ ...this.#state, tableName }) as unknown as Model<{\n [KState in keyof UpdateState<State, { tableName: Name }>]: UpdateState<\n State,\n { tableName: Name }\n >[KState];\n }>;\n }\n\n /**\n * Hide scalars from every result of this model — the schema-level exclusion.\n *\n * Keyed to the model's own SCALARS, so a typo or a relation name is a\n * compile error instead of an `omit` that quietly hides nothing. That\n * matters more here than anywhere else the builder takes field names: this\n * is the spelling used for secrets, and a silently-ignored key is a leaked\n * column. The refusal is per KEY, not per call: `{ secret: true, tokne:\n * true }` fails on `tokne` even though `secret` is real — two secrets with\n * one misspelled is the realistic case, and it is exactly the case an\n * excess-property-only refusal would wave through (see `UnknownOmitKeys`).\n *\n * Every value must be `true`. `false` has no meaning here (model-level omit\n * only ever hides) and a flag that may be `undefined` hides nothing at\n * runtime — `projectableScalarNames` compares against `true` — so\n * `Record<Hidden, true>` refuses both rather than recording a claim the\n * runtime would not honor.\n *\n * The literal survives the round trip — `.omit({ secret: true })` carries\n * exactly `{ secret: true }` into the state, not a widened record — which is\n * what every downstream `keyof State[\"omit\"]` reads. `Hidden` defaults to\n * `never` for the one call with nothing to infer from, `.omit({})`: a bare\n * `extends string` would fall back to `string` there and hand the state a\n * record keyed by every conceivable name.\n */\n omit<Hidden extends string = never>(\n items: Record<Hidden, true> &\n Record<UnknownOmitKeys<Hidden, State>, never> &\n ModelOmitInput<State>\n ) {\n return new Model({\n ...this.#state,\n omit: items,\n }) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n { omit: Record<Hidden, true> }\n >]: UpdateState<State, { omit: Record<Hidden, true> }>[KState];\n }>;\n }\n\n index<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n O extends OrdinaryIndexOptions = OrdinaryIndexOptions,\n >(\n fields: Keys,\n options?: ExactOptions<O, OrdinaryIndexOptions>\n ): Model<{\n [KState in keyof UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: Keys; options: O }> }\n >]: UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: Keys; options: O }> }\n >[KState];\n }>;\n index<\n const Key extends NonNullablePointScalarKeys<State[\"scalars\"]>,\n const O extends GeoPointSpatialIndexOptions,\n >(\n fields: [Key],\n options: ExactOptions<O, GeoPointSpatialIndexOptions>\n ): Model<{\n [KState in keyof UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: [Key]; options: O }> }\n >]: UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: [Key]; options: O }> }\n >[KState];\n }>;\n index(fields: string[], options: IndexOptions = {}): Model<any> {\n const storedFields = snapshotModelKeyMembers(fields, \"Index\");\n refuseDuplicateModelKeyMembers(storedFields, \"Index\");\n const storedOptions = snapshotIndexOptions(options);\n return new Model({\n ...this.#state,\n indexes: mergeIndexDefinitions(this.#state, {\n fields: storedFields,\n options: storedOptions,\n }),\n });\n }\n\n id<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n const O extends CompoundKeyOptions = Record<never, never>,\n >(fields: Keys, options?: ExactOptions<O, CompoundKeyOptions>) {\n return withCompound(\n this.#state,\n \"compoundId\",\n \"Compound ID\",\n fields,\n options\n ) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n {\n compoundId: MergeCompound<\n State[\"compoundId\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >]: UpdateState<\n State,\n {\n compoundId: MergeCompound<\n State[\"compoundId\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >[KState];\n }>;\n }\n\n unique<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n const O extends CompoundKeyOptions = Record<never, never>,\n >(fields: Keys, options?: ExactOptions<O, CompoundKeyOptions>) {\n return withCompound(\n this.#state,\n \"compoundUniques\",\n \"Compound unique\",\n fields,\n options\n ) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n {\n compoundUniques: MergeCompound<\n State[\"compoundUniques\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >]: UpdateState<\n State,\n {\n compoundUniques: MergeCompound<\n State[\"compoundUniques\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >[KState];\n }>;\n }\n\n extends<ETShape extends DeclaredModelShape>(shape: ETShape) {\n const newShape = { ...this.#state.shape, ...shape } as State[\"shape\"] &\n ETShape;\n return new Model({\n ...this.#state,\n shape: newShape,\n scalars: extractScalarMap(newShape),\n relations: extractRelationMap(newShape),\n uniques: extractUniqueScalarMap(newShape),\n }) as unknown as Model<\n UpdateState<\n State,\n {\n shape: State[\"shape\"] & ETShape;\n scalars: ScalarMap<State[\"shape\"] & ETShape>;\n relations: RelationMap<State[\"shape\"] & ETShape>;\n uniques: UniqueScalarMap<State[\"shape\"] & ETShape>;\n }\n >\n >;\n }\n\n get \"~\"(): ModelInternal<State> {\n if (this.#internal) {\n return this.#internal;\n }\n // Capture model instance for use in getters\n const model = this;\n\n this.#internal = {\n state: this.#state,\n // getters so hydration after first access is still observed\n get names() {\n return model.#names;\n },\n get nameRegistry() {\n return model.#nameRegistry;\n },\n /**\n * Get the resolved names for a field.\n * Throws if the schema has not been hydrated.\n */\n getFieldName: (key: string): HydratedSchemaNames => {\n const registered = model.#nameRegistry.fields.get(key);\n if (registered) {\n return registered as HydratedSchemaNames;\n }\n throw new Error(`Scalar \"${key}\" not found in nameRegistry`);\n },\n /** Cached scalar field names (computed once on first access) */\n get scalarFieldNames(): string[] {\n return (model.#scalarFieldNames ??= Object.keys(model.#state.scalars));\n },\n /** Cached relation names (computed once on first access) */\n get relationNames(): string[] {\n return (model.#relationNames ??= Object.keys(model.#state.relations));\n },\n };\n return this.#internal;\n }\n}\n\nexport const model = <TShape extends DeclaredModelShape>(\n shape: TShape\n): Model<InitialModelState<TShape>> =>\n new Model({\n compoundId: undefined,\n compoundUniques: undefined,\n tableName: undefined,\n indexes: [],\n omit: undefined,\n shape,\n scalars: extractScalarMap(shape),\n relations: extractRelationMap(shape),\n uniques: extractUniqueScalarMap(shape),\n });\n\nexport type AnyModel = Model<any>;\n\n/**\n * SQL table name for a model: hydrated name, then .map() tableName, then\n * the given fallback.\n */\nexport function getTableName(model: AnyModel, fallback = \"unknown\"): string {\n return model[\"~\"].names.sql ?? model[\"~\"].state.tableName ?? fallback;\n}\n\n/**\n * SQL column name for a field, resolved through the model's nameRegistry\n * (supports field reuse across models) with .map() and field-name fallbacks.\n */\nexport function getColumnName(model: AnyModel, fieldName: string): string {\n return model[\"~\"].getFieldName(fieldName).sql;\n}\n","// Common Scalar Utilities\n// Shared types and helpers for all scalar classes\n\nimport { ValidationError } from \"@errors\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { InferInput, VibSchema } from \"@validation\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport type { Scalar } from \"./base\";\n\n// =============================================================================\n// SCHEMA NAMES (hydrated by client at initialization)\n// =============================================================================\n\n/**\n * Name slots for models, scalars, and relations.\n * These are hydrated by the client at initialization time when the full\n * schema context is available.\n *\n * - ts: TypeScript/schema key name (e.g., \"email\", \"User\")\n * - sql: Resolved database name (e.g., \"email_column\", \"users\")\n */\nexport interface SchemaNames {\n /** TypeScript key name in the schema */\n ts?: string;\n /** Resolved SQL name (column/table) */\n sql?: string;\n}\n\n/**\n * Hydrated schema names - guaranteed to have both ts and sql defined.\n * Returned by model[\"~\"].getFieldName() for scalar keys.\n */\nexport interface HydratedSchemaNames {\n /** TypeScript key name in the schema */\n ts: string;\n /** Resolved SQL name (column/table) */\n sql: string;\n}\n\n// =============================================================================\n// SCALAR TYPES\n// =============================================================================\n\nexport type ScalarType =\n | \"string\"\n | \"int\"\n | \"number\"\n | \"decimal\"\n | \"boolean\"\n | \"datetime\"\n | \"date\"\n | \"time\"\n | \"bigint\"\n | \"json\"\n | \"blob\"\n | \"vector\"\n | \"point\"\n | \"enum\";\n\nexport type AutoGenerateType =\n | \"uuid\"\n | \"uuidv7\"\n | \"ulid\"\n | \"ksuid\"\n | \"nanoid\"\n | \"cuid\"\n | \"increment\"\n | \"now\"\n | \"updatedAt\";\n\n/**\n * A generator declaration.\n *\n * `kind` is the only statement of which generator runs. `prefix` and `length`\n * are declaration facts the string generators otherwise bake into their default\n * closure, where nothing can read them back; state is their durable home so a\n * serializer can restate the declaration that produced the closure.\n * `increment`/`now`/`updatedAt` take neither.\n */\nexport interface AutoGenerate {\n kind: AutoGenerateType;\n prefix?: string | undefined;\n length?: number | undefined;\n /**\n * The caller did not NAME this format; `.id()` installed it.\n *\n * The distinction is what separates a key from a domain. `.ulid()` is an\n * assertion about every value the field will ever hold — which is what lets\n * VibORM admit those values, normalize their aliases and store them as\n * sixteen bytes. `.id()` is an assertion about the KEY, carrying a generator\n * so a caller need not supply one; the values it accepts are still whatever\n * a string column accepts, and it stores them as text. `.ulid().id()` says\n * both, and is a ULID key.\n *\n * It lives on the declaration record, beside `kind`, because it IS a fact\n * about how this generator came to be declared — not a second scalar state.\n */\n implicit?: boolean | undefined;\n /** Explicit generation choice; absent formats acquire a default only as IDs. */\n generate?: boolean | undefined;\n}\n\n/**\n * The closures the generator modifiers installed.\n *\n * A generator writes TWO facts: `autoGenerate`, which is the declaration, and\n * `default`, which is the closure that produces the value. A later\n * `.default(fn)` replaces only the second, so `autoGenerate !== undefined` is\n * not evidence that the closure standing in `default` is the generator's — and\n * a consumer that restates a declaration from state (the JSON serializer) would\n * otherwise silently substitute a random generator for a caller's own function.\n *\n * Identity is the only thing that distinguishes them, so identity is what is\n * recorded. One owner, beside the declaration it belongs to; nothing outside\n * the eight modifier writers may add to it.\n */\nconst GENERATOR_DEFAULTS = new WeakSet<object>();\n\n/** Mark a closure as the default a generator modifier installed. */\ndeclare const GENERATED_DEFAULT: unique symbol;\nexport interface GeneratorDefaultBrand {\n readonly [GENERATED_DEFAULT]: true;\n}\nexport function generatorDefault<F extends () => unknown>(\n closure: F\n): F & GeneratorDefaultBrand;\nexport function generatorDefault<F extends () => unknown>(closure: F) {\n GENERATOR_DEFAULTS.add(closure);\n return closure;\n}\n\n/** A scalar generator cannot produce a complete list default. */\nexport function refuseListGenerator(builder: string): never {\n throw new ValidationError(\n { kind: \"schema-builder\", builder, path: \"array\" },\n [\n {\n path: \"array\",\n message:\n \"Scalar generation is not supported on lists; declare an explicit array default\",\n },\n ]\n );\n}\n\n/** Nullable admission supplies null only when no default was already declared. */\nexport function nullableDefault<State extends ScalarState>(\n state: State\n): State[\"hasDefault\"] extends true ? State[\"default\"] : null;\nexport function nullableDefault(state: ScalarState) {\n return state.hasDefault ? state.default : null;\n}\n\n/** Whether this default value IS a generator's own installed closure. */\nexport function isGeneratorDefault(value: unknown): boolean {\n return typeof value === \"function\" && GENERATOR_DEFAULTS.has(value);\n}\n\n// =============================================================================\n// SCALAR STATE\n// =============================================================================\n\n/**\n * Complete state for a scalar instance.\n * This is the single generic that flows through the scalar class.\n */\n\nexport interface ScalarState<T extends ScalarType = ScalarType> {\n type: T;\n nullable: boolean;\n array: boolean;\n hasDefault: boolean;\n isId: boolean;\n isUnique: boolean;\n default: DefaultValue<any> | undefined;\n autoGenerate: AutoGenerate | undefined;\n /** Runtime create validation for portable auto-increment semantics. */\n disallowZero?: boolean;\n schema: StandardSchemaV1<any, any> | undefined;\n optional: boolean;\n /** Custom column name in the database (set via .map()) */\n columnName: string | undefined;\n base: VibSchema;\n withTimezone?: boolean | undefined;\n /**\n * The declared fixed-decimal domain, frozen at `s.decimal({...})`.\n *\n * It is the ONE source of truth for input validation, physical DDL, literal\n * encoding, result decoding, comparison and aggregate lowering, arithmetic\n * rounding and overflow, list-member encoding, and migration compatibility.\n * No adapter, driver, result parser, or migration component stores a second\n * precision or scale decision, and every modifier carries THIS object by\n * reference rather than rebuilding one.\n */\n decimal?: DecimalDescriptor | undefined;\n /** Fixed vector length for pgvector-backed vector scalars. */\n dimension?: number | undefined;\n /** Custom enum type name in the database (set via .name() on enum scalars) */\n enumName?: string | undefined;\n}\n\n// =============================================================================\n// STATE UPDATE HELPER\n// =============================================================================\n\n/**\n * Computes the new state type after applying an update.\n * Used by chainable methods to derive the return type.\n *\n * @example\n * nullable(): StringScalar<UpdateState<State, { nullable: true }>>\n */\nexport type UpdateState<\n State extends ScalarState,\n Update extends Partial<ScalarState>,\n> = Omit<State, keyof Update> & Update;\n\nexport const updateState = <\n F extends Scalar,\n const Update extends Partial<ScalarState>,\n>(\n scalar: F,\n update: Update\n) => {\n return { ...scalar[\"~\"].state, ...update } as UpdateState<\n F[\"~\"][\"state\"],\n Update\n >;\n};\n\n// =============================================================================\n// TYPE HELPERS\n// =============================================================================\n\n/**\n * Conditionally wraps a type with null\n */\nexport type MaybeNullable<\n T,\n Nullable extends boolean = false,\n> = Nullable extends true ? T | null : T;\n\n/**\n * Conditionally wraps a type as array\n */\nexport type MaybeArray<\n T,\n IsArray extends boolean = false,\n> = IsArray extends true ? T[] : T;\n\n/**\n * Type for default value - can be direct value or factory function\n */\nexport type DefaultValue<T> = T | (() => T);\n\n/**\n * The input accepted by the scalar's current base schema, or a factory for it.\n *\n * The base schema already owns the scalar's nullable and array wrappers. Adding\n * them again here turns a list default into a list of lists at the type level\n * (`string[][]` for `s.string().array()`), while runtime validation correctly\n * expects `string[]`. Read the one trusted shape instead of reconstructing it.\n */\nexport type DefaultValueInput<S extends ScalarState> = DefaultValue<\n InferInput<S[\"base\"]>\n>;\n\n// =============================================================================\n// DEFAULT STATE FACTORY\n// =============================================================================\n\n/** The factory's existing initial state stays named in exported model graphs. */\nexport interface InitialScalarState<T extends ScalarType, B extends VibSchema> {\n type: T;\n nullable: boolean;\n array: boolean;\n hasDefault: boolean;\n isId: boolean;\n isUnique: boolean;\n default: undefined;\n autoGenerate: undefined;\n disallowZero: boolean;\n schema: undefined;\n columnName: undefined;\n optional: boolean;\n withTimezone: boolean;\n base: B;\n}\n\n/**\n * Creates a default initial state for a scalar type\n */\nexport const createDefaultState = <T extends ScalarType, B extends VibSchema>(\n type: T,\n base: B\n): InitialScalarState<T, B> => ({\n type,\n nullable: false,\n array: false,\n hasDefault: false,\n isId: false,\n isUnique: false,\n default: undefined,\n autoGenerate: undefined,\n disallowZero: false,\n schema: undefined,\n columnName: undefined,\n optional: false,\n withTimezone: false,\n base,\n});\n\n// =============================================================================\n// INFER HELPERS (for type-level inference from state)\n// =============================================================================\n\n/**\n * Infers the base TypeScript type from a scalar state\n */\nexport type InferBaseType<\n BaseType,\n State extends ScalarState,\n> = State[\"array\"] extends true\n ? State[\"nullable\"] extends true\n ? (BaseType | null)[]\n : BaseType[]\n : State[\"nullable\"] extends true\n ? BaseType | null\n : BaseType;\n\n/**\n * Infers the create input type from a scalar state\n */\nexport type InferCreateType<\n BaseType,\n State extends ScalarState,\n> = State[\"hasDefault\"] extends true\n ? State[\"nullable\"] extends true\n ? BaseType | null | undefined\n : BaseType | undefined\n : State[\"nullable\"] extends true\n ? BaseType | null\n : BaseType;\n\n// =============================================================================\n// SCHEMA SHORTHANDS (re-exported from validation primitives)\n// =============================================================================\n\nexport {\n shorthandArray,\n shorthandFilter,\n shorthandUpdate,\n} from \"@validation/primitives/shorthand\";\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 { ValidationError } from \"@errors\";\nimport { isRecord } from \"@validation/value-guards\";\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\n/**\n * A native type at the matching boundary: a base identifier, optionally followed\n * by one parenthesized group of comma-separated integers. This gate REJECTS\n * everything a clause needs — a quote, a space, a semicolon, a comment, a second\n * group, a non-integer argument — so what survives is only shaped like a type,\n * and the catalog then decides whether it IS one.\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\n// Built on the first native-type check rather than at import: walking every\n// dialect's constants runs dozens of probe calls, and a schema that declares\n// no native type never asks.\nlet catalogs: Record<Dialect, DialectCatalog> | undefined;\n\n/**\n * Whether `type` is a native type the declared dialect's catalog admits. The\n * gate's single statement, used by the reader and the serializer alike.\n */\nexport function isNativeTypeInCatalog(db: Dialect, type: string): boolean {\n catalogs ??= buildCatalogs();\n const catalog = catalogs[db];\n if (catalog.exact.has(type)) {\n return true;\n }\n if (!TYPE_EXPRESSION.test(type)) {\n return false;\n }\n const open = type.indexOf(\"(\");\n if (open === -1) {\n return catalog.templates.get(type)?.has(0) === true;\n }\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\n/**\n * The refusal both directions carry, naming the dialect whose catalog was\n * consulted and pointing at the documented list.\n */\nexport function nativeTypeRefusal(db: Dialect): string {\n return `A \\`native.type\\` is written into DDL verbatim, so a document may carry only a native type from the '${db}' dialect's closed catalog — the values the ${CONSTANT_NAMES[db]} native-type constants produce. See the native types documentation (docs/schema/native-types).`;\n}\n\n// =============================================================================\n// SCALAR FACTORY ADMISSION\n// =============================================================================\n\n/** The one construction-time refusal of a native-type argument. */\nfunction refuse(builder: string, path: string, message: string): never {\n throw new ValidationError({ kind: \"schema-builder\", builder, path }, [\n { path, message },\n ]);\n}\n\n/**\n * A scalar factory's native-type argument, admitted: the declaration the scalar\n * stores and every modifier carries.\n *\n * The tagged shorthand is returned AS GIVEN — its open historical contract,\n * custom spellings and unrelated extra keys included, is unchanged — once it\n * names one of the three dialects as `db` and a string `type` (a value that does\n * not would be silently ignored by every dialect, or reach DDL as `undefined`),\n * and unless it also carries a dialect key, which makes it two declarations at\n * once. A map is the new form and is\n * held to its whole contract here, where types can be bypassed: only the three\n * dialect keys, at least one of them, each an OWN entry of its own dialect whose\n * type the catalog admits. It is then SNAPSHOT into a frozen map of frozen\n * `{ db, type }` entries, so the caller's object — or an entry it shares with\n * another declaration — can change afterwards without changing this scalar.\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 refuse(\n builder,\n \"nativeType\",\n \"A native type is a `{ db, type }` constant or a map of them by dialect (`{ pg, mysql, sqlite }`)\"\n );\n }\n if (isTaggedNativeType(declaration)) {\n const { db, type } = declaration;\n if (!NATIVE_DIALECTS.includes(db) || typeof type !== \"string\") {\n refuse(\n builder,\n \"nativeType\",\n `A tagged native type is \\`{ db, type }\\`: \\`db\\` one of ${NATIVE_DIALECTS.join(\", \")} and \\`type\\` a string`\n );\n }\n const beside = NATIVE_DIALECTS.find((dialect) =>\n Object.hasOwn(declaration, dialect)\n );\n if (beside !== undefined) {\n refuse(\n builder,\n `nativeType.${beside}`,\n `A tagged native type ('db: ${db}') cannot also carry a '${beside}' entry: declare one tagged type, or a map by dialect (\\`{ pg, mysql, sqlite }\\`)`\n );\n }\n return declaration;\n }\n return admitNativeTypeMap(builder, declaration);\n}\n\nfunction admitNativeTypeMap(\n builder: string,\n map: NativeTypeMap\n): NativeTypeMap {\n for (const key of Object.keys(map)) {\n if (!NATIVE_DIALECTS.some((dialect) => dialect === key)) {\n refuse(\n builder,\n `nativeType.${key}`,\n `'${key}' is not a dialect: a native-type map names only ${NATIVE_DIALECTS.join(\", \")}`\n );\n }\n }\n const snapshot: {\n pg?: DialectNativeType<\"pg\">;\n mysql?: DialectNativeType<\"mysql\">;\n sqlite?: DialectNativeType<\"sqlite\">;\n } = {};\n if (Object.hasOwn(map, \"pg\")) snapshot.pg = admitEntry(builder, \"pg\", map.pg);\n if (Object.hasOwn(map, \"mysql\")) {\n snapshot.mysql = admitEntry(builder, \"mysql\", map.mysql);\n }\n if (Object.hasOwn(map, \"sqlite\")) {\n snapshot.sqlite = admitEntry(builder, \"sqlite\", map.sqlite);\n }\n if (Object.keys(snapshot).length === 0) {\n refuse(\n builder,\n \"nativeType\",\n \"A native-type map names at least one dialect; omit the argument to keep every automatic column\"\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 db = isRecord(entry) ? entry.db : undefined;\n const type = isRecord(entry) ? entry.type : undefined;\n if (db !== dialect || typeof type !== \"string\") {\n refuse(\n builder,\n `nativeType.${dialect}`,\n `The '${dialect}' entry must be a ${CONSTANT_NAMES[dialect]} native type (\\`{ db: \"${dialect}\", type }\\`)`\n );\n }\n return Object.freeze({ db: dialect, type });\n}\n\n// =============================================================================\n// CATALOG CONSTRUCTION\n// =============================================================================\n\nfunction buildCatalogs(): Record<Dialect, DialectCatalog> {\n const catalogs: Record<Dialect, DialectCatalog> = {\n pg: emptyCatalog(),\n mysql: emptyCatalog(),\n sqlite: emptyCatalog(),\n };\n walk(PG, catalogs.pg);\n walk(MYSQL, catalogs.mysql);\n walk(SQLITE, catalogs.sqlite);\n return catalogs;\n}\n\nfunction emptyCatalog(): DialectCatalog {\n return { exact: new Set(), templates: new Map() };\n}\n\n// The trees are trusted, shipped constants — objects, categories and function\n// leaves, never a primitive or null — so this walk reads their shape directly.\n// The node type is `any` because a walk over a heterogeneous tree erases the\n// leaf types, and narrowing back to them would need the casts the house forbids.\nfunction walk(node: any, catalog: DialectCatalog): void {\n if (typeof node === \"function\") {\n deriveFunction(node, catalog);\n return;\n }\n const type = node.type;\n if (typeof type === \"string\") {\n catalog.exact.add(type);\n return;\n }\n for (const value of Object.values(node)) {\n walk(value, catalog);\n }\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 admit(catalog, type, 0);\n continue;\n }\n // A required-argument function called with too few produces `base(undefined)`\n // — never a value the constant yields — so a non-integer argument is skipped.\n const parts = type.slice(open + 1, -1).split(\",\");\n if (parts.every((part) => INTEGER_ARGUMENT.test(part))) {\n admit(catalog, type.slice(0, open), parts.length);\n }\n }\n}\n\nfunction admit(catalog: DialectCatalog, base: string, arity: number): void {\n const arities = catalog.templates.get(base);\n if (arities === undefined) {\n catalog.templates.set(base, new Set([arity]));\n return;\n }\n arities.add(arity);\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 ROUND_CONSTANTS = new DataView(new ArrayBuffer(ROUNDS * 8));\nfor (const [half, constant] of [\n 0x00_00_00_01, 0x00_00_00_00, 0x00_00_80_82, 0x00_00_00_00, 0x00_00_80_8a,\n 0x80_00_00_00, 0x80_00_80_00, 0x80_00_00_00, 0x00_00_80_8b, 0x00_00_00_00,\n 0x80_00_00_01, 0x00_00_00_00, 0x80_00_80_81, 0x80_00_00_00, 0x00_00_80_09,\n 0x80_00_00_00, 0x00_00_00_8a, 0x00_00_00_00, 0x00_00_00_88, 0x00_00_00_00,\n 0x80_00_80_09, 0x00_00_00_00, 0x80_00_00_0a, 0x00_00_00_00, 0x80_00_80_8b,\n 0x00_00_00_00, 0x00_00_00_8b, 0x80_00_00_00, 0x00_00_80_89, 0x80_00_00_00,\n 0x00_00_80_03, 0x80_00_00_00, 0x00_00_80_02, 0x80_00_00_00, 0x00_00_00_80,\n 0x80_00_00_00, 0x00_00_80_0a, 0x00_00_00_00, 0x80_00_00_0a, 0x80_00_00_00,\n 0x80_00_80_81, 0x80_00_00_00, 0x00_00_80_80, 0x80_00_00_00, 0x80_00_00_01,\n 0x00_00_00_00, 0x80_00_80_08, 0x80_00_00_00,\n].entries()) {\n ROUND_CONSTANTS.setInt32(half * 4, constant, true);\n}\n\n/** Rho: the rotation each lane receives, indexed by `x + 5y`. */\nconst ROTATIONS = new DataView(\n new Uint8Array([\n 0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8,\n 18, 2, 61, 56, 14,\n ]).buffer\n);\n\n/** Pi: where lane `x + 5y` lands, which is `y + 5*((2x + 3y) mod 5)`. */\nconst DESTINATIONS = new DataView(\n new Uint8Array([\n 0, 10, 20, 5, 15, 16, 1, 11, 21, 6, 7, 17, 2, 12, 22, 23, 8, 18, 3, 13, 14,\n 24, 9, 19, 4,\n ]).buffer\n);\n\n/**\n * The permutation state and its two scratch planes, allocated once.\n *\n * `sha3_512` is synchronous from entry to return and this module has no other\n * caller, so one set of buffers is reused rather than allocating a hundred\n * slots per identifier. Every entry begins by zeroing the state.\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\n/**\n * Keccak-f[1600]: 24 rounds of theta, rho + pi, chi and iota.\n *\n * A rotation by `n < 32` takes its missing bits from the other half at\n * `32 - n`; a rotation by `n > 32` is the same shape with the halves swapped\n * and `n - 32`. Neither case is reachable with `n = 0` or `n = 32`, which would\n * need a 32-bit shift JavaScript does not have: rho's only zero is lane 0,\n * which is skipped, and 32 is not one of its offsets.\n */\nfunction permute(): void {\n for (let round = 0; 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 ^= state.getInt32((x + y) * 8, true);\n high ^= state.getInt32((x + y) * 8 + 4, true);\n }\n column.setInt32(x * 8, low, true);\n column.setInt32(x * 8 + 4, high, true);\n }\n for (let x = 0; x < 5; x++) {\n const nextLow = column.getInt32(((x + 1) % 5) * 8, true);\n const nextHigh = column.getInt32(((x + 1) % 5) * 8 + 4, true);\n const deltaLow =\n column.getInt32(((x + 4) % 5) * 8, true) ^\n ((nextLow << 1) | (nextHigh >>> 31));\n const deltaHigh =\n column.getInt32(((x + 4) % 5) * 8 + 4, true) ^\n ((nextHigh << 1) | (nextLow >>> 31));\n for (let y = 0; y < LANES; y += 5) {\n const at = (x + y) * 8;\n state.setInt32(at, state.getInt32(at, true) ^ deltaLow, true);\n state.setInt32(at + 4, state.getInt32(at + 4, true) ^ deltaHigh, true);\n }\n }\n\n // Rho and pi: rotate every lane, then move it to its permuted position.\n plane.setInt32(0, state.getInt32(0, true), true);\n plane.setInt32(4, state.getInt32(4, true), true);\n for (let lane = 1; lane < LANES; lane++) {\n const shift = ROTATIONS.getUint8(lane);\n const low = state.getInt32(lane * 8, true);\n const high = state.getInt32(lane * 8 + 4, true);\n const target = DESTINATIONS.getUint8(lane) * 8;\n if (shift < 32) {\n plane.setInt32(target, (low << shift) | (high >>> (32 - shift)), true);\n plane.setInt32(\n target + 4,\n (high << shift) | (low >>> (32 - shift)),\n true\n );\n } else {\n const rest = shift - 32;\n plane.setInt32(target, (high << rest) | (low >>> (32 - rest)), true);\n plane.setInt32(\n target + 4,\n (low << rest) | (high >>> (32 - rest)),\n true\n );\n }\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 state.setInt32(\n at,\n plane.getInt32(at, true) ^\n (~plane.getInt32(next, true) & plane.getInt32(after, true)),\n true\n );\n state.setInt32(\n at + 4,\n plane.getInt32(at + 4, true) ^\n (~plane.getInt32(next + 4, true) & plane.getInt32(after + 4, true)),\n true\n );\n }\n }\n\n // Iota: the round constant, on the first lane only.\n state.setInt32(\n 0,\n state.getInt32(0, true) ^ ROUND_CONSTANTS.getInt32(round * 8, true),\n true\n );\n state.setInt32(\n 4,\n state.getInt32(4, true) ^ ROUND_CONSTANTS.getInt32(round * 8 + 4, true),\n true\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 state.setInt32(\n at,\n state.getInt32(at, true) ^ block.getInt32(offset + at, true),\n true\n );\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 */\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) => () =>\n applyIdPrefix(prefix, uuidV4());\n\nexport const defaultUuidV7 = (prefix?: string) => () =>\n applyIdPrefix(\n prefix,\n bytesToUuid(\n uuidV7Bytes(Date.now(), randomBytes(UUIDV7_RANDOM_LENGTH, \"uuidv7\"))\n )\n );\n\n// =============================================================================\n// ULID\n// =============================================================================\n\n/** The next 80-bit random block, or a refusal when the block is exhausted. */\nfunction incrementUlidRandom(random: Uint8Array): Uint8Array {\n const next = Uint8Array.from(random);\n const view = new DataView(next.buffer);\n for (let index = next.length - 1; index >= 0; index--) {\n const incremented = view.getUint8(index) + 1;\n view.setUint8(index, incremented & 255);\n if (incremented <= 255) return next;\n }\n return refuseId(\n \"s.string().ulid\",\n \"generate\",\n \"This process issued every ULID one millisecond can hold (2^80). Monotonicity cannot be preserved without emitting a smaller identifier\"\n );\n}\n\n/**\n * One monotonic ULID sequence.\n *\n * Within a millisecond the timestamp repeats, so the 80-bit random block is\n * INCREMENTED instead of redrawn: two ULIDs minted in the same millisecond\n * still sort in the order they were issued. A clock that moves backwards keeps\n * emitting the last timestamp for the same reason — a smaller identifier would\n * break the ordering the format promises, and the ORM cannot fix the clock.\n *\n * The whole block is drawn at once from secure bytes, so every bit is uniform.\n *\n * `now` and `random` are injectable because monotonicity, rollback and\n * exhaustion are statements about a SEQUENCE, and a sequence cannot be observed\n * through a real clock. The process-wide generator below takes the defaults.\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 last: { time: number; random: Uint8Array } | undefined;\n return () => {\n const time = now();\n last =\n last !== undefined && time <= last.time\n ? { time: last.time, random: incrementUlidRandom(last.random) }\n : { time, random: draw(ULID_RANDOM_LENGTH) };\n return bytesToUlid(ulidBytes(last.time, last.random));\n };\n}\n\n/**\n * ONE monotonic sequence per process, shared by every `.ulid()` and `.id()`\n * field. Monotonicity is a property of the issuing process, not of a field: two\n * models minting ULIDs in the same millisecond must not collide, and a\n * per-field sequence would let them.\n */\nconst nextUlid = createUlidGenerator();\n\nexport const defaultUlid = (prefix?: string) => () =>\n applyIdPrefix(prefix, nextUlid());\n\n// =============================================================================\n// KSUID\n// =============================================================================\n\nexport const defaultKsuid = (prefix?: string) => () =>\n applyIdPrefix(\n 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 `A nanoid length must be a whole number of characters between 1 and ${MAX_RANDOM_BYTES}; received ${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\nconst TEXT_ENCODER = new TextEncoder();\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\n/**\n * SHA3-512 of `input`, rendered in base36 with the first digit dropped — that\n * digit is biased toward the low end of the alphabet because the digest is not\n * a whole number of base36 digits.\n */\nfunction hashBase36(input: string): string {\n let value = 0n;\n for (const byte of sha3_512(TEXT_ENCODER.encode(input))) {\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 createCounter(Math.floor(random() * CUID_INITIAL_COUNT_MAX));\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 count = counter().toString(BASE36);\n const salt = createEntropy(length, random);\n return (\n firstLetter +\n hashBase36(time + salt + count + fingerprint).substring(1, length)\n );\n };\n}\n\nfunction createCounter(start: number): () => number {\n let count = start;\n return () => {\n const current = count;\n count++;\n return current;\n };\n}\n\n/**\n * The process-wide CUID2 sequence, built on first use.\n *\n * Lazily, because the fingerprint hashes 32 characters of entropy: building it\n * at import would draw randomness from every process that merely loads VibORM,\n * including ones that never mint an id.\n */\nlet processCuid: (() => string) | undefined;\n\nexport const defaultCuid = (prefix?: string) => () =>\n applyIdPrefix(prefix, (processCuid ??= createCuid2())());\n","// String Scalar\n// Standalone scalar class with State generic pattern\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { hasIdPrefix, refuseId } from \"@validation/primitives/id-formats\";\nimport v from \"@validation/primitives/v\";\nimport {\n type AutoGenerate,\n createDefaultState,\n type DefaultValueInput,\n type GeneratorDefaultBrand,\n generatorDefault,\n isGeneratorDefault,\n nullableDefault,\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(\n \"s.string\",\n \"generate\",\n \"This generator is not a string identifier format\"\n );\n }\n}\n\nconst stringBase = v.string();\n\nexport class StringScalar<State extends ScalarState<\"string\">> {\n private readonly state: State;\n private readonly _nativeType?: NativeTypeDeclaration | undefined;\n\n constructor(state: State, _nativeType?: NativeTypeDeclaration) {\n this.state = state;\n this._nativeType = _nativeType;\n }\n\n nullable() {\n return new StringScalar(\n updateState(this, {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n base: v.string<{\n nullable: true;\n array: State[\"array\"];\n schema: State[\"schema\"];\n }>({\n nullable: true,\n array: this.state.array,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\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 nullable: this.state.nullable,\n array: true,\n schema: this.state.schema,\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 unique() {\n return new StringScalar(\n updateState(this, {\n isUnique: true,\n }),\n this._nativeType\n );\n }\n\n default<V extends DefaultValueInput<State>>(value: V) {\n return new StringScalar(\n updateState(this, {\n hasDefault: true,\n default: value,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n schema<S extends StandardSchemaV1<string>>(schema: S) {\n return new StringScalar(\n updateState(this, {\n schema,\n base: v.string<{\n nullable: State[\"nullable\"];\n array: State[\"array\"];\n schema: S;\n }>({\n nullable: this.state.nullable,\n array: this.state.array,\n schema,\n }),\n }),\n this._nativeType\n );\n }\n\n /**\n * Maps this scalar to a custom column name in the database\n */\n map(columnName: string) {\n return new StringScalar(\n updateState(this, { columnName }),\n this._nativeType\n );\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 return new StringScalar(\n updateState(this, {\n isId,\n isUnique: isId || this.state.isUnique,\n autoGenerate: declaration,\n hasDefault: customDefault || installed,\n optional: customDefault || installed,\n default: installed\n ? generatorDefault(generator)\n : customDefault\n ? this.state.default\n : undefined,\n }),\n this._nativeType\n );\n }\n\n private _internal?: {\n state: State;\n nativeType: NativeTypeDeclaration | undefined;\n };\n\n get [\"~\"]() {\n return (this._internal ??= {\n state: this.state,\n nativeType: 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 `This field already declares a '${declared.kind}' generator${declared.prefix ? ` with the prefix '${declared.prefix}'` : \"\"}. A prefix is spelled once, on the call that declares the format`\n );\n}\n"],"mappings":"0iBAWA,SAAgB,mCACd,EACmC,CACnC,IAAM,EAAoB,IAAI,IAC9B,IAAK,GAAM,CAAC,EAAUA,KAAU,EAAe,CAC7C,GAEE,OAAOA,GAAU,WADjBA,GAEA,CAACA,EAAM,MAAM,OACb,CAACA,EAAM,MAAM,OAAO,QAEpB,MAAO,CACL,KAAM,OACN,QAAS,iBAAiB,EAAS,iFACnC,SAAU,QACV,MAAO,EACR,CACH,IAAM,EAAUA,EAAM,KAAK,MAAM,IAAM,EAAkB,IAAIA,EAAM,C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
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Ft as VibORMClient, It as VibORMConfig, Jr as JunctionReferentialAction, Kn as IndexType, Xi as NativeTypeMap, Yi as NativeType, Yr as ReferentialAction, er as AutoGenerateType, hn as Schema, ir as ScalarType, yr as JsonValue } from "../index-VsM29vYN.mjs";
|
|
2
2
|
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
3
3
|
|
|
4
4
|
//#region src/schema/json/document.d.ts
|
package/dist/schema/json.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"../chunk-BuuaeEvq.mjs";import{c as t,i as n,r}from"../value-guards-CK9guf2Z.mjs";import{k as i}from"../base-AdXAoy6l.mjs";import{t as a}from"../validation-Dk9Q_-C7.mjs";import{_ as o,i as s,m as c,n as l,p as u}from"../terminal-C8cq1WWX.mjs";import{t as d}from"../identifier-hQCs8M1n.mjs";import{a as f}from"../validator-X9-bwtRo.mjs";import{C as p,S as m,a as h,b as g,c as _,i as v,n as y,x as b,y as x}from"../registration-preflight-DEjv050M.mjs";import{_ as S,a as C,c as w,d as T,f as E,g as D,h as O,i as ee,m as te,n as ne,o as re,p as ie,r as ae,s as oe,t as se,u as ce}from"../scalar-U0wD5bKy.mjs";import{t as k}from"../types-C4v6iAmY.mjs";import{a as A,n as j}from"../native-types-veeTk36s.mjs";import{t as M}from"../hydration-CAxOL4aI.mjs";const N=/~/g,P=/\//g;function pointer(e,...t){let n=e;for(let e of t)n+=`/${e.replace(N,`~0`).replace(P,`~1`)}`;return n}function addIssue(e,t,n,r){e.push({path:t,message:`[${n}] ${r}`})}function refuseDocument(e,t){return new a({kind:`schema-builder`,builder:`schema-json`,path:``},e,t===void 0?void 0:{cause:t})}function throwIfRefused(e){if(e.length>0)throw refuseDocument(e)}function member(e,t,n,r){return guardedValue(e,t,n,r,`J004`)}function guardedValue(e,t,n,r,a){try{return Reflect.get(e,t)}catch(e){throw addIssue(r,pointer(n,t),a,`Reading this value threw`),refuseDocument(r,i(e))}}function inspectPlainRecord(e,t,n,r){try{return s(e)}catch(e){throw addIssue(n,t,r,`Inspecting this value's prototype threw`),refuseDocument(n,i(e))}}function inspectKeys(e,t,n,r){try{return l(e)}catch(e){throw addIssue(n,t,r,`Enumerating this value's keys threw`),refuseDocument(n,i(e))}}function renderValue(e){return typeof e==`bigint`?`${e}n`:typeof e==`object`?`[${typeof e}]`:String(e)}function refuseFromBuilder(e,t){let n=[];throw addIssue(n,e,`J010`,t.message),refuseDocument(n,t)}const F=`$bigint`,I=`$date`,L=`$bytes`,R=`$raw`,z=`$jsonNull`,B=new Set([F,I,L,R,z]),V=/^-?\d+$/,H=`'${F}' (a decimal integer string), '${I}' (an ISO timestamp), '${L}' (base64), '${R}' (the literal it wraps), '${z}' ('JsonNull' or 'DbNull')`;function reservedKey(e){let t=e.length===1?e[0]:void 0;return t?.startsWith(`$`)===!0?t:void 0}function readDefaultValue(e,t,n){return readValue(e,t,n,new Set)}function readValue(e,t,r,i){if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`){if(Number.isFinite(e))return e;addIssue(r,t,`J004`,`A default must be a finite number`);return}if(Array.isArray(e))return readArray(e,t,r,i);if(inspectPlainRecord(e,t,r,`J004`))return readRecord(e,t,r,i);addIssue(r,t,`J004`,n(e)?"A function default has no document spelling — use `generate`, a literal, or a database default through `native`":`A default must be a JSON value; a value outside JSON takes a tag — ${H}`)}function readArray(e,t,n,r){if(enterCycle(e,t,n,r,`J004`))return;let i=[];for(let a=0;a<e.length;a+=1){let o=pointer(t,String(a)),s=readValue(member(e,String(a),t,n),o,n,r);if(s===void 0)return;i.push(s)}return r.delete(e),i}function readRecord(e,t,n,r){if(enterCycle(e,t,n,r,`J004`))return;let i=inspectKeys(e,t,n,`J004`),a=reservedKey(i);if(a!==void 0&&!B.has(a)){addIssue(n,t,`J008`,`'${a}' is not a tag this format defines. The tags are ${H}`);return}let o=g();for(let a of i){let i=readValue(member(e,a,t,n),pointer(t,a),n,r);if(i===void 0)return;m(o,a,i)}return r.delete(e),o}function enterCycle(e,t,n,r,i){return r.has(e)?(addIssue(n,t,i,`This default contains a cycle; a document holds a finite value`),!0):(r.add(e),!1)}function decodeDefault(e,t){if(Array.isArray(e))return e.map((e,n)=>decodeDefault(e,pointer(t,String(n))));if(typeof e!=`object`||!e)return e;let n=reservedKey(Object.keys(e));if(n===void 0)return decodeBody(e,t);let r=e[n];if(n===R)return decodeRaw(r,t);if(n===F)return decodeBigInt(r,t);if(n===I)return decodeDate(r,t);if(n===z){if(r===`JsonNull`)return c;if(r===`DbNull`)return u;throw refuseTag(t,`'${z}' takes 'JsonNull' or 'DbNull'`)}return decodeBytes(r,t)}function decodeBody(e,t){let n=g();for(let r of Object.keys(e))m(n,r,decodeDefault(e[r]??null,pointer(t,r)));return n}function decodeRaw(e,t){return typeof e!=`object`||!e?e:Array.isArray(e)?decodeDefault(e,t):decodeBody(e,t)}function decodeBigInt(e,t){if(typeof e==`string`&&V.test(e))return BigInt(e);throw refuseTag(t,`'${F}' takes a decimal integer string`)}function decodeDate(e,t){if(typeof e==`string`){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t}throw refuseTag(t,`'${I}' takes a string naming an instant`)}function decodeBytes(e,t){if(typeof e==`string`)try{return decodeBase64(e)}catch{}throw refuseTag(t,`'${L}' takes a base64 string`)}function refuseTag(e,t){let n=[];return addIssue(n,e,`J008`,`${t}. The tags are ${H}`),refuseDocument(n)}function decodeBase64(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function encodeDefault(e,t,n){return encodeValue(e,t,n,new Set)}function encodeValue(e,n,i,a){let s=o(e);if(s===`JsonNull`||s===`DbNull`)return tagged(z,s);if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isFinite(e)?e:refuseValue(i,n,"A non-finite number has no JSON spelling; `JSON.stringify` would write it as `null`");if(typeof e==`bigint`)return tagged(F,e.toString(10));if(t(e))try{return tagged(L,encodeBase64(e))}catch{return refuseValue(i,n,`This byte string has a detached buffer and cannot be serialized`)}return r(e)?Number.isNaN(Date.prototype.getTime.call(e))?refuseValue(i,n,`An invalid Date names no instant`):tagged(I,Date.prototype.toISOString.call(e)):Array.isArray(e)?encodeArray(e,n,i,a):inspectPlainRecord(e,n,i,`J009`)?encodeRecord(e,n,i,a):refuseValue(i,n,`This default holds a value the document cannot state — a JSON value, a bigint, a Date or a byte string is what a default may be`)}function tagged(e,t){let n=g();return m(n,e,t),n}function encodeArray(e,t,n,r){if(enterCycle(e,t,n,r,`J009`))return;let i=[];for(let a=0;a<e.length;a+=1){let o=String(a),s=encodeValue(guardedValue(e,o,t,n,`J009`),pointer(t,o),n,r);if(s===void 0)return;i.push(s)}return r.delete(e),i}function encodeRecord(e,t,n,r){if(enterCycle(e,t,n,r,`J009`))return;let i=g();for(let a of inspectKeys(e,t,n,`J009`)){let o=encodeValue(guardedValue(e,a,t,n,`J009`),pointer(t,a),n,r);if(o===void 0)return;m(i,a,o)}if(r.delete(e),reservedKey(Object.keys(i))===void 0)return i;let a=g();return m(a,R,i),a}function refuseValue(e,t,n){addIssue(e,t,`J009`,n)}function encodeBase64(e){let t=``,n=Uint8Array.prototype.values.call(e);for(let e of n)t+=String.fromCharCode(e);return btoa(t)}const U=1;function isRelationField(e){return e.type===`toOne`||e.type===`toMany`}const W={string:y,int:C,number:ae,boolean:te,datetime:E,date:ie,time:T,bigint:D,json:ee,blob:O,vector:se,point:ne},G=new Set([...Object.keys(W),`decimal`,`enum`]);function builderMethod(e,t){let n=Reflect.get(e,t);return typeof n==`function`?n:void 0}function interpret(e,t){let n={},r=pointer(``,`models`);refuseUnknownFieldSchemas(e,t);for(let[i,a]of Object.entries(e.models))n[i]=buildModel(i,a,e,n,pointer(r,i),t);return n}function refuseUnknownFieldSchemas(e,t){if(t===void 0)return;let n=[];for(let r of Object.keys(t)){let t=r.indexOf(`.`),i=e.models[r.slice(0,t)]?.fields[r.slice(t+1)];i!==void 0&&!isRelationField(i)||addIssue(n,``,`J006`,`Field schema '${r}' does not name a scalar field of this schema; spell it '<model>.<field>'`)}if(n.length>0)throw refuseDocument(n)}function buildModel(e,t,n,r,i,a){let o=pointer(i,`fields`),s={};for(let[i,c]of Object.entries(t.fields)){let t=pointer(o,i);if(isRelationField(c)){s[i]=buildRelation(c,r,t);continue}s[i]=buildScalar(c,n,t,a?.[`${e}.${i}`])}let c=call(i,()=>x(s));if(t.table!==void 0){let e=t.table;c=call(pointer(i,`table`),()=>c.map(e))}for(let[e,n]of(t.indexes??[]).entries()){let t=pointer(i,`indexes`,String(e)),r={...n.name===void 0?{}:{name:n.name},...n.unique===void 0?{}:{unique:n.unique},...n.type===void 0?{}:{type:n.type}};c=call(t,()=>Reflect.apply(c.index,c,[n.fields,r]))}for(let[e,n]of(t.ids??[]).entries())c=call(pointer(i,`ids`,String(e)),()=>c.id(n.fields,options(n.name)));for(let[e,n]of(t.uniques??[]).entries())c=call(pointer(i,`uniques`,String(e)),()=>c.unique(n.fields,options(n.name)));if(t.omit!==void 0){let e={};for(let n of t.omit)e[n]=!0;c=call(pointer(i,`omit`),()=>c.omit(e))}return c}function options(e){return e===void 0?{}:{name:e}}function buildScalar(e,t,n,r){let i=e.type,a=createScalar(e,t,n);if(e.array&&(a=modify(a,`array`,[],i,pointer(n,`array`))),e.nullable&&(a=modify(a,`nullable`,[],i,pointer(n,`nullable`))),e.id){let t=e.generate?.implicit===!0,r=e.generate?.generate===!1?[{generate:!1,prefix:t?e.generate.prefix:void 0}]:t&&e.generate?.prefix!==void 0?[e.generate.prefix]:[];a=modify(a,`id`,r,i,pointer(n,`id`))}e.unique&&(a=modify(a,`unique`,[],i,pointer(n,`unique`))),e.withoutTimezone&&(a=modify(a,`withoutTimezone`,[],i,pointer(n,`withoutTimezone`))),e.dimension!==void 0&&(a=modify(a,`dimension`,[e.dimension],i,pointer(n,`dimension`))),e.generate!==void 0&&e.generate.implicit!==!0&&(a=applyGenerate(a,e.generate,i,n));let o=e.default;return o!==void 0&&(a=applyDefault(a,e,o,n)),e.column!==void 0&&(a=modify(a,`map`,[e.column],i,pointer(n,`column`))),r!==void 0&&(a=modify(a,`schema`,[r],i,pointer(n,`schema`))),a}function createScalar(e,t,n){if(e.type===`decimal`){let{precision:t,scale:r}=e;return call(n,()=>w({precision:t,scale:r}))}let r=e.native??e.nativeByDialect;if(e.type!==`enum`){let t=W[e.type];return call(n,()=>r===void 0?t():t(r))}let i=resolveEnum(e,t,n),a=call(n,()=>re(i.values,r));if(i.name===void 0)return a;let o=i.name;return modify(a,`name`,[o],`enum`,pointer(n,`enum`))}function resolveEnum(e,t,n){let r=e.enum;if(Array.isArray(r))return{values:r};let i=t.enums?.[r];if(i!==void 0)return i;let a=[];throw addIssue(a,pointer(n,`enum`),`J006`,`\`enum\` names '${r}', which \`enums\` does not declare`),refuseDocument(a)}function modify(e,t,n,r,i){let a=builderMethod(e,t);if(a===void 0){let e=[];throw addIssue(e,i,`J007`,`A '${r}' field has no '${t}' modifier`),refuseDocument(e)}return call(i,()=>a.apply(e,n))}function applyGenerate(e,t,n,r){let i=pointer(r,`generate`),a=![`now`,`updatedAt`,`increment`].includes(t.kind),o=t.generate===!1?{prefix:t.prefix,length:t.length}:{prefix:t.prefix,length:t.length,generate:!0},s=a?[o]:[t.prefix],c=modify(e,t.kind,s,n,i),l=c[`~`].state.autoGenerate;if(l?.prefix===t.prefix&&l?.length===t.length)return c;let u=[];throw addIssue(u,i,`J007`,`The '${t.kind}' generator does not take the 'prefix' or 'length' this node declares`),refuseDocument(u)}function applyDefault(e,t,n,r){let i=pointer(r,`default`),a=decodeDefault(n,i);if(t.type===`json`&&o(a)!==void 0)return modify(e,`default`,[a],t.type,i);let s=e[`~`].state.base[`~standard`].validate(a),c=t.type===`bigint`&&[a].flat().some(e=>typeof e==`string`);if(s.issues||c){let e=s.issues?s.issues.map(e=>e.message).join(`; `):`a bigint is written {"$bigint": "<integer>"}`,n=[];throw addIssue(n,i,`J008`,`A '${t.type}' default must be a value of the field's own domain: ${e}`),refuseDocument(n)}return e instanceof oe?ce(e,s.value):modify(e,`default`,[a],t.type,i)}function buildRelation(e,t,n){let r=e.target===void 0?buildVariantRelation(e,t,n):buildModelRelation(e,t,n);if(e.name===void 0)return r;let i=e.name;return call(pointer(n,`name`),()=>r.name(i))}function buildModelRelation(e,t,n){let r=e.target,getter=()=>t[r],i=e.type===`toOne`?p:S,a=call(n,()=>Reflect.apply(i,void 0,[getter]));if(e.fields!==void 0){let t=e.fields;a=call(pointer(n,`fields`),()=>a.fields(...t))}if(e.references!==void 0){let t=e.references;a=call(pointer(n,`references`),()=>a.references(...t))}for(let t of[`onDelete`,`onUpdate`]){let r=e[t];r!==void 0&&(a=call(pointer(n,t),()=>a[t](r)))}return e.junction!==void 0&&(a=applyJunction(a,e.junction,n)),a}function buildVariantRelation(e,t,n){let r={};for(let[n,i]of Object.entries(e.variants))r[n]=()=>t[i];let i=e.type===`toOne`?p:S,a=e.values===void 0?[r]:[r,{values:e.values}],o=call(n,()=>Reflect.apply(i,void 0,a));if(e.through!==void 0){let t=e.through;o=call(pointer(n,`through`),()=>o.through(t))}return e.optional&&(o=call(pointer(n,`optional`),()=>o.optional())),o}const le=[[`table`,`through`],[`source`,`source`],[`target`,`target`],[`onDelete`,`onDelete`],[`onUpdate`,`onUpdate`],[`onDeleteSides`,`onDelete`],[`onUpdateSides`,`onUpdate`]];function applyJunction(e,t,n){let r=e,i=pointer(n,`junction`);for(let[e,n]of le){let a=t[e];a!==void 0&&(r=call(pointer(i,e),()=>r[n](a)))}return r}function call(e,t){try{return t()}catch(t){return refuseFromBuilder(e,i(t))}}const K={cascade:!0,setNull:!0,restrict:!0,noAction:!0},q={cascade:!0,restrict:!0,noAction:!0},J={btree:!0,hash:!0,gin:!0,gist:!0,fulltext:!0,spatial:!0},Y={uuid:!0,uuidv7:!0,ulid:!0,ksuid:!0,nanoid:!0,cuid:!0,increment:!0,now:!0,updatedAt:!0},isReferentialAction=e=>typeof e==`string`&&Object.hasOwn(K,e),isJunctionAction=e=>typeof e==`string`&&Object.hasOwn(q,e),isIndexType=e=>typeof e==`string`&&Object.hasOwn(J,e),isGenerateKind=e=>typeof e==`string`&&Object.hasOwn(Y,e),isNativeDialect=e=>typeof e==`string`&&j.some(t=>t===e),isScalarTypeName=e=>typeof e==`string`&&G.has(e),ue=[`version`,`enums`,`models`],de=[`values`,`name`],fe=[`table`,`fields`,`indexes`,`ids`,`uniques`,`omit`],pe=[`fields`,`name`,`unique`,`type`,`where`],me=[`fields`,`name`],he=[`db`,`type`],ge=[`kind`,`prefix`,`length`,`implicit`,`generate`],X=[`table`,`source`,`target`,`onDelete`,`onUpdate`,`onDeleteSides`,`onUpdateSides`],_e=[`source`,`target`],ve=[`table`,`source`,`target`],Z=[`type`,`native`,`nativeByDialect`,`nullable`,`array`,`id`,`unique`,`column`,`default`,`generate`,`enum`,`dimension`,`precision`,`scale`,`withoutTimezone`],ye=[...new Set([...Z,...relationKeys({cardinality:`one`,variants:!1}),...relationKeys({cardinality:`many`,variants:!1}),...relationKeys({cardinality:`one`,variants:!0}),...relationKeys({cardinality:`many`,variants:!0})])];function relationKeys(e){let t=[`type`,`name`];return e.variants?(t.push(`variants`,`values`),t.push(e.cardinality===`one`?`optional`:`through`),t):(t.push(`target`),e.cardinality===`one`?(t.push(`fields`,`references`,`onDelete`,`onUpdate`),t):(t.push(`junction`),t))}function elements(e,t,n){let r=[];for(let i=0;i<e.length;i+=1)r.push(member(e,String(i),t,n));return r}function asRecord(e,t,n,r){if(inspectPlainRecord(e,t,n,`J004`))return e;addIssue(n,t,`J004`,`${r} must be a plain JSON object`)}function asString(e,t,n,r){if(typeof e==`string`)return e;addIssue(n,t,`J004`,`${r} must be a string`)}function asBoolean(e,t,n,r){if(typeof e==`boolean`)return e;addIssue(n,t,`J004`,`${r} must be a boolean`)}function asNumber(e,t,n,r){if(typeof e==`number`&&Number.isFinite(e))return e;addIssue(n,t,`J004`,`${r} must be a finite number`)}function asStringArray(e,t,n,r){if(!Array.isArray(e)){addIssue(n,t,`J004`,`${r} must be an array of strings`);return}let i=[],a=!0;for(let[o,s]of elements(e,t,n).entries()){let e=asString(s,pointer(t,String(o)),n,r);if(e===void 0){a=!1;continue}i.push(e)}return a?i:void 0}function refuseUnknownKeys(e,t,n,r,i=`this node`){for(let a of inspectKeys(e,n,r,`J004`)){if(!t.includes(a)){addIssue(r,pointer(n,a),`J003`,`Unknown key '${a}'; ${i} declares ${renderKeys(t)}`);continue}member(e,a,n,r)===void 0&&addIssue(r,pointer(n,a),`J004`,`'${a}' is \`undefined\`; a document omits an absent key rather than setting it to \`undefined\``)}}function refuseInvalidKey(e,t,n,r){return d(e)?!0:(addIssue(n,t,`J005`,`${r} '${e}' is not a valid schema identifier`),!1)}function renderKeys(e){return e.map(e=>`'${e}'`).join(`, `)}function readDocument(e){let t=[],n=intake(e,t);throwIfRefused(t);let r=asRecord(n,``,t,`A schema document`);if(r===void 0)throw refuseDocument(t);refuseUnknownKeys(r,ue,``,t);let i=member(r,`version`,``,t);if(i!==1)throw addIssue(t,pointer(``,`version`),`J002`,`Unsupported document version ${renderValue(i)}; this parser reads version 1`),refuseDocument(t);let a={version:1,models:readModels(r,t)},o=readEnums(r,t);return o!==void 0&&(a.enums=o),resolveReferences(a,t),throwIfRefused(t),a}function intake(e,t){if(typeof e!=`string`)return e;try{return JSON.parse(e)}catch(e){addIssue(t,``,`J001`,`The document is not valid JSON: ${String(e)}`);return}}function readEnums(e,t){let n=pointer(``,`enums`),r=member(e,`enums`,``,t);if(r===void 0)return;let i=asRecord(r,n,t,"`enums`");if(i===void 0)return;let a={};for(let e of inspectKeys(i,n,t,`J004`)){let r=pointer(n,e);if(!refuseInvalidKey(e,r,t,`Enum reference`))continue;let o=readEnumNode(member(i,e,n,t),r,t);o!==void 0&&(a[e]=o)}return a}function readEnumNode(e,t,n){let r=asRecord(e,t,n,`An enum definition`);if(r===void 0)return;refuseUnknownKeys(r,de,t,n);let i=asStringArray(member(r,`values`,t,n),pointer(t,`values`),n,"`values`");if(i===void 0)return;let a={values:i},o=member(r,`name`,t,n);if(o!==void 0){let e=asString(o,pointer(t,`name`),n,"`name`");e!==void 0&&(a.name=e)}return a}function readModels(e,t){let n=pointer(``,`models`),r={},i=asRecord(member(e,`models`,``,t),n,t,"`models`");if(i===void 0)return r;for(let e of inspectKeys(i,n,t,`J004`)){let a=pointer(n,e);if(!refuseInvalidKey(e,a,t,`Model key`))continue;let o=readModelNode(member(i,e,n,t),a,t);o!==void 0&&(r[e]=o)}return r}function readModelNode(e,t,n){let r=asRecord(e,t,n,`A model`);if(r===void 0)return;refuseUnknownKeys(r,fe,t,n);let i={fields:readFields(r,t,n)},a=member(r,`table`,t,n);if(a!==void 0){let e=asString(a,pointer(t,`table`),n,"`table`");e!==void 0&&(i.table=e)}let o=readIndexes(r,t,n);o!==void 0&&(i.indexes=o);let s=readCompoundKeys(r,`ids`,t,n);s!==void 0&&(i.ids=s);let c=readCompoundKeys(r,`uniques`,t,n);c!==void 0&&(i.uniques=c);let l=readOmit(r,t,n);return l!==void 0&&(i.omit=l),i}function readFields(e,t,n){let r=pointer(t,`fields`),i={},a=asRecord(member(e,`fields`,t,n),r,n,"`fields`");if(a===void 0)return i;for(let e of inspectKeys(a,r,n,`J004`)){let t=pointer(r,e);if(!refuseInvalidKey(e,t,n,`Field key`))continue;let o=readFieldNode(member(a,e,r,n),t,n);o!==void 0&&(i[e]=o)}return i}function readIndexes(e,t,n){let r=pointer(t,`indexes`),i=member(e,`indexes`,t,n);if(i===void 0)return;if(!Array.isArray(i)){addIssue(n,r,`J004`,"`indexes` must be an array");return}let a=[];for(let[e,t]of elements(i,r,n).entries()){let i=readIndexNode(t,pointer(r,String(e)),n);i!==void 0&&a.push(i)}return a}function readIndexNode(e,t,n){let r=asRecord(e,t,n,`An index`);if(r===void 0)return;inspectKeys(r,t,n,`J004`).includes(`where`)&&addIssue(n,pointer(t,`where`),`J009`,"`where` is refused in v1: it is raw SQL interpolated unescaped into DDL, and a machine-written document must not carry an execution channel. It returns when a structured predicate form exists"),refuseUnknownKeys(r,pe,t,n);let i=asStringArray(member(r,`fields`,t,n),pointer(t,`fields`),n,"`fields`");if(i===void 0)return;let a={fields:i},o=member(r,`name`,t,n);if(o!==void 0){let e=asString(o,pointer(t,`name`),n,"`name`");e!==void 0&&(a.name=e)}let s=member(r,`unique`,t,n);if(s!==void 0){let e=asBoolean(s,pointer(t,`unique`),n,"`unique`");e!==void 0&&(a.unique=e)}let c=member(r,`type`,t,n);return c!==void 0&&(isIndexType(c)?a.type=c:addIssue(n,pointer(t,`type`),`J004`,`\`type\` must be one of ${renderKeys(Object.keys(J))}`)),a}function readCompoundKeys(e,t,n,r){let i=pointer(n,t),a=member(e,t,n,r);if(a===void 0)return;if(!Array.isArray(a)){addIssue(r,i,`J004`,`\`${t}\` must be an array`);return}let o=[];for(let[e,t]of elements(a,i,r).entries()){let n=readCompoundKeyNode(t,pointer(i,String(e)),r);n!==void 0&&o.push(n)}return o}function readCompoundKeyNode(e,t,n){let r=asRecord(e,t,n,`A compound key`);if(r===void 0)return;refuseUnknownKeys(r,me,t,n);let i=asStringArray(member(r,`fields`,t,n),pointer(t,`fields`),n,"`fields`");if(i===void 0)return;let a={fields:i},o=member(r,`name`,t,n);if(o!==void 0){let e=asString(o,pointer(t,`name`),n,"`name`");e!==void 0&&(a.name=e)}return a}function readOmit(e,t,n){let r=member(e,`omit`,t,n);if(r!==void 0)return asStringArray(r,pointer(t,`omit`),n,"`omit`")}function readFieldNode(e,t,n){let r=asRecord(e,t,n,`A field`);if(r===void 0)return;let i=member(r,`type`,t,n);if(i===`toOne`||i===`toMany`)return readRelationField(r,i,t,n);if(isScalarTypeName(i))return readScalarField(r,i,t,n);addIssue(n,pointer(t,`type`),`J004`,`\`type\` must be 'toOne', 'toMany', or one of ${renderKeys([...G])}`),refuseUnknownKeys(r,ye,t,n,`a field node`)}function readScalarField(e,t,n,r){refuseUnknownKeys(e,Z,n,r);let i=readScalarArm(e,t,n,r);if(i===void 0)return;readFlag(e,`nullable`,n,r,i),readFlag(e,`array`,n,r,i),readFlag(e,`id`,n,r,i),readFlag(e,`unique`,n,r,i),readFlag(e,`withoutTimezone`,n,r,i);let a=member(e,`column`,n,r);if(a!==void 0){let e=asString(a,pointer(n,`column`),r,"`column`");e!==void 0&&(i.column=e)}let o=member(e,`dimension`,n,r);if(o!==void 0)if(t===`point`)refusePointModifier(`dimension`,n,r);else{let e=asNumber(o,pointer(n,`dimension`),r,"`dimension`");e!==void 0&&(i.dimension=e)}t!==`decimal`&&(refuseDecimalDomainBound(e,`precision`,n,r),refuseDecimalDomainBound(e,`scale`,n,r));let s=member(e,`native`,n,r);if(s!==void 0)if(i.type===`point`)refusePointModifier(`native`,n,r);else if(i.type===`decimal`)addIssue(r,pointer(n,`native`),`J003`,"`native` does not belong to a decimal field; its physical type is derived from `precision` and `scale`");else{let e=readNativeNode(s,pointer(n,`native`),r);e!==void 0&&(i.native=e)}let c=member(e,`nativeByDialect`,n,r);if(c!==void 0)if(i.type===`point`)refusePointModifier(`nativeByDialect`,n,r);else if(i.type===`decimal`||s!==void 0)addIssue(r,pointer(n,`nativeByDialect`),`J003`,i.type===`decimal`?"`nativeByDialect` does not belong to a decimal field; its physical type is derived from `precision` and `scale`":"`native` and `nativeByDialect` are two spellings of one declaration; a field carries at most one");else{let e=readNativeByDialectNode(c,pointer(n,`nativeByDialect`),r);e!==void 0&&(i.nativeByDialect=e)}let l=member(e,`generate`,n,r);if(l!==void 0)if(t===`point`)refusePointModifier(`generate`,n,r);else{let e=readGenerateNode(l,pointer(n,`generate`),r,i.id===!0);e!==void 0&&(i.generate=e)}let u=member(e,`default`,n,r);if(u!==void 0){let e=readDefaultValue(u,pointer(n,`default`),r);e!==void 0&&(i.default=e)}return i}function readRequiredDomainBound(e,t,n,r){let i=member(e,t,n,r);if(i===void 0){addIssue(r,pointer(n,t),`J004`,`A decimal field must declare \`${t}\``);return}return asNumber(i,pointer(n,t),r,`\`${t}\``)}function refuseDecimalDomainBound(e,t,n,r){member(e,t,n,r)!==void 0&&addIssue(r,pointer(n,t),`J003`,`\`${t}\` belongs only to a field of type 'decimal'`)}function readScalarArm(e,t,n,r){let i=member(e,`enum`,n,r),a=pointer(n,`enum`);if(t!==`enum`){if(i!==void 0&&addIssue(r,a,`J003`,"`enum` belongs to a field of type 'enum'"),t===`decimal`){let i=readRequiredDomainBound(e,`precision`,n,r),a=readRequiredDomainBound(e,`scale`,n,r);return i===void 0||a===void 0?void 0:{type:t,precision:i,scale:a}}return{type:t}}if(i===void 0){addIssue(r,a,`J004`,"An enum field declares `enum` as an `enums` reference or an inline array of values");return}if(typeof i==`string`)return{type:t,enum:i};let o=asStringArray(i,a,r,"`enum`");if(o!==void 0)return{type:t,enum:o}}function readFlag(e,t,n,r,i){let a=member(e,t,n,r);if(a===void 0)return;if(i.type===`point`&&t!==`nullable`){refusePointModifier(t,n,r);return}let o=asBoolean(a,pointer(n,t),r,`\`${t}\``);if(o!==void 0){if(t===`nullable`){i.nullable=o;return}i.type!==`point`&&(i[t]=o)}}function refusePointModifier(e,t,n){addIssue(n,pointer(t,e),`J007`,`A 'point' field has no '${e}' modifier`)}function readNativeNode(e,t,n){let r=asRecord(e,t,n,"`native`");if(r===void 0)return;refuseUnknownKeys(r,he,t,n);let i=member(r,`db`,t,n),a=asString(member(r,`type`,t,n),pointer(t,`type`),n,"`native.type`");if(!isNativeDialect(i)){addIssue(n,pointer(t,`db`),`J004`,`\`native.db\` must be one of ${renderKeys(j)}`);return}if(a!==void 0){if(!v(i,a)){addIssue(n,pointer(t,`type`),`J011`,h(i));return}return{db:i,type:a}}}function readNativeByDialectNode(e,t,n){let r=asRecord(e,t,n,"`nativeByDialect`");if(r===void 0)return;refuseUnknownKeys(r,j,t,n);let i={},a=readDialectEntry(r,`pg`,t,n);a!==void 0&&(i.pg=a);let o=readDialectEntry(r,`mysql`,t,n);o!==void 0&&(i.mysql=o);let s=readDialectEntry(r,`sqlite`,t,n);return s!==void 0&&(i.sqlite=s),i}function readDialectEntry(e,t,n,r){let i=member(e,t,n,r);if(i===void 0)return;let a=pointer(n,t),o=readNativeNode(i,a,r);if(o!==void 0){if(o.db!==t){addIssue(r,pointer(a,`db`),`J004`,`The '${t}' entry's \`db\` must be '${t}'`);return}return{db:t,type:o.type}}}function readGenerateNode(e,t,n,r){let i=asRecord(e,t,n,"`generate`");if(i===void 0)return;refuseUnknownKeys(i,ge,t,n);let a=member(i,`kind`,t,n);if(!isGenerateKind(a)){addIssue(n,pointer(t,`kind`),`J004`,`\`generate.kind\` must be one of ${renderKeys(Object.keys(Y))}`);return}let o={kind:a},s=member(i,`generate`,t,n);if(s!==void 0){let e=asBoolean(s,pointer(t,`generate`),n,"`generate`");a===`now`||a===`updatedAt`||a===`increment`?addIssue(n,pointer(t,`generate`),`J004`,`An explicit generation choice belongs only to string identifier formats`):e!==void 0&&(o.generate=e)}let c=member(i,`prefix`,t,n);if(c!==void 0){let e=asString(c,pointer(t,`prefix`),n,"`prefix`");e!==void 0&&(o.prefix=e)}let l=member(i,`length`,t,n);if(l!==void 0){let e=asNumber(l,pointer(t,`length`),n,"`length`");e!==void 0&&(o.length=e)}let u=member(i,`implicit`,t,n);return u!==void 0&&asBoolean(u,pointer(t,`implicit`),n,"`implicit`")===!0&&(a===`ulid`?r?o.implicit=!0:addIssue(n,pointer(t,`implicit`),`J004`,"`generate.implicit` describes the ULID `.id()` installs, so it belongs only beside `id: true`"):addIssue(n,pointer(t,`implicit`),`J004`,'`generate.implicit` describes the ULID `.id()` installs, so it belongs only to `kind: "ulid"`')),o}function readRelationField(e,t,n,r){let i=member(e,`target`,n,r),a=member(e,`variants`,n,r);if(i===void 0==(a===void 0)){addIssue(r,n,`J004`,"A relation names exactly one target domain: `target` for one model, or `variants` for named variants");return}let o=t===`toOne`?`one`:`many`;refuseUnknownKeys(e,relationKeys({cardinality:o,variants:a!==void 0}),n,r);let s=readName(e,n,r);if(i===void 0)return readVariantTargetArm(e,{type:t,variants:a},s,o,n,r);let c=asString(i,pointer(n,`target`),r,"`target`");if(c!==void 0)return readModelTargetArm(e,{type:t,target:c},s,o,n,r)}function readName(e,t,n){let r=member(e,`name`,t,n);if(r!==void 0)return asString(r,pointer(t,`name`),n,"`name`")}function readModelTargetArm(e,t,n,r,i,a){if(n!==void 0&&(t.name=n),r===`many`){let n=member(e,`junction`,i,a);if(n!==void 0){let e=readJunctionNode(n,pointer(i,`junction`),a);e!==void 0&&(t.junction=e)}return t}for(let n of[`fields`,`references`]){let r=member(e,n,i,a);if(r===void 0)continue;let o=asStringArray(r,pointer(i,n),a,`\`${n}\``);o!==void 0&&(t[n]=o)}for(let n of[`onDelete`,`onUpdate`]){let r=member(e,n,i,a);if(r!==void 0){if(isReferentialAction(r)){t[n]=r;continue}addIssue(a,pointer(i,n),`J004`,`\`${n}\` must be one of ${renderKeys(Object.keys(K))}`)}}return t}function readVariantTargetArm(e,t,n,r,i,a){let o=readVariantMap(t.variants,pointer(i,`variants`),a);if(o===void 0)return;let s={type:t.type,variants:o};n!==void 0&&(s.name=n);let c=member(e,`values`,i,a);if(c!==void 0){let e=readStringMap(c,pointer(i,`values`),a,"`values`");e!==void 0&&(s.values=e)}if(r===`one`){let t=member(e,`optional`,i,a);if(t!==void 0){let e=asBoolean(t,pointer(i,`optional`),a,"`optional`");e!==void 0&&(s.optional=e)}return s}let l=member(e,`through`,i,a);if(l!==void 0){let e=readThroughMap(l,pointer(i,`through`),a);e!==void 0&&(s.through=e)}return s}function readVariantMap(e,t,n){let r=asRecord(e,t,n,"`variants`");if(r===void 0)return;let i={};for(let e of inspectKeys(r,t,n,`J004`)){let a=pointer(t,e);if(!refuseInvalidKey(e,a,n,`Variant key`))continue;let o=asString(member(r,e,t,n),a,n,`A variant target`);o!==void 0&&(i[e]=o)}return i}function readStringMap(e,t,n,r){let i=asRecord(e,t,n,r);if(i===void 0)return;let a={};for(let e of inspectKeys(i,t,n,`J004`)){let o=pointer(t,e);if(!refuseInvalidKey(e,o,n,`Variant key`))continue;let s=asString(member(i,e,t,n),o,n,r);s!==void 0&&(a[e]=s)}return a}function readThroughMap(e,t,n){let r=asRecord(e,t,n,"`through`");if(r===void 0)return;let i={};for(let e of inspectKeys(r,t,n,`J004`)){let a=pointer(t,e);if(!refuseInvalidKey(e,a,n,`Variant key`))continue;let o=readVariantJunctionNode(member(r,e,t,n),a,n);o!==void 0&&(i[e]=o)}return i}function readVariantJunctionNode(e,t,n){let r=asRecord(e,t,n,`A member junction`);if(r===void 0)return;refuseUnknownKeys(r,ve,t,n);let i=asString(member(r,`table`,t,n),pointer(t,`table`),n,"`table`"),a=asString(member(r,`source`,t,n),pointer(t,`source`),n,"`source`"),o=asString(member(r,`target`,t,n),pointer(t,`target`),n,"`target`");if(!(i===void 0||a===void 0||o===void 0))return{table:i,source:a,target:o}}function readJunctionNode(e,t,n){let r=asRecord(e,t,n,"`junction`");if(r===void 0)return;if(refuseUnknownKeys(r,X,t,n),inspectKeys(r,t,n,`J004`).length===0){addIssue(n,t,`J004`,"`junction` declares at least one of 'table', 'source', 'target', 'onDelete', 'onUpdate', 'onDeleteSides', 'onUpdateSides'; omit it to keep the derived defaults");return}let i={};for(let e of[`table`,`source`,`target`]){let a=member(r,e,t,n);if(a===void 0)continue;let o=asString(a,pointer(t,e),n,`\`${e}\``);o!==void 0&&(i[e]=o)}let a=readJunctionActionSpelling(r,`onDelete`,t,n),o=readJunctionActionSpelling(r,`onUpdate`,t,n);return{...i,...typeof a==`string`?{onDelete:a}:a&&{onDeleteSides:a},...typeof o==`string`?{onUpdate:o}:o&&{onUpdateSides:o}}}function readJunctionActionSpelling(e,t,n,r){let i=member(e,t,n,r),a=`${t}Sides`,o=member(e,a,n,r);if(i!==void 0&&o!==void 0){addIssue(r,pointer(n,a),`J004`,`\`${t}\` and \`${a}\` are exclusive: one action for both foreign keys, or one per side`);return}if(o!==void 0)return readJunctionSides(o,pointer(n,a),r,a);if(i!==void 0)return readJunctionAction(i,pointer(n,t),r,t)}function readJunctionSides(e,t,n,r){let i=asRecord(e,t,n,`\`${r}\``);if(i===void 0)return;refuseUnknownKeys(i,_e,t,n);let readSide=e=>{let a=member(i,e,t,n);if(a!==void 0)return readJunctionAction(a,pointer(t,e),n,`${r}.${e}`);addIssue(n,pointer(t,e),`J004`,`\`${r}\` states both 'source' and 'target'; '${e}' is missing`)},a=readSide(`source`),o=readSide(`target`);if(!(a===void 0||o===void 0))return{source:a,target:o}}function readJunctionAction(e,t,n,r){if(isJunctionAction(e))return e;addIssue(n,t,`J004`,`A junction \`${r}\` must be one of ${renderKeys(Object.keys(q))}; 'setNull' cannot null a membership-key member`)}function resolveReferences(e,t){let n=pointer(``,`models`);for(let[r,i]of Object.entries(e.models)){let a=pointer(n,r),o=pointer(a,`fields`);for(let[n,r]of Object.entries(i.fields))resolveTargetReferences(e,r,pointer(o,n),t);resolveOmitReferences(i,a,t)}}function resolveTargetReferences(e,t,n,r){if(isRelationField(t)){t.target!==void 0&&refuseUnknownModel(e,t.target,pointer(n,`target`),r);for(let[i,a]of Object.entries(t.variants??{}))refuseUnknownModel(e,a,pointer(n,`variants`,i),r)}}function refuseUnknownModel(e,t,n,r){Object.hasOwn(e.models,t)||addIssue(r,n,`J006`,`Model '${t}' is not declared in \`models\``)}function resolveOmitReferences(e,t,n){for(let[r,i]of(e.omit??[]).entries()){let a=e.fields[i];a!==void 0&&!isRelationField(a)||addIssue(n,pointer(t,`omit`,String(r)),`J006`,`\`omit\` names '${i}', which is not a scalar field of this model`)}}const Q=[`validate`],be=Q.map(e=>`'${e}'`).join(`, `),$=pointer(``,`options`);function readValidateOption(e){if(e===void 0)return!1;let t=[];if(!inspectPlainRecord(e,$,t,`J004`))throw addIssue(t,$,`J004`,"`options` must be a plain object"),refuseDocument(t);for(let n of inspectKeys(e,$,t,`J004`))Q.includes(n)||addIssue(t,pointer($,n),`J003`,`Unknown option '${n}'; this call declares ${be}`);let n=member(e,`validate`,$,t);return n!==void 0&&typeof n!=`boolean`&&addIssue(t,pointer($,`validate`),`J004`,"`validate` must be a boolean"),throwIfRefused(t),n===!0}function validateGraph(e){M(e),f(e)}function serializeSchema(e,t){readValidateOption(t)&&validateGraph(e);let n=[],r={refs:new Map,definitions:g()},i=g(),a=pointer(``,`models`);for(let[t,o]of Object.entries(e))m(i,t,serializeModel(o,e,r,pointer(a,t),n));throwIfRefused(n);let o={version:1,models:i};return Object.keys(r.definitions).length>0&&(o.enums=r.definitions),o}function serializeModel(e,t,n,r,i){let a=e[`~`].state,o=a.relations,s=a.scalars,c=g(),l=pointer(r,`fields`);for(let e of Object.keys(a.shape)){let r=b(o,e),a=b(s,e),u=pointer(l,e);if(r!==void 0){m(c,e,serializeRelation(r,t,u,i));continue}a!==void 0&&m(c,e,serializeScalar(a,n,u,i))}let u={fields:c};a.tableName!==void 0&&(u.table=a.tableName);let d=serializeIndexes(a.indexes,r,i);d.length>0&&(u.indexes=d);let f=serializeCompound(a.compoundId);f.length>0&&(u.ids=f);let p=serializeCompound(a.compoundUniques);return p.length>0&&(u.uniques=p),a.omit!==void 0&&(u.omit=Object.keys(a.omit).sort()),u}function serializeIndexes(e,t,n){let r=[];for(let[i,a]of e.entries()){let e=pointer(t,`indexes`,String(i));if(a.options.where!==void 0){addIssue(n,e,`J009`,"This index carries a `where` predicate — raw SQL the v1 document refuses to carry. Drop the partial index or keep this schema in code");continue}let o={fields:[...a.fields]};a.options.name!==void 0&&(o.name=a.options.name),a.options.unique!==void 0&&(o.unique=a.options.unique),a.options.type!==void 0&&(o.type=a.options.type),r.push(o)}return r}function serializeCompound(e){let t=[];for(let[n,r]of Object.entries(e??{})){let e=Object.keys(r.entries),i={fields:e};n!==e.join(`_`)&&(i.name=n),t.push(i)}return t}function serializeScalar(e,t,n,r){let i=e[`~`].state,a=i.type===`enum`?{type:`enum`,enum:serializeEnum(e,i,t,n,r)}:i.type===`decimal`?{type:`decimal`,precision:i.decimal.precision,scale:i.decimal.scale}:{type:i.type},o=e[`~`].nativeType;o!==void 0&&(a.type===`point`?refusePointState(n,`native`,r):a.type===`decimal`?addIssue(r,pointer(n,`native`),`J009`,`A fixed decimal cannot carry a native-type override`):A(o)?v(o.db,o.type)?a.native={db:o.db,type:o.type}:addIssue(r,pointer(n,`native`,`type`),`J011`,h(o.db)):a.nativeByDialect=nativeTypeMapDocument(o)),i.array&&(a.type===`point`?refusePointState(n,`array`,r):a.array=!0),i.nullable&&(a.nullable=!0),i.isId&&(a.type===`point`?refusePointState(n,`id`,r):a.id=!0),i.isUnique&&!i.isId&&(a.type===`point`?refusePointState(n,`unique`,r):a.unique=!0),i.withTimezone===!1&&builderMethod(e,`withoutTimezone`)!==void 0&&(a.withoutTimezone=!0),i.dimension!==void 0&&(a.type===`point`?refusePointState(n,`dimension`,r):a.dimension=i.dimension),i.columnName!==void 0&&(a.column=i.columnName),i.autoGenerate!==void 0&&(a.type===`point`?refusePointState(n,`generate`,r):writeGenerate(a,i.autoGenerate,i.isId||_(i.default))),i.schema!==void 0&&addIssue(r,n,`J009`,"This field carries a custom `.schema()` validator — arbitrary code the document cannot hold. Re-attach it with `attachFieldSchemas`");let s=serializeDefault(i,n,r);return s!==void 0&&(a.default=s),a}function nativeTypeMapDocument(e){let t={};return e.pg!==void 0&&(t.pg={db:`pg`,type:e.pg.type}),e.mysql!==void 0&&(t.mysql={db:`mysql`,type:e.mysql.type}),e.sqlite!==void 0&&(t.sqlite={db:`sqlite`,type:e.sqlite.type}),t}function refusePointState(e,t,n){addIssue(n,pointer(e,t),`J009`,`A GeoPoint cannot carry a '${t}' declaration`)}function serializeEnum(e,t,n,r,i){let a=readEnumValues(e),o=t.enumName;if(o===void 0)return a;let s=n.refs.get(o);if(s!==void 0)return sameValues(b(n.definitions,s)?.values,a)||addIssue(i,r,`J009`,`Enum type '${o}' is declared with two different value sets; one database enum type holds one set`),s;let c=claimRef(o,n);return n.refs.set(o,c),m(n.definitions,c,{values:a,name:o}),c}function claimRef(e,t){let taken=e=>b(t.definitions,e)!==void 0;if(d(e)&&!taken(e))return e;let n=t.refs.size+1;for(;taken(`enum_${n}`);)n+=1;return`enum_${n}`}function sameValues(e,t){return e!==void 0&&e.length===t.length&&e.every((e,n)=>e===t[n])}function readEnumValues(e){return[...Reflect.get(e,`enumValues`)]}function serializeDefault(e,t,r){if(!e.hasDefault)return;let i=e.default;if(i!==void 0)return i===null?e.nullable?void 0:null:n(i)?serializeFunctionDefault(e,t,r):encodeDefault(i,pointer(t,`default`),r)}function serializeFunctionDefault(e,t,n){e.autoGenerate!==void 0&&_(e.default)||addIssue(n,pointer(t,`default`),`J009`,"This field carries a function default, which the document cannot hold. Use one of the nine `generate` kinds, a literal default, or a database default through `native`")}function serializeRelation(e,t,n,r){let i=e[`~`].state,a=i.cardinality===`one`?`toOne`:`toMany`,o=k(i)?withVariantTargetFacts(a,i,t,n,r):withModelTargetFacts({type:a,target:resolveTargetKey(i.target.getter,t,n,r)},i);return i.name!==void 0&&(o.name=i.name),o}function withModelTargetFacts(e,t){let n=t.foreignKey;n!==void 0&&(e.fields=[...n.fields],e.references=[...n.references],n.onDelete!==void 0&&(e.onDelete=n.onDelete),n.onUpdate!==void 0&&(e.onUpdate=n.onUpdate));let r=t.junction;if(r!==void 0){let t={};r.table!==void 0&&(t.table=r.table),r.source!==void 0&&(t.source=r.source),r.target!==void 0&&(t.target=r.target);let n=canonicalJunctionActions(r.onDelete),i=canonicalJunctionActions(r.onUpdate);e.junction={...t,...typeof n==`string`?{onDelete:n}:n&&{onDeleteSides:n},...typeof i==`string`?{onUpdate:i}:i&&{onUpdateSides:i}}}return e}function canonicalJunctionActions(e){if(e!==void 0)return e.source===e.target?e.source:{...e}}function withVariantTargetFacts(e,t,n,r,i){let a={},o={},s={},c=!1;for(let[e,l]of Object.entries(t.target.entries)){let t=l;a[e]=resolveTargetKey(t.getter,n,pointer(r,`variants`,e),i),o[e]=t.storedValue,t.storedValue!==e&&(c=!0);let u=readVariantJunction(t);u!==void 0&&(s[e]=u)}let l={type:e,variants:a};return c&&(l.values=o),Object.keys(s).length>0&&(l.through=s),t.optional===!0&&(l.optional=!0),l}function readVariantJunction(e){let t=Reflect.get(e,`junction`);if(t!==void 0)return{table:t.table,source:t.source,target:t.target}}function resolveTargetKey(e,t,n,r){let i=readTarget(e,n);for(let[e,n]of Object.entries(t))if(n===i)return e;return addIssue(r,n,`J006`,`This relation targets a model that is not a member of the schema record being serialized`),``}function readTarget(e,t){try{return e()}catch(e){let n=[];throw addIssue(n,t,`J006`,`This relation's target getter threw; the schema cannot be serialized`),refuseDocument(n,i(e))}}function writeGenerate(e,t,n){let r=t.implicit===!0,i=t.generate??n;if(r&&t.prefix===void 0&&i)return;let a={kind:t.kind};[`uuid`,`uuidv7`,`ulid`,`ksuid`,`nanoid`,`cuid`].includes(t.kind)&&!i&&(a.generate=!1),t.prefix!==void 0&&(a.prefix=t.prefix),t.length!==void 0&&(a.length=t.length),r&&(a.implicit=!0),e.generate=a}function parseSchema(e,t){let n=readValidateOption(t),r=interpret(readDocument(e));return n&&validateGraph(r),r}function attachFieldSchemas(e,t){return interpret(readDocument(serializeSchema(e)),t)}export{U as SCHEMA_DOCUMENT_VERSION,attachFieldSchemas,parseSchema,serializeSchema};
|
|
1
|
+
import{n as e}from"../chunk-BuuaeEvq.mjs";import{c as t,i as n,r}from"../value-guards-CK9guf2Z.mjs";import{k as i}from"../base-D3m1S7Uc.mjs";import{t as a}from"../validation-BamBwne9.mjs";import{A as o,D as s,E as c,_ as l,h as u}from"../v-CYTUI0H5.mjs";import{Pt as d}from"../geo-point-codec-DyEHMdJg.mjs";import{b as f,g as p,h as m,i as h,r as g,s as _,t as v,x as y,y as b}from"../scalar-S8yMvdmx.mjs";import{t as x}from"../hydration-DsyHNSDS.mjs";import{a as S}from"../validator-DgffZq9C.mjs";import{a as C,n as w}from"../native-types-asNCr26n.mjs";import{_ as T,a as E,c as D,d as O,f as ee,g as te,h as ne,i as re,l as ie,m as ae,n as oe,o as se,p as ce,r as k,s as A,t as j}from"../to-many-C1PuFIpf.mjs";import{t as M}from"../types-C5Oxz9yp.mjs";const N=/~/g,P=/\//g;function pointer(e,...t){let n=e;for(let e of t)n+=`/${e.replace(N,`~0`).replace(P,`~1`)}`;return n}function addIssue(e,t,n,r){e.push({path:t,message:`[${n}] ${r}`})}function refuseDocument(e,t){return new a({kind:`schema-builder`,builder:`schema-json`,path:``},e,t===void 0?void 0:{cause:t})}function throwIfRefused(e){if(e.length>0)throw refuseDocument(e)}function member(e,t,n,r){return guardedValue(e,t,n,r,`J004`)}function guardedValue(e,t,n,r,a){try{return Reflect.get(e,t)}catch(e){throw addIssue(r,pointer(n,t),a,`Reading this value threw`),refuseDocument(r,i(e))}}function inspectPlainRecord(e,t,n,r){try{return l(e)}catch(e){throw addIssue(n,t,r,`Inspecting this value's prototype threw`),refuseDocument(n,i(e))}}function inspectKeys(e,t,n,r){try{return u(e)}catch(e){throw addIssue(n,t,r,`Enumerating this value's keys threw`),refuseDocument(n,i(e))}}function renderValue(e){return typeof e==`bigint`?`${e}n`:typeof e==`object`?`[${typeof e}]`:String(e)}function refuseFromBuilder(e,t){let n=[];throw addIssue(n,e,`J010`,t.message),refuseDocument(n,t)}const F=`$bigint`,I=`$date`,L=`$bytes`,R=`$raw`,z=`$jsonNull`,B=new Set([F,I,L,R,z]),V=/^-?\d+$/,H=`'${F}' (a decimal integer string), '${I}' (an ISO timestamp), '${L}' (base64), '${R}' (the literal it wraps), '${z}' ('JsonNull' or 'DbNull')`;function reservedKey(e){let t=e.length===1?e[0]:void 0;return t?.startsWith(`$`)===!0?t:void 0}function readDefaultValue(e,t,n){return readValue(e,t,n,new Set)}function readValue(e,t,r,i){if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`){if(Number.isFinite(e))return e;addIssue(r,t,`J004`,`A default must be a finite number`);return}if(Array.isArray(e))return readArray(e,t,r,i);if(inspectPlainRecord(e,t,r,`J004`))return readRecord(e,t,r,i);addIssue(r,t,`J004`,n(e)?"A function default has no document spelling — use `generate`, a literal, or a database default through `native`":`A default must be a JSON value; a value outside JSON takes a tag — ${H}`)}function readArray(e,t,n,r){if(enterCycle(e,t,n,r,`J004`))return;let i=[];for(let a=0;a<e.length;a+=1){let o=pointer(t,String(a)),s=readValue(member(e,String(a),t,n),o,n,r);if(s===void 0)return;i.push(s)}return r.delete(e),i}function readRecord(e,t,n,r){if(enterCycle(e,t,n,r,`J004`))return;let i=inspectKeys(e,t,n,`J004`),a=reservedKey(i);if(a!==void 0&&!B.has(a)){addIssue(n,t,`J008`,`'${a}' is not a tag this format defines. The tags are ${H}`);return}let o=b();for(let a of i){let i=readValue(member(e,a,t,n),pointer(t,a),n,r);if(i===void 0)return;y(o,a,i)}return r.delete(e),o}function enterCycle(e,t,n,r,i){return r.has(e)?(addIssue(n,t,i,`This default contains a cycle; a document holds a finite value`),!0):(r.add(e),!1)}function decodeDefault(e,t){if(Array.isArray(e))return e.map((e,n)=>decodeDefault(e,pointer(t,String(n))));if(typeof e!=`object`||!e)return e;let n=reservedKey(Object.keys(e));if(n===void 0)return decodeBody(e,t);let r=e[n];if(n===R)return decodeRaw(r,t);if(n===F)return decodeBigInt(r,t);if(n===I)return decodeDate(r,t);if(n===z){if(r===`JsonNull`)return s;if(r===`DbNull`)return c;throw refuseTag(t,`'${z}' takes 'JsonNull' or 'DbNull'`)}return decodeBytes(r,t)}function decodeBody(e,t){let n=b();for(let r of Object.keys(e))y(n,r,decodeDefault(e[r]??null,pointer(t,r)));return n}function decodeRaw(e,t){return typeof e!=`object`||!e?e:Array.isArray(e)?decodeDefault(e,t):decodeBody(e,t)}function decodeBigInt(e,t){if(typeof e==`string`&&V.test(e))return BigInt(e);throw refuseTag(t,`'${F}' takes a decimal integer string`)}function decodeDate(e,t){if(typeof e==`string`){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t}throw refuseTag(t,`'${I}' takes a string naming an instant`)}function decodeBytes(e,t){if(typeof e==`string`)try{return decodeBase64(e)}catch{}throw refuseTag(t,`'${L}' takes a base64 string`)}function refuseTag(e,t){let n=[];return addIssue(n,e,`J008`,`${t}. The tags are ${H}`),refuseDocument(n)}function decodeBase64(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function encodeDefault(e,t,n){return encodeValue(e,t,n,new Set)}function encodeValue(e,n,i,a){let s=o(e);if(s===`JsonNull`||s===`DbNull`)return tagged(z,s);if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isFinite(e)?e:refuseValue(i,n,"A non-finite number has no JSON spelling; `JSON.stringify` would write it as `null`");if(typeof e==`bigint`)return tagged(F,e.toString(10));if(t(e))try{return tagged(L,encodeBase64(e))}catch{return refuseValue(i,n,`This byte string has a detached buffer and cannot be serialized`)}return r(e)?Number.isNaN(Date.prototype.getTime.call(e))?refuseValue(i,n,`An invalid Date names no instant`):tagged(I,Date.prototype.toISOString.call(e)):Array.isArray(e)?encodeArray(e,n,i,a):inspectPlainRecord(e,n,i,`J009`)?encodeRecord(e,n,i,a):refuseValue(i,n,`This default holds a value the document cannot state — a JSON value, a bigint, a Date or a byte string is what a default may be`)}function tagged(e,t){let n=b();return y(n,e,t),n}function encodeArray(e,t,n,r){if(enterCycle(e,t,n,r,`J009`))return;let i=[];for(let a=0;a<e.length;a+=1){let o=String(a),s=encodeValue(guardedValue(e,o,t,n,`J009`),pointer(t,o),n,r);if(s===void 0)return;i.push(s)}return r.delete(e),i}function encodeRecord(e,t,n,r){if(enterCycle(e,t,n,r,`J009`))return;let i=b();for(let a of inspectKeys(e,t,n,`J009`)){let o=encodeValue(guardedValue(e,a,t,n,`J009`),pointer(t,a),n,r);if(o===void 0)return;y(i,a,o)}if(r.delete(e),reservedKey(Object.keys(i))===void 0)return i;let a=b();return y(a,R,i),a}function refuseValue(e,t,n){addIssue(e,t,`J009`,n)}function encodeBase64(e){let t=``,n=Uint8Array.prototype.values.call(e);for(let e of n)t+=String.fromCharCode(e);return btoa(t)}const U=1;function isRelationField(e){return e.type===`toOne`||e.type===`toMany`}const W={string:v,int:se,number:re,boolean:ne,datetime:ce,date:ae,time:ee,bigint:T,json:E,blob:te,vector:oe,point:k},G=new Set([...Object.keys(W),`decimal`,`enum`]);function builderMethod(e,t){let n=Reflect.get(e,t);return typeof n==`function`?n:void 0}function interpret(e,t){let n={},r=pointer(``,`models`);refuseUnknownFieldSchemas(e,t);for(let[i,a]of Object.entries(e.models))n[i]=buildModel(i,a,e,n,pointer(r,i),t);return n}function refuseUnknownFieldSchemas(e,t){if(t===void 0)return;let n=[];for(let r of Object.keys(t)){let t=r.indexOf(`.`),i=e.models[r.slice(0,t)]?.fields[r.slice(t+1)];i!==void 0&&!isRelationField(i)||addIssue(n,``,`J006`,`Field schema '${r}' does not name a scalar field of this schema; spell it '<model>.<field>'`)}if(n.length>0)throw refuseDocument(n)}function buildModel(e,t,n,r,i,a){let o=pointer(i,`fields`),s={};for(let[i,c]of Object.entries(t.fields)){let t=pointer(o,i);if(isRelationField(c)){s[i]=buildRelation(c,r,t);continue}s[i]=buildScalar(c,n,t,a?.[`${e}.${i}`])}let c=call(i,()=>m(s));if(t.table!==void 0){let e=t.table;c=call(pointer(i,`table`),()=>c.map(e))}for(let[e,n]of(t.indexes??[]).entries()){let t=pointer(i,`indexes`,String(e)),r={...n.name===void 0?{}:{name:n.name},...n.unique===void 0?{}:{unique:n.unique},...n.type===void 0?{}:{type:n.type}};c=call(t,()=>Reflect.apply(c.index,c,[n.fields,r]))}for(let[e,n]of(t.ids??[]).entries())c=call(pointer(i,`ids`,String(e)),()=>c.id(n.fields,options(n.name)));for(let[e,n]of(t.uniques??[]).entries())c=call(pointer(i,`uniques`,String(e)),()=>c.unique(n.fields,options(n.name)));if(t.omit!==void 0){let e={};for(let n of t.omit)e[n]=!0;c=call(pointer(i,`omit`),()=>c.omit(e))}return c}function options(e){return e===void 0?{}:{name:e}}function buildScalar(e,t,n,r){let i=e.type,a=createScalar(e,t,n);if(e.array&&(a=modify(a,`array`,[],i,pointer(n,`array`))),e.nullable&&(a=modify(a,`nullable`,[],i,pointer(n,`nullable`))),e.id){let t=e.generate?.implicit===!0,r=e.generate?.generate===!1?[{generate:!1,prefix:t?e.generate.prefix:void 0}]:t&&e.generate?.prefix!==void 0?[e.generate.prefix]:[];a=modify(a,`id`,r,i,pointer(n,`id`))}e.unique&&(a=modify(a,`unique`,[],i,pointer(n,`unique`))),e.withoutTimezone&&(a=modify(a,`withoutTimezone`,[],i,pointer(n,`withoutTimezone`))),e.dimension!==void 0&&(a=modify(a,`dimension`,[e.dimension],i,pointer(n,`dimension`))),e.generate!==void 0&&e.generate.implicit!==!0&&(a=applyGenerate(a,e.generate,i,n));let o=e.default;return o!==void 0&&(a=applyDefault(a,e,o,n)),e.column!==void 0&&(a=modify(a,`map`,[e.column],i,pointer(n,`column`))),r!==void 0&&(a=modify(a,`schema`,[r],i,pointer(n,`schema`))),a}function createScalar(e,t,n){if(e.type===`decimal`){let{precision:t,scale:r}=e;return call(n,()=>ie({precision:t,scale:r}))}let r=e.native??e.nativeByDialect;if(e.type!==`enum`){let t=W[e.type];return call(n,()=>r===void 0?t():t(r))}let i=resolveEnum(e,t,n),a=call(n,()=>A(i.values,r));if(i.name===void 0)return a;let o=i.name;return modify(a,`name`,[o],`enum`,pointer(n,`enum`))}function resolveEnum(e,t,n){let r=e.enum;if(Array.isArray(r))return{values:r};let i=t.enums?.[r];if(i!==void 0)return i;let a=[];throw addIssue(a,pointer(n,`enum`),`J006`,`\`enum\` names '${r}', which \`enums\` does not declare`),refuseDocument(a)}function modify(e,t,n,r,i){let a=builderMethod(e,t);if(a===void 0){let e=[];throw addIssue(e,i,`J007`,`A '${r}' field has no '${t}' modifier`),refuseDocument(e)}return call(i,()=>a.apply(e,n))}function applyGenerate(e,t,n,r){let i=pointer(r,`generate`),a=![`now`,`updatedAt`,`increment`].includes(t.kind),o=t.generate===!1?{prefix:t.prefix,length:t.length}:{prefix:t.prefix,length:t.length,generate:!0},s=a?[o]:[t.prefix],c=modify(e,t.kind,s,n,i),l=c[`~`].state.autoGenerate;if(l?.prefix===t.prefix&&l?.length===t.length)return c;let u=[];throw addIssue(u,i,`J007`,`The '${t.kind}' generator does not take the 'prefix' or 'length' this node declares`),refuseDocument(u)}function applyDefault(e,t,n,r){let i=pointer(r,`default`),a=decodeDefault(n,i);if(t.type===`json`&&o(a)!==void 0)return modify(e,`default`,[a],t.type,i);let s=e[`~`].state.base[`~standard`].validate(a),c=t.type===`bigint`&&[a].flat().some(e=>typeof e==`string`);if(s.issues||c){let e=s.issues?s.issues.map(e=>e.message).join(`; `):`a bigint is written {"$bigint": "<integer>"}`,n=[];throw addIssue(n,i,`J008`,`A '${t.type}' default must be a value of the field's own domain: ${e}`),refuseDocument(n)}return e instanceof D?O(e,s.value):modify(e,`default`,[a],t.type,i)}function buildRelation(e,t,n){let r=e.target===void 0?buildVariantRelation(e,t,n):buildModelRelation(e,t,n);if(e.name===void 0)return r;let i=e.name;return call(pointer(n,`name`),()=>r.name(i))}function buildModelRelation(e,t,n){let r=e.target,getter=()=>t[r],i=e.type===`toOne`?p:j,a=call(n,()=>Reflect.apply(i,void 0,[getter]));if(e.fields!==void 0){let t=e.fields;a=call(pointer(n,`fields`),()=>a.fields(...t))}if(e.references!==void 0){let t=e.references;a=call(pointer(n,`references`),()=>a.references(...t))}for(let t of[`onDelete`,`onUpdate`]){let r=e[t];r!==void 0&&(a=call(pointer(n,t),()=>a[t](r)))}return e.junction!==void 0&&(a=applyJunction(a,e.junction,n)),a}function buildVariantRelation(e,t,n){let r={};for(let[n,i]of Object.entries(e.variants))r[n]=()=>t[i];let i=e.type===`toOne`?p:j,a=e.values===void 0?[r]:[r,{values:e.values}],o=call(n,()=>Reflect.apply(i,void 0,a));if(e.through!==void 0){let t=e.through;o=call(pointer(n,`through`),()=>o.through(t))}return e.optional&&(o=call(pointer(n,`optional`),()=>o.optional())),o}const le=[[`table`,`through`],[`source`,`source`],[`target`,`target`],[`onDelete`,`onDelete`],[`onUpdate`,`onUpdate`],[`onDeleteSides`,`onDelete`],[`onUpdateSides`,`onUpdate`]];function applyJunction(e,t,n){let r=e,i=pointer(n,`junction`);for(let[e,n]of le){let a=t[e];a!==void 0&&(r=call(pointer(i,e),()=>r[n](a)))}return r}function call(e,t){try{return t()}catch(t){return refuseFromBuilder(e,i(t))}}const K={cascade:!0,setNull:!0,restrict:!0,noAction:!0},q={cascade:!0,restrict:!0,noAction:!0},J={btree:!0,hash:!0,gin:!0,gist:!0,fulltext:!0,spatial:!0},Y={uuid:!0,uuidv7:!0,ulid:!0,ksuid:!0,nanoid:!0,cuid:!0,increment:!0,now:!0,updatedAt:!0},isReferentialAction=e=>typeof e==`string`&&Object.hasOwn(K,e),isJunctionAction=e=>typeof e==`string`&&Object.hasOwn(q,e),isIndexType=e=>typeof e==`string`&&Object.hasOwn(J,e),isGenerateKind=e=>typeof e==`string`&&Object.hasOwn(Y,e),isNativeDialect=e=>typeof e==`string`&&w.some(t=>t===e),isScalarTypeName=e=>typeof e==`string`&&G.has(e),ue=[`version`,`enums`,`models`],de=[`values`,`name`],fe=[`table`,`fields`,`indexes`,`ids`,`uniques`,`omit`],pe=[`fields`,`name`,`unique`,`type`,`where`],me=[`fields`,`name`],he=[`db`,`type`],ge=[`kind`,`prefix`,`length`,`implicit`,`generate`],X=[`table`,`source`,`target`,`onDelete`,`onUpdate`,`onDeleteSides`,`onUpdateSides`],_e=[`source`,`target`],ve=[`table`,`source`,`target`],Z=[`type`,`native`,`nativeByDialect`,`nullable`,`array`,`id`,`unique`,`column`,`default`,`generate`,`enum`,`dimension`,`precision`,`scale`,`withoutTimezone`],ye=[...new Set([...Z,...relationKeys({cardinality:`one`,variants:!1}),...relationKeys({cardinality:`many`,variants:!1}),...relationKeys({cardinality:`one`,variants:!0}),...relationKeys({cardinality:`many`,variants:!0})])];function relationKeys(e){let t=[`type`,`name`];return e.variants?(t.push(`variants`,`values`),t.push(e.cardinality===`one`?`optional`:`through`),t):(t.push(`target`),e.cardinality===`one`?(t.push(`fields`,`references`,`onDelete`,`onUpdate`),t):(t.push(`junction`),t))}function elements(e,t,n){let r=[];for(let i=0;i<e.length;i+=1)r.push(member(e,String(i),t,n));return r}function asRecord(e,t,n,r){if(inspectPlainRecord(e,t,n,`J004`))return e;addIssue(n,t,`J004`,`${r} must be a plain JSON object`)}function asString(e,t,n,r){if(typeof e==`string`)return e;addIssue(n,t,`J004`,`${r} must be a string`)}function asBoolean(e,t,n,r){if(typeof e==`boolean`)return e;addIssue(n,t,`J004`,`${r} must be a boolean`)}function asNumber(e,t,n,r){if(typeof e==`number`&&Number.isFinite(e))return e;addIssue(n,t,`J004`,`${r} must be a finite number`)}function asStringArray(e,t,n,r){if(!Array.isArray(e)){addIssue(n,t,`J004`,`${r} must be an array of strings`);return}let i=[],a=!0;for(let[o,s]of elements(e,t,n).entries()){let e=asString(s,pointer(t,String(o)),n,r);if(e===void 0){a=!1;continue}i.push(e)}return a?i:void 0}function refuseUnknownKeys(e,t,n,r,i=`this node`){for(let a of inspectKeys(e,n,r,`J004`)){if(!t.includes(a)){addIssue(r,pointer(n,a),`J003`,`Unknown key '${a}'; ${i} declares ${renderKeys(t)}`);continue}member(e,a,n,r)===void 0&&addIssue(r,pointer(n,a),`J004`,`'${a}' is \`undefined\`; a document omits an absent key rather than setting it to \`undefined\``)}}function refuseInvalidKey(e,t,n,r){return d(e)?!0:(addIssue(n,t,`J005`,`${r} '${e}' is not a valid schema identifier`),!1)}function renderKeys(e){return e.map(e=>`'${e}'`).join(`, `)}function readDocument(e){let t=[],n=intake(e,t);throwIfRefused(t);let r=asRecord(n,``,t,`A schema document`);if(r===void 0)throw refuseDocument(t);refuseUnknownKeys(r,ue,``,t);let i=member(r,`version`,``,t);if(i!==1)throw addIssue(t,pointer(``,`version`),`J002`,`Unsupported document version ${renderValue(i)}; this parser reads version 1`),refuseDocument(t);let a={version:1,models:readModels(r,t)},o=readEnums(r,t);return o!==void 0&&(a.enums=o),resolveReferences(a,t),throwIfRefused(t),a}function intake(e,t){if(typeof e!=`string`)return e;try{return JSON.parse(e)}catch(e){addIssue(t,``,`J001`,`The document is not valid JSON: ${String(e)}`);return}}function readEnums(e,t){let n=pointer(``,`enums`),r=member(e,`enums`,``,t);if(r===void 0)return;let i=asRecord(r,n,t,"`enums`");if(i===void 0)return;let a={};for(let e of inspectKeys(i,n,t,`J004`)){let r=pointer(n,e);if(!refuseInvalidKey(e,r,t,`Enum reference`))continue;let o=readEnumNode(member(i,e,n,t),r,t);o!==void 0&&(a[e]=o)}return a}function readEnumNode(e,t,n){let r=asRecord(e,t,n,`An enum definition`);if(r===void 0)return;refuseUnknownKeys(r,de,t,n);let i=asStringArray(member(r,`values`,t,n),pointer(t,`values`),n,"`values`");if(i===void 0)return;let a={values:i},o=member(r,`name`,t,n);if(o!==void 0){let e=asString(o,pointer(t,`name`),n,"`name`");e!==void 0&&(a.name=e)}return a}function readModels(e,t){let n=pointer(``,`models`),r={},i=asRecord(member(e,`models`,``,t),n,t,"`models`");if(i===void 0)return r;for(let e of inspectKeys(i,n,t,`J004`)){let a=pointer(n,e);if(!refuseInvalidKey(e,a,t,`Model key`))continue;let o=readModelNode(member(i,e,n,t),a,t);o!==void 0&&(r[e]=o)}return r}function readModelNode(e,t,n){let r=asRecord(e,t,n,`A model`);if(r===void 0)return;refuseUnknownKeys(r,fe,t,n);let i={fields:readFields(r,t,n)},a=member(r,`table`,t,n);if(a!==void 0){let e=asString(a,pointer(t,`table`),n,"`table`");e!==void 0&&(i.table=e)}let o=readIndexes(r,t,n);o!==void 0&&(i.indexes=o);let s=readCompoundKeys(r,`ids`,t,n);s!==void 0&&(i.ids=s);let c=readCompoundKeys(r,`uniques`,t,n);c!==void 0&&(i.uniques=c);let l=readOmit(r,t,n);return l!==void 0&&(i.omit=l),i}function readFields(e,t,n){let r=pointer(t,`fields`),i={},a=asRecord(member(e,`fields`,t,n),r,n,"`fields`");if(a===void 0)return i;for(let e of inspectKeys(a,r,n,`J004`)){let t=pointer(r,e);if(!refuseInvalidKey(e,t,n,`Field key`))continue;let o=readFieldNode(member(a,e,r,n),t,n);o!==void 0&&(i[e]=o)}return i}function readIndexes(e,t,n){let r=pointer(t,`indexes`),i=member(e,`indexes`,t,n);if(i===void 0)return;if(!Array.isArray(i)){addIssue(n,r,`J004`,"`indexes` must be an array");return}let a=[];for(let[e,t]of elements(i,r,n).entries()){let i=readIndexNode(t,pointer(r,String(e)),n);i!==void 0&&a.push(i)}return a}function readIndexNode(e,t,n){let r=asRecord(e,t,n,`An index`);if(r===void 0)return;inspectKeys(r,t,n,`J004`).includes(`where`)&&addIssue(n,pointer(t,`where`),`J009`,"`where` is refused in v1: it is raw SQL interpolated unescaped into DDL, and a machine-written document must not carry an execution channel. It returns when a structured predicate form exists"),refuseUnknownKeys(r,pe,t,n);let i=asStringArray(member(r,`fields`,t,n),pointer(t,`fields`),n,"`fields`");if(i===void 0)return;let a={fields:i},o=member(r,`name`,t,n);if(o!==void 0){let e=asString(o,pointer(t,`name`),n,"`name`");e!==void 0&&(a.name=e)}let s=member(r,`unique`,t,n);if(s!==void 0){let e=asBoolean(s,pointer(t,`unique`),n,"`unique`");e!==void 0&&(a.unique=e)}let c=member(r,`type`,t,n);return c!==void 0&&(isIndexType(c)?a.type=c:addIssue(n,pointer(t,`type`),`J004`,`\`type\` must be one of ${renderKeys(Object.keys(J))}`)),a}function readCompoundKeys(e,t,n,r){let i=pointer(n,t),a=member(e,t,n,r);if(a===void 0)return;if(!Array.isArray(a)){addIssue(r,i,`J004`,`\`${t}\` must be an array`);return}let o=[];for(let[e,t]of elements(a,i,r).entries()){let n=readCompoundKeyNode(t,pointer(i,String(e)),r);n!==void 0&&o.push(n)}return o}function readCompoundKeyNode(e,t,n){let r=asRecord(e,t,n,`A compound key`);if(r===void 0)return;refuseUnknownKeys(r,me,t,n);let i=asStringArray(member(r,`fields`,t,n),pointer(t,`fields`),n,"`fields`");if(i===void 0)return;let a={fields:i},o=member(r,`name`,t,n);if(o!==void 0){let e=asString(o,pointer(t,`name`),n,"`name`");e!==void 0&&(a.name=e)}return a}function readOmit(e,t,n){let r=member(e,`omit`,t,n);if(r!==void 0)return asStringArray(r,pointer(t,`omit`),n,"`omit`")}function readFieldNode(e,t,n){let r=asRecord(e,t,n,`A field`);if(r===void 0)return;let i=member(r,`type`,t,n);if(i===`toOne`||i===`toMany`)return readRelationField(r,i,t,n);if(isScalarTypeName(i))return readScalarField(r,i,t,n);addIssue(n,pointer(t,`type`),`J004`,`\`type\` must be 'toOne', 'toMany', or one of ${renderKeys([...G])}`),refuseUnknownKeys(r,ye,t,n,`a field node`)}function readScalarField(e,t,n,r){refuseUnknownKeys(e,Z,n,r);let i=readScalarArm(e,t,n,r);if(i===void 0)return;readFlag(e,`nullable`,n,r,i),readFlag(e,`array`,n,r,i),readFlag(e,`id`,n,r,i),readFlag(e,`unique`,n,r,i),readFlag(e,`withoutTimezone`,n,r,i);let a=member(e,`column`,n,r);if(a!==void 0){let e=asString(a,pointer(n,`column`),r,"`column`");e!==void 0&&(i.column=e)}let o=member(e,`dimension`,n,r);if(o!==void 0)if(t===`point`)refusePointModifier(`dimension`,n,r);else{let e=asNumber(o,pointer(n,`dimension`),r,"`dimension`");e!==void 0&&(i.dimension=e)}t!==`decimal`&&(refuseDecimalDomainBound(e,`precision`,n,r),refuseDecimalDomainBound(e,`scale`,n,r));let s=member(e,`native`,n,r);if(s!==void 0)if(i.type===`point`)refusePointModifier(`native`,n,r);else if(i.type===`decimal`)addIssue(r,pointer(n,`native`),`J003`,"`native` does not belong to a decimal field; its physical type is derived from `precision` and `scale`");else{let e=readNativeNode(s,pointer(n,`native`),r);e!==void 0&&(i.native=e)}let c=member(e,`nativeByDialect`,n,r);if(c!==void 0)if(i.type===`point`)refusePointModifier(`nativeByDialect`,n,r);else if(i.type===`decimal`||s!==void 0)addIssue(r,pointer(n,`nativeByDialect`),`J003`,i.type===`decimal`?"`nativeByDialect` does not belong to a decimal field; its physical type is derived from `precision` and `scale`":"`native` and `nativeByDialect` are two spellings of one declaration; a field carries at most one");else{let e=readNativeByDialectNode(c,pointer(n,`nativeByDialect`),r);e!==void 0&&(i.nativeByDialect=e)}let l=member(e,`generate`,n,r);if(l!==void 0)if(t===`point`)refusePointModifier(`generate`,n,r);else{let e=readGenerateNode(l,pointer(n,`generate`),r,i.id===!0);e!==void 0&&(i.generate=e)}let u=member(e,`default`,n,r);if(u!==void 0){let e=readDefaultValue(u,pointer(n,`default`),r);e!==void 0&&(i.default=e)}return i}function readRequiredDomainBound(e,t,n,r){let i=member(e,t,n,r);if(i===void 0){addIssue(r,pointer(n,t),`J004`,`A decimal field must declare \`${t}\``);return}return asNumber(i,pointer(n,t),r,`\`${t}\``)}function refuseDecimalDomainBound(e,t,n,r){member(e,t,n,r)!==void 0&&addIssue(r,pointer(n,t),`J003`,`\`${t}\` belongs only to a field of type 'decimal'`)}function readScalarArm(e,t,n,r){let i=member(e,`enum`,n,r),a=pointer(n,`enum`);if(t!==`enum`){if(i!==void 0&&addIssue(r,a,`J003`,"`enum` belongs to a field of type 'enum'"),t===`decimal`){let i=readRequiredDomainBound(e,`precision`,n,r),a=readRequiredDomainBound(e,`scale`,n,r);return i===void 0||a===void 0?void 0:{type:t,precision:i,scale:a}}return{type:t}}if(i===void 0){addIssue(r,a,`J004`,"An enum field declares `enum` as an `enums` reference or an inline array of values");return}if(typeof i==`string`)return{type:t,enum:i};let o=asStringArray(i,a,r,"`enum`");if(o!==void 0)return{type:t,enum:o}}function readFlag(e,t,n,r,i){let a=member(e,t,n,r);if(a===void 0)return;if(i.type===`point`&&t!==`nullable`){refusePointModifier(t,n,r);return}let o=asBoolean(a,pointer(n,t),r,`\`${t}\``);if(o!==void 0){if(t===`nullable`){i.nullable=o;return}i.type!==`point`&&(i[t]=o)}}function refusePointModifier(e,t,n){addIssue(n,pointer(t,e),`J007`,`A 'point' field has no '${e}' modifier`)}function readNativeNode(e,t,n){let r=asRecord(e,t,n,"`native`");if(r===void 0)return;refuseUnknownKeys(r,he,t,n);let i=member(r,`db`,t,n),a=asString(member(r,`type`,t,n),pointer(t,`type`),n,"`native.type`");if(!isNativeDialect(i)){addIssue(n,pointer(t,`db`),`J004`,`\`native.db\` must be one of ${renderKeys(w)}`);return}if(a!==void 0){if(!g(i,a)){addIssue(n,pointer(t,`type`),`J011`,h(i));return}return{db:i,type:a}}}function readNativeByDialectNode(e,t,n){let r=asRecord(e,t,n,"`nativeByDialect`");if(r===void 0)return;refuseUnknownKeys(r,w,t,n);let i={},a=readDialectEntry(r,`pg`,t,n);a!==void 0&&(i.pg=a);let o=readDialectEntry(r,`mysql`,t,n);o!==void 0&&(i.mysql=o);let s=readDialectEntry(r,`sqlite`,t,n);return s!==void 0&&(i.sqlite=s),i}function readDialectEntry(e,t,n,r){let i=member(e,t,n,r);if(i===void 0)return;let a=pointer(n,t),o=readNativeNode(i,a,r);if(o!==void 0){if(o.db!==t){addIssue(r,pointer(a,`db`),`J004`,`The '${t}' entry's \`db\` must be '${t}'`);return}return{db:t,type:o.type}}}function readGenerateNode(e,t,n,r){let i=asRecord(e,t,n,"`generate`");if(i===void 0)return;refuseUnknownKeys(i,ge,t,n);let a=member(i,`kind`,t,n);if(!isGenerateKind(a)){addIssue(n,pointer(t,`kind`),`J004`,`\`generate.kind\` must be one of ${renderKeys(Object.keys(Y))}`);return}let o={kind:a},s=member(i,`generate`,t,n);if(s!==void 0){let e=asBoolean(s,pointer(t,`generate`),n,"`generate`");a===`now`||a===`updatedAt`||a===`increment`?addIssue(n,pointer(t,`generate`),`J004`,`An explicit generation choice belongs only to string identifier formats`):e!==void 0&&(o.generate=e)}let c=member(i,`prefix`,t,n);if(c!==void 0){let e=asString(c,pointer(t,`prefix`),n,"`prefix`");e!==void 0&&(o.prefix=e)}let l=member(i,`length`,t,n);if(l!==void 0){let e=asNumber(l,pointer(t,`length`),n,"`length`");e!==void 0&&(o.length=e)}let u=member(i,`implicit`,t,n);return u!==void 0&&asBoolean(u,pointer(t,`implicit`),n,"`implicit`")===!0&&(a===`ulid`?r?o.implicit=!0:addIssue(n,pointer(t,`implicit`),`J004`,"`generate.implicit` describes the ULID `.id()` installs, so it belongs only beside `id: true`"):addIssue(n,pointer(t,`implicit`),`J004`,'`generate.implicit` describes the ULID `.id()` installs, so it belongs only to `kind: "ulid"`')),o}function readRelationField(e,t,n,r){let i=member(e,`target`,n,r),a=member(e,`variants`,n,r);if(i===void 0==(a===void 0)){addIssue(r,n,`J004`,"A relation names exactly one target domain: `target` for one model, or `variants` for named variants");return}let o=t===`toOne`?`one`:`many`;refuseUnknownKeys(e,relationKeys({cardinality:o,variants:a!==void 0}),n,r);let s=readName(e,n,r);if(i===void 0)return readVariantTargetArm(e,{type:t,variants:a},s,o,n,r);let c=asString(i,pointer(n,`target`),r,"`target`");if(c!==void 0)return readModelTargetArm(e,{type:t,target:c},s,o,n,r)}function readName(e,t,n){let r=member(e,`name`,t,n);if(r!==void 0)return asString(r,pointer(t,`name`),n,"`name`")}function readModelTargetArm(e,t,n,r,i,a){if(n!==void 0&&(t.name=n),r===`many`){let n=member(e,`junction`,i,a);if(n!==void 0){let e=readJunctionNode(n,pointer(i,`junction`),a);e!==void 0&&(t.junction=e)}return t}for(let n of[`fields`,`references`]){let r=member(e,n,i,a);if(r===void 0)continue;let o=asStringArray(r,pointer(i,n),a,`\`${n}\``);o!==void 0&&(t[n]=o)}for(let n of[`onDelete`,`onUpdate`]){let r=member(e,n,i,a);if(r!==void 0){if(isReferentialAction(r)){t[n]=r;continue}addIssue(a,pointer(i,n),`J004`,`\`${n}\` must be one of ${renderKeys(Object.keys(K))}`)}}return t}function readVariantTargetArm(e,t,n,r,i,a){let o=readVariantMap(t.variants,pointer(i,`variants`),a);if(o===void 0)return;let s={type:t.type,variants:o};n!==void 0&&(s.name=n);let c=member(e,`values`,i,a);if(c!==void 0){let e=readStringMap(c,pointer(i,`values`),a,"`values`");e!==void 0&&(s.values=e)}if(r===`one`){let t=member(e,`optional`,i,a);if(t!==void 0){let e=asBoolean(t,pointer(i,`optional`),a,"`optional`");e!==void 0&&(s.optional=e)}return s}let l=member(e,`through`,i,a);if(l!==void 0){let e=readThroughMap(l,pointer(i,`through`),a);e!==void 0&&(s.through=e)}return s}function readVariantMap(e,t,n){let r=asRecord(e,t,n,"`variants`");if(r===void 0)return;let i={};for(let e of inspectKeys(r,t,n,`J004`)){let a=pointer(t,e);if(!refuseInvalidKey(e,a,n,`Variant key`))continue;let o=asString(member(r,e,t,n),a,n,`A variant target`);o!==void 0&&(i[e]=o)}return i}function readStringMap(e,t,n,r){let i=asRecord(e,t,n,r);if(i===void 0)return;let a={};for(let e of inspectKeys(i,t,n,`J004`)){let o=pointer(t,e);if(!refuseInvalidKey(e,o,n,`Variant key`))continue;let s=asString(member(i,e,t,n),o,n,r);s!==void 0&&(a[e]=s)}return a}function readThroughMap(e,t,n){let r=asRecord(e,t,n,"`through`");if(r===void 0)return;let i={};for(let e of inspectKeys(r,t,n,`J004`)){let a=pointer(t,e);if(!refuseInvalidKey(e,a,n,`Variant key`))continue;let o=readVariantJunctionNode(member(r,e,t,n),a,n);o!==void 0&&(i[e]=o)}return i}function readVariantJunctionNode(e,t,n){let r=asRecord(e,t,n,`A member junction`);if(r===void 0)return;refuseUnknownKeys(r,ve,t,n);let i=asString(member(r,`table`,t,n),pointer(t,`table`),n,"`table`"),a=asString(member(r,`source`,t,n),pointer(t,`source`),n,"`source`"),o=asString(member(r,`target`,t,n),pointer(t,`target`),n,"`target`");if(!(i===void 0||a===void 0||o===void 0))return{table:i,source:a,target:o}}function readJunctionNode(e,t,n){let r=asRecord(e,t,n,"`junction`");if(r===void 0)return;if(refuseUnknownKeys(r,X,t,n),inspectKeys(r,t,n,`J004`).length===0){addIssue(n,t,`J004`,"`junction` declares at least one of 'table', 'source', 'target', 'onDelete', 'onUpdate', 'onDeleteSides', 'onUpdateSides'; omit it to keep the derived defaults");return}let i={};for(let e of[`table`,`source`,`target`]){let a=member(r,e,t,n);if(a===void 0)continue;let o=asString(a,pointer(t,e),n,`\`${e}\``);o!==void 0&&(i[e]=o)}let a=readJunctionActionSpelling(r,`onDelete`,t,n),o=readJunctionActionSpelling(r,`onUpdate`,t,n);return{...i,...typeof a==`string`?{onDelete:a}:a&&{onDeleteSides:a},...typeof o==`string`?{onUpdate:o}:o&&{onUpdateSides:o}}}function readJunctionActionSpelling(e,t,n,r){let i=member(e,t,n,r),a=`${t}Sides`,o=member(e,a,n,r);if(i!==void 0&&o!==void 0){addIssue(r,pointer(n,a),`J004`,`\`${t}\` and \`${a}\` are exclusive: one action for both foreign keys, or one per side`);return}if(o!==void 0)return readJunctionSides(o,pointer(n,a),r,a);if(i!==void 0)return readJunctionAction(i,pointer(n,t),r,t)}function readJunctionSides(e,t,n,r){let i=asRecord(e,t,n,`\`${r}\``);if(i===void 0)return;refuseUnknownKeys(i,_e,t,n);let readSide=e=>{let a=member(i,e,t,n);if(a!==void 0)return readJunctionAction(a,pointer(t,e),n,`${r}.${e}`);addIssue(n,pointer(t,e),`J004`,`\`${r}\` states both 'source' and 'target'; '${e}' is missing`)},a=readSide(`source`),o=readSide(`target`);if(!(a===void 0||o===void 0))return{source:a,target:o}}function readJunctionAction(e,t,n,r){if(isJunctionAction(e))return e;addIssue(n,t,`J004`,`A junction \`${r}\` must be one of ${renderKeys(Object.keys(q))}; 'setNull' cannot null a membership-key member`)}function resolveReferences(e,t){let n=pointer(``,`models`);for(let[r,i]of Object.entries(e.models)){let a=pointer(n,r),o=pointer(a,`fields`);for(let[n,r]of Object.entries(i.fields))resolveTargetReferences(e,r,pointer(o,n),t);resolveOmitReferences(i,a,t)}}function resolveTargetReferences(e,t,n,r){if(isRelationField(t)){t.target!==void 0&&refuseUnknownModel(e,t.target,pointer(n,`target`),r);for(let[i,a]of Object.entries(t.variants??{}))refuseUnknownModel(e,a,pointer(n,`variants`,i),r)}}function refuseUnknownModel(e,t,n,r){Object.hasOwn(e.models,t)||addIssue(r,n,`J006`,`Model '${t}' is not declared in \`models\``)}function resolveOmitReferences(e,t,n){for(let[r,i]of(e.omit??[]).entries()){let a=e.fields[i];a!==void 0&&!isRelationField(a)||addIssue(n,pointer(t,`omit`,String(r)),`J006`,`\`omit\` names '${i}', which is not a scalar field of this model`)}}const Q=[`validate`],be=Q.map(e=>`'${e}'`).join(`, `),$=pointer(``,`options`);function readValidateOption(e){if(e===void 0)return!1;let t=[];if(!inspectPlainRecord(e,$,t,`J004`))throw addIssue(t,$,`J004`,"`options` must be a plain object"),refuseDocument(t);for(let n of inspectKeys(e,$,t,`J004`))Q.includes(n)||addIssue(t,pointer($,n),`J003`,`Unknown option '${n}'; this call declares ${be}`);let n=member(e,`validate`,$,t);return n!==void 0&&typeof n!=`boolean`&&addIssue(t,pointer($,`validate`),`J004`,"`validate` must be a boolean"),throwIfRefused(t),n===!0}function validateGraph(e){x(e),S(e)}function serializeSchema(e,t){readValidateOption(t)&&validateGraph(e);let n=[],r={refs:new Map,definitions:b()},i=b(),a=pointer(``,`models`);for(let[t,o]of Object.entries(e))y(i,t,serializeModel(o,e,r,pointer(a,t),n));throwIfRefused(n);let o={version:1,models:i};return Object.keys(r.definitions).length>0&&(o.enums=r.definitions),o}function serializeModel(e,t,n,r,i){let a=e[`~`].state,o=a.relations,s=a.scalars,c=b(),l=pointer(r,`fields`);for(let e of Object.keys(a.shape)){let r=f(o,e),a=f(s,e),u=pointer(l,e);if(r!==void 0){y(c,e,serializeRelation(r,t,u,i));continue}a!==void 0&&y(c,e,serializeScalar(a,n,u,i))}let u={fields:c};a.tableName!==void 0&&(u.table=a.tableName);let d=serializeIndexes(a.indexes,r,i);d.length>0&&(u.indexes=d);let p=serializeCompound(a.compoundId);p.length>0&&(u.ids=p);let m=serializeCompound(a.compoundUniques);return m.length>0&&(u.uniques=m),a.omit!==void 0&&(u.omit=Object.keys(a.omit).sort()),u}function serializeIndexes(e,t,n){let r=[];for(let[i,a]of e.entries()){let e=pointer(t,`indexes`,String(i));if(a.options.where!==void 0){addIssue(n,e,`J009`,"This index carries a `where` predicate — raw SQL the v1 document refuses to carry. Drop the partial index or keep this schema in code");continue}let o={fields:[...a.fields]};a.options.name!==void 0&&(o.name=a.options.name),a.options.unique!==void 0&&(o.unique=a.options.unique),a.options.type!==void 0&&(o.type=a.options.type),r.push(o)}return r}function serializeCompound(e){let t=[];for(let[n,r]of Object.entries(e??{})){let e=Object.keys(r.entries),i={fields:e};n!==e.join(`_`)&&(i.name=n),t.push(i)}return t}function serializeScalar(e,t,n,r){let i=e[`~`].state,a=i.type===`enum`?{type:`enum`,enum:serializeEnum(e,i,t,n,r)}:i.type===`decimal`?{type:`decimal`,precision:i.decimal.precision,scale:i.decimal.scale}:{type:i.type},o=e[`~`].nativeType;o!==void 0&&(a.type===`point`?refusePointState(n,`native`,r):a.type===`decimal`?addIssue(r,pointer(n,`native`),`J009`,`A fixed decimal cannot carry a native-type override`):C(o)?g(o.db,o.type)?a.native={db:o.db,type:o.type}:addIssue(r,pointer(n,`native`,`type`),`J011`,h(o.db)):a.nativeByDialect=nativeTypeMapDocument(o)),i.array&&(a.type===`point`?refusePointState(n,`array`,r):a.array=!0),i.nullable&&(a.nullable=!0),i.isId&&(a.type===`point`?refusePointState(n,`id`,r):a.id=!0),i.isUnique&&!i.isId&&(a.type===`point`?refusePointState(n,`unique`,r):a.unique=!0),i.withTimezone===!1&&builderMethod(e,`withoutTimezone`)!==void 0&&(a.withoutTimezone=!0),i.dimension!==void 0&&(a.type===`point`?refusePointState(n,`dimension`,r):a.dimension=i.dimension),i.columnName!==void 0&&(a.column=i.columnName),i.autoGenerate!==void 0&&(a.type===`point`?refusePointState(n,`generate`,r):writeGenerate(a,i.autoGenerate,i.isId||_(i.default))),i.schema!==void 0&&addIssue(r,n,`J009`,"This field carries a custom `.schema()` validator — arbitrary code the document cannot hold. Re-attach it with `attachFieldSchemas`");let s=serializeDefault(i,n,r);return s!==void 0&&(a.default=s),a}function nativeTypeMapDocument(e){let t={};return e.pg!==void 0&&(t.pg={db:`pg`,type:e.pg.type}),e.mysql!==void 0&&(t.mysql={db:`mysql`,type:e.mysql.type}),e.sqlite!==void 0&&(t.sqlite={db:`sqlite`,type:e.sqlite.type}),t}function refusePointState(e,t,n){addIssue(n,pointer(e,t),`J009`,`A GeoPoint cannot carry a '${t}' declaration`)}function serializeEnum(e,t,n,r,i){let a=readEnumValues(e),o=t.enumName;if(o===void 0)return a;let s=n.refs.get(o);if(s!==void 0)return sameValues(f(n.definitions,s)?.values,a)||addIssue(i,r,`J009`,`Enum type '${o}' is declared with two different value sets; one database enum type holds one set`),s;let c=claimRef(o,n);return n.refs.set(o,c),y(n.definitions,c,{values:a,name:o}),c}function claimRef(e,t){let taken=e=>f(t.definitions,e)!==void 0;if(d(e)&&!taken(e))return e;let n=t.refs.size+1;for(;taken(`enum_${n}`);)n+=1;return`enum_${n}`}function sameValues(e,t){return e!==void 0&&e.length===t.length&&e.every((e,n)=>e===t[n])}function readEnumValues(e){return[...Reflect.get(e,`enumValues`)]}function serializeDefault(e,t,r){if(!e.hasDefault)return;let i=e.default;if(i!==void 0)return i===null?e.nullable?void 0:null:n(i)?serializeFunctionDefault(e,t,r):encodeDefault(i,pointer(t,`default`),r)}function serializeFunctionDefault(e,t,n){e.autoGenerate!==void 0&&_(e.default)||addIssue(n,pointer(t,`default`),`J009`,"This field carries a function default, which the document cannot hold. Use one of the nine `generate` kinds, a literal default, or a database default through `native`")}function serializeRelation(e,t,n,r){let i=e[`~`].state,a=i.cardinality===`one`?`toOne`:`toMany`,o=M(i)?withVariantTargetFacts(a,i,t,n,r):withModelTargetFacts({type:a,target:resolveTargetKey(i.target.getter,t,n,r)},i);return i.name!==void 0&&(o.name=i.name),o}function withModelTargetFacts(e,t){let n=t.foreignKey;n!==void 0&&(e.fields=[...n.fields],e.references=[...n.references],n.onDelete!==void 0&&(e.onDelete=n.onDelete),n.onUpdate!==void 0&&(e.onUpdate=n.onUpdate));let r=t.junction;if(r!==void 0){let t={};r.table!==void 0&&(t.table=r.table),r.source!==void 0&&(t.source=r.source),r.target!==void 0&&(t.target=r.target);let n=canonicalJunctionActions(r.onDelete),i=canonicalJunctionActions(r.onUpdate);e.junction={...t,...typeof n==`string`?{onDelete:n}:n&&{onDeleteSides:n},...typeof i==`string`?{onUpdate:i}:i&&{onUpdateSides:i}}}return e}function canonicalJunctionActions(e){if(e!==void 0)return e.source===e.target?e.source:{...e}}function withVariantTargetFacts(e,t,n,r,i){let a={},o={},s={},c=!1;for(let[e,l]of Object.entries(t.target.entries)){let t=l;a[e]=resolveTargetKey(t.getter,n,pointer(r,`variants`,e),i),o[e]=t.storedValue,t.storedValue!==e&&(c=!0);let u=readVariantJunction(t);u!==void 0&&(s[e]=u)}let l={type:e,variants:a};return c&&(l.values=o),Object.keys(s).length>0&&(l.through=s),t.optional===!0&&(l.optional=!0),l}function readVariantJunction(e){let t=Reflect.get(e,`junction`);if(t!==void 0)return{table:t.table,source:t.source,target:t.target}}function resolveTargetKey(e,t,n,r){let i=readTarget(e,n);for(let[e,n]of Object.entries(t))if(n===i)return e;return addIssue(r,n,`J006`,`This relation targets a model that is not a member of the schema record being serialized`),``}function readTarget(e,t){try{return e()}catch(e){let n=[];throw addIssue(n,t,`J006`,`This relation's target getter threw; the schema cannot be serialized`),refuseDocument(n,i(e))}}function writeGenerate(e,t,n){let r=t.implicit===!0,i=t.generate??n;if(r&&t.prefix===void 0&&i)return;let a={kind:t.kind};[`uuid`,`uuidv7`,`ulid`,`ksuid`,`nanoid`,`cuid`].includes(t.kind)&&!i&&(a.generate=!1),t.prefix!==void 0&&(a.prefix=t.prefix),t.length!==void 0&&(a.length=t.length),r&&(a.implicit=!0),e.generate=a}function parseSchema(e,t){let n=readValidateOption(t),r=interpret(readDocument(e));return n&&validateGraph(r),r}function attachFieldSchemas(e,t){return interpret(readDocument(serializeSchema(e)),t)}export{U as SCHEMA_DOCUMENT_VERSION,attachFieldSchemas,parseSchema,serializeSchema};
|
|
2
2
|
//# sourceMappingURL=json.mjs.map
|